2
votes

I need to generate a PDF report from a table and I am using jsPDF along with jsPDF-autotable. I know it's very simple to generate a PDF file with jsPDF and I believe that I am following the exact steps mentioned on jsPDF documentation page, but I haven't got any success so far. I have also gone through many similar questions but none seems to be working for me.

Here is how I have imported jsPDF and jsPDF-autotable in html head tag:

<!-- Js PDF -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.3.0/jspdf.umd.min.js"></script>
<!-- Js PDF Auto Table -->
<script src="https://cdn.jsdelivr.net/npm/jspdf-autotable@3/dist/jspdf.plugin.autotable.min.js"></script>

Here is my html code code for the button which should trigger a JavaScript function:

<div class="col text-end">
        <button type="button" class="btn btn-secondary" id="btnGenerateReport" onclick="prepareReport()">
            Generate Report
        </button>
</div>

Here is the JavaScript function which should just generate a PDF file based on a table:

function prepareReport() {
    var doc = new jsPDF();
    doc.autoTable({ html: '#reportTable' });
    doc.save(stationSelected + '_' + dateSelected + '.pdf');
}

And here is the console error I am getting:

reports.js:180 Uncaught ReferenceError: jsPDF is not defined
at prepareReport (reports.js:180)
at HTMLButtonElement.onclick (reports:213)

I would truly appreciate all the help I can get. Thanks.

1

1 Answers

1
votes

The issue is in your function:

function prepareReport() {
    var doc = new jsPDF();
    doc.autoTable({ html: '#reportTable' });
    doc.save(stationSelected + '_' + dateSelected + '.pdf');
}

Importing this module using the tag like you are doing, after reviewing the jsPDF project repo, exports the global variable as jspdf, not jsPDF.

So the correct working version should be:

function prepareReport() {
    var doc = new jspdf.jsPDF();
    doc.autoTable({ html: '#reportTable' });
    doc.save(stationSelected + '_' + dateSelected + '.pdf');
}

Note that this code alone is not enough, because stationSelected and dateSelected are not defined. You should also provide definitions for these values.

Live codepen working example.