Hossam Ayman
Hossam Ayman

Reputation: 13

Export an HTML table as a PDF using jsPDF library

I'm trying to export an HTML table as a PDF using the jsPDF library. I have added the necessary script tags in my HTML file and included the jsPDF library using a CDN link. When I click on the export button, I get an error message in the console that says "Uncaught ReferenceError: jsPDF is not defined at HTMLButtonElement. (app.js:85:15)". The line of code that is causing the error is const doc = new jsPDF();. I'm unsure why the library is not being recognized and would appreciate any help resolving this issue.

I have included the following script tag in the head of my HTML file to include the library and did also try it before the body tag but it didn't work:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>

const exportPdfBtn = document.getElementById("export-pdf-btn");
exportPdfBtn.addEventListener("click", () => {
  // Create a new jsPDF instance
  const doc = new jsPDF();
  // Get the table HTML element
  const table = document.getElementById("streets-table");

  html2canvas(table).then((canvas) => {
    // Get the canvas data as an image URL
    const imgData = canvas.toDataURL("image/png");

    doc.addImage(imgData, "PNG", 10, 10, 180, 0);

    // Save the PDF document
    doc.save("table.pdf");
  });
});

What could be causing this error and how can I fix it?

Any help or guidance would be greatly appreciated.

Upvotes: 0

Views: 900

Answers (1)

Hossam Ayman
Hossam Ayman

Reputation: 13

The problem was that I had not added the html2canvas script to my HTML file.

Upvotes: 0

Related Questions