Search code examples
javascriptjspdfjspdf-autotable

jsPDF with AutoTable not working - Possible JavaScript issue


I have a simple example table that I want to download as a PDF. I followed the AutoTable document on getting setup here: https://github.com/simonbengtsson/jsPDF-AutoTable

I didn't know how to create the actual download hyperlink so I tried something with JavaScript and am getting a ReferenceError: $ is not defined

I would prefer to use a standard hyperlink.

My code is as follows:

<table id="myTable">
  <tr>
    <th>Firstname</th>
    <th>Lastname</th>
    <th>Age</th>
  </tr>
  <tr>
    <td>Jill</td>
    <td>Smith</td>
    <td>50</td>
  </tr>
  <tr>
    <td>Eve</td>
    <td>Jackson</td>
    <td>94</td>
  </tr>
</table>

<button id="downloadPdf">Download Table as PDF</button>

<script src="js/jspdf.min.js"></script>
<script src="js/jspdf.plugin.autotable.js"></script>

<script>
$("#downloadPdf").click(function(){
    var doc = new jsPDF()
    doc.autoTable({ html: '#myTable' })
    doc.save('table.pdf')
})
</script>

Solution

  • You have to import jquery file, working example - https://jsfiddle.net/nishantj/bja0fnve/

    It's downloading a pdf, working as expected. Used the cdn versions of the scripts involved.

    $("#downloadPdf").click(function(){
        var doc = new jsPDF()
        doc.autoTable({ html: '#myTable' })
        doc.save('table.pdf')
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.5.3/jspdf.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf-autotable/3.5.6/jspdf.plugin.autotable.min.js"></script>
    <table id="myTable">
      <tr>
        <th>Firstname</th>
        <th>Lastname</th>
        <th>Age</th>
      </tr>
      <tr>
        <td>Jill</td>
        <td>Smith</td>
        <td>50</td>
      </tr>
      <tr>
        <td>Eve</td>
        <td>Jackson</td>
        <td>94</td>
      </tr>
    </table>
    <button id="downloadPdf">Download Table as PDF</button>