How To Export Html To Pdf (multiple Pages) Using Jquery?
I want to Export HTML to PDF using jQuery that is working fine but only for when HTML will finish in single page PDF. But I'm facing difficultly export html to PDF when there is lo
Solution 1:
I found 2 issues...
- Better use the latest version of pdfMake. You were using 0.1.22... I used 0.1.68 found on cdnjs.
- Seems like pdfMake isn't able to "split" an image and spead to several pages... So you have to provide some already splitted chunks. Fortunately, I found a SO answer about this specifically... Which I very slightly adapted here.
You can choose a predefined page format, like letter or A4, etc as a pdfMake param. See possible options.
Then you will have to adjust the height of the splitted image chunks by try/fail. Here, I found that 775px seemed good for a letter page... But only tried it with the HTML you provided.
SO snippets are disallowing downloads. So, useless to make it a snippet but you can check my CodePen.
Some documentation:
// Slightly adapted function from this SO answer: https://stackoverflow.com/a/21937796/2159528// It now returns the objects formatted for pdfMakefunctiongetClippedRegion(image, x, y, width, height) {
var canvas = document.createElement("canvas"),
ctx = canvas.getContext("2d");
canvas.width = width;
canvas.height = height;
// source region dest. region
ctx.drawImage(image, x, y, width, height, 0, 0, width, height);
return {
// Those are some pdfMake paramsimage: canvas.toDataURL(),
width: 500
};
}
$("body").on("click", "#downloadPDF", function () {
html2canvas($("#downloadPDFData")[0], {
onrendered: function (canvas) {
// split the canvas produced by html2canvas into several, based on desired PDF page heightlet splitAt = 775; // A page height which fits for "LETTER" pageSize...let images = [];
let y = 0;
while (canvas.height > y) {
images.push(getClippedRegion(canvas, 0, y, canvas.width, splitAt));
y += splitAt;
}
// PDF creation using pdfMakevar docDefinition = {
content: images,
pageSize: "LETTER"
};
pdfMake.createPdf(docDefinition).download("report.pdf");
}
});
});
Post a Comment for "How To Export Html To Pdf (multiple Pages) Using Jquery?"