Tip: Instead of using jspdf, try utilizing pdfmake [https://www.npmjs.com/package/pdfmake]
(Why settle for a buggy tool when there's a superior one available with enhanced features and easier coding?
Admittedly, no library is flawless. However, some are more bug-ridden than others, especially when it comes to specific functions or uses. For instance: In my scenario of converting an HTML table to PDF in TypeScript, I experimented with jspdf-autotable
but encountered issues)
Now, my task has become simpler. No longer do I need a screenshot tool like html2canvas
to capture all table contents as images. Gone are the concerns about screenshot quality, resizing, etc. Moreover, I have tangible data in PDF format that can be copied, rather than just being a static image.
Let’s get started.
Get pdfmake:
(In my case, it was installed for Angular)
npm i pdfmake --save
TypeScript Code:
Import It:
import pdfMake from "../../../../node_modules/pdfmake/build/pdfmake";
import pdfFonts from "../../../../node_modules/pdfmake/build/vfs_fonts";
pdfMake.vfs = pdfFonts.pdfMake.vfs;
Develop Function:
Create a function for downloading the desired PDF file upon clicking a download button
peopleExportToPdf() {
let docDefinition = {
content: [
{
table: {
body: [
[{ text: 'SL#', bold: true }, { text: 'Name', bold: true }, { text: 'Age', bold: true }],
[{ text: 'Bold value', bold: true }, 'Val 2', 'Val 3'],
]
}
}]
}
docDefinition.content[0].table.body.pop(); //remove the unnecessary 2nd row
let slno: number = 1;
for (let p of this.people) {
docDefinition.content[0].table.body.push([{ text: slno.toString(), bold: true }, p.name, p.age.toString()]);
slno = slno +1;
}
pdfMake.createPdf(docDefinition).download('Report.pdf');
}
Quick Tips:
- Align your table columns - SL#, name, age - according to your requirements.
- If dealing with non-string data, ensure conversion to string (I had to convert age to string to avoid errors).
- I added and removed an extra row due to complications. You might encounter similar challenges (If you have a better solution, please share!)
Acknowledgment:
I received guidance from the following sources:
- How to convert html table to pdf using pdfmake
- https://github.com/bpampuch/pdfmake/issues/1046