I am using jspdf and canvas to download specific div in my page as pdf but it takes 2 or 3 seconds and my client want it to be fast to download, is there any way to speed up this process, or to decrease the file size because it's 8MB but?
the code
$('#print').click(function (e) {
e.preventDefault();
let HTML_Width = $(".report").width();
let HTML_Height = $(".report").height();
let top_left_margin = 1;
let PDF_Width = HTML_Width + (top_left_margin * 2);
let PDF_Height = (PDF_Width * 1.5) + (top_left_margin * 2);
let canvas_image_width = HTML_Width;
let canvas_image_height = HTML_Height;
let totalPDFPages = Math.ceil(HTML_Height / PDF_Height) - 1;
html2canvas($(".report")[0]).then(function (canvas) {
let imgData = canvas.toDataURL("image/png", 1.0);
let pdf = new jsPDF('p', 'pt', [PDF_Width, PDF_Height]);
pdf.addImage(imgData, 'JPG', top_left_margin, top_left_margin, canvas_image_width, canvas_image_height);
for (let i = 1; i <= totalPDFPages; i++) {
pdf.addPage(PDF_Width, PDF_Height);
pdf.addImage(imgData, 'JPG', top_left_margin, -(PDF_Height * i) + (top_left_margin * 4), canvas_image_width, canvas_image_height);
}
pdf.save("Report.pdf");
$(".html-content").hide();
});
});
There's 2 components that made up the bulk of the performance. The amount of data and the compression.
The amount can be reduced by selecting a lower DPI - 72 for screen-read documents is reasonable, but it might not be great if the intention is print.
For html2cavas we ended up with a scale of 3.125 to get this pixel density down. (It's part of the options parameter). I can't recall specifics, this might result in around 96dpi.
For the compression, you can play around with the options, we ended up using 'FAST' compression on pdf.addImage.