Search code examples
angularhtml2canvas

How to reduce html2canvas export file size


I'am using html2canvers library to create invoice and download as PDF(A4 size PDF). Downloaded file size was large (7MB - 13MB) always. Is there a way to reduce the file size and maintain the quality of the PDF.

 public downloadPDF(order_id: string): void {            
        html2canvas(this.invoicepdf.nativeElement).then(function (canvas) {
            var wid: number
            var hgt: number
            var img = canvas.toDataURL("image/png", wid = canvas.width, hgt = canvas.height);
            var hratio = hgt / wid
            var height = 210 * hratio
            var pdf = new jsPDF("p", "mm", "a4");
            var imgData = canvas.toDataURL('image/png', 1.0);
            pdf.addImage(imgData, 'PNG', 0, 0, 210, height);
            pdf.save(order_id + '_Invoice.pdf');           
        });            
    }

Solution

  • With jsPDF, using addImage() function, it's possible to compress a generated JPEG (with the values 'NONE', 'FAST', 'MEDIUM' or 'SLOW'). Cf.: https://rawgit.com/MrRio/jsPDF/master/docs/module-addImage.html

    So, by doing this, you can reduce the export file size:

    // ...
    var img = canvas.toDataURL("image/jpeg", [...])
    // ...
    pdf.addImage(imgData, 'JPEG', 0, 0, 210, height, 'someAlias', 'FAST');
    // ...