Skip to content
I'm Son
LinkedIn

How to print a html table to PDF format in React

ReactPrint, printPDF, Javascript, ExportPDF1 min read

Use lib html2pdf.js with custom format avoid break page & pdf quality

const html2pdf = require("html2pdf.js");

Your table component

<div id="print_pdf_table">
<ExamOverviewParticipantTable
participants={participantsData} // List of participant will render to the table.
/>
</div>
const handleDownloadPDF = async (): Promise<void> => {
window.scrollTo(0, 0);
const domElement = document.getElementById("print_pdf_table") as any;
const filename = `exam-overview-participant-${formatDate(
new Date().toDateString()
)}.pdf`;
var opt = {
margin: [20, 20, 20, 20],
filename,
image: { type: "jpeg", quality: 1 },
html2canvas: {
dpi: 192,
scale: 4,
letterRendering: true,
useCORS: true,
},
jsPDF: { unit: "pt", format: "a4", orientation: "p" },
};
html2pdf()
.set(opt)
.from(domElement)
.toPdf()
.get("pdf")
.then((pdf: any) => {
var totalPages = pdf.internal.getNumberOfPages();
for (let i = 1; i <= totalPages; i++) {
pdf.setPage(i);
pdf.setFontSize(10);
pdf.setTextColor(0);
pdf.text(
Math.round(pdf.internal.pageSize.width / 2),
pdf.internal.pageSize.height - 10,
i + "/" + totalPages
);
}
})
.save()
.then(() => {
domElement.style.display = "none";
});
};

Explain:

html2canvas: {
dpi: 192,
scale: 4,
letterRendering: true,
useCORS: true,
},

Page break & quality of PDF file take me a bunch of time. Then I adjust dpi: 192 & scale:4