I am creating a PDF from a DOM file using a combination of html2canvas and jspdf to convert a section of the DOM into an image and then add it to the respective PDF file created.
This is working fine on the desktop browser but is tremendously slow on the mobile browser.
You can test out the issue on a mobile browser by going to the link mentioned below and then selecting on any of the templates, followed by clicking on the download option.
https://countenance-proto.herokuapp.com/resumevariation
Here is the functional code for the respective canvas to pdf conversion.
printTemplate = () => {
const input = document.getElementById("main-document");
html2canvas(input, {
scale: 2
})
.then((canvas) => {
const imgData = canvas.toDataURL('image/png');
const pdf = new jsPDF("p", "mm", "a4", true);
let width = pdf.internal.pageSize.getWidth();
let height = pdf.internal.pageSize.getHeight();
pdf.addImage(imgData, 'PNG', 0, 0, width, height, '', 'FAST');
pdf.save("countenance-resume.pdf");
});
}
I expect it to be at par with the time it takes for the pdf to download on desktop, if not less.
Try using
const imgData = canvas.toDataURL('image/jpeg', 1.0);
pdf.addImage(imgData, 'JPEG', 0, 0, width, height, '', 'FAST');
instead of
const imgData = canvas.toDataURL('image/png');
pdf.addImage(imgData, 'PNG', 0, 0, width, height, '', 'FAST');
As far as I know, jsPDF converts the PNG image to JPEG anyways so it takes longer time for the conversion, this can be avoided if you use JPEG directly.