Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to speed up PDF download on mobile browsers using a combination of JSPDF and html2canvas?

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.

like image 752
tejaz Avatar asked Oct 17 '25 17:10

tejaz


1 Answers

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.

like image 183
GauthamK Avatar answered Oct 20 '25 08:10

GauthamK



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!