I’m trying to generate a PDF from HTML content using jspdf and html2canvas, but I’m encountering some issues with the generated PDF. Here’s the relevant code:
function printDivAsPdf(divId, filename = "generated-pdf") {
const printContent = document.getElementById(divId);
if (!printContent) {
console.error(`Div with ID '${divId}' not found.`);
return;
}
const printHTML = `
<html>
<head>
<title>Print Preview</title>
<style>
@media print {
body {
-webkit-print-color-adjust: exact;
color-adjust: exact;
}
#${divId}, #${divId} div {
page-break-inside: avoid;
margin: 0;
padding: 0;
}
${this.getAllStyles()}
${this.getMediaQueryStyles()}
}
</style>
</head>
<body>
${printContent.outerHTML}
</body>
</html>
`;
const pdf = new jsPDF({
orientation: "portrait",
unit: "mm",
format: "a4",
});
const options = {
scale: 2,
useCORS: true,
logging: true,
};
html2canvas(printContent, options).then((canvas) => {
const imgData = canvas.toDataURL("image/jpeg", 1.0);
const pdfWidth = pdf.internal.pageSize.getWidth();
const pdfHeight = (canvas.height * pdfWidth) / canvas.width;
let currentPosition = 0;
let imgHeightLeft = canvas.height;
const pageSize = pdf.internal.pageSize.getHeight();
while (imgHeightLeft > 0) {
if (currentPosition > 0) {
pdf.addPage();
}
const heightToPrint = Math.min(imgHeightLeft, pageSize);
pdf.addImage(imgData, "JPEG", 0, -currentPosition, pdfWidth, pdfHeight);
currentPosition += heightToPrint;
imgHeightLeft -= heightToPrint;
}
pdf.save(`${filename}.pdf`);
});
}
The function works, but I’m encountering a problem where the generated PDF contains blank pages. I suspect that the issue might be related to the canvas height or page breaks, but I’m not sure how to fix it.
Any suggestions on how to troubleshoot or resolve this issue would be greatly appreciated. Thanks in advance!
I tried make an html element(printHTML in the function) but couldn’t use it to download .
Rahul Patnaik is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.