jsPDF Html2Canvas Tutorial to Reduce or Compress File Size of PDF Document in Browser Using Javascript Full Project For Beginners

 

 

function genPDF() {

  html2canvas(document.querySelector(".page"), {scale: "2"}).then(canvas => {

    this.imgFile = canvas.toDataURL("image/jpeg", 0.3);
    var doc = new jsPDF('p', 'mm', 'a4', true);
    doc.addImage(this.imgFile, "JPEG", 5, 0, 210, 297, undefined,'FAST');
    doc.save('Test.pdf');

  });

}

 

 

https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toDataURL

I tried with

canvas.toDataURL( 'image/jpeg', 1.0 );

works well, got size down to 111kb from 2.5Mb.

 

 

As I wasn’t even aware of what Fabric.js was, I’m rewriting this from scratch.

First of all, changing the canvas size should work there. It is working on my example, test it if you can (I will post it below).

I believe that this line of code, wasn’t working:

var imgData = canvas.toDataURL("image/jpeg", 1.0);

I tried changing the quality and it didn’t work. I found here how to fix that. The new code:

var imgData = canvas.toDataURL({
    format: 'jpeg',
    quality: 0.9 // compression works now!
});

So, before that, changing the image size, or any element for that matter, wouldn’t change the final .PDF size, because it was probably being saved with no compression at all.

Here’s my updated sample (try different canvas sizes, if possible):

<!DOCTYPE html>
<html>
<body>
<canvas id="canvas" width="1024" height="768"></canvas>

<script src='jquery-2.1.4.js'></script>
<script src='jspdf.min.js'></script>
<script src='fabric.min.js'></script>
<script src='fabricPdf.js'></script>

</body>
</html>

Here’s the fabricPdf.js file:

function createPdf() {
    var imgData = canvas.toDataURL({
        format: 'jpeg',
        quality: 0.2
    });

    var width = $("canvas").attr('width');
    var height = $("canvas").attr('height');
    var pdf = new jsPDF('p', 'pt', [width,height]);
    pdf.addImage(imgData, 'JPEG', , , width, height);
    pdf.save("download.pdf");
}

var canvas = new fabric.Canvas('canvas');
var image = new Image();

image.setAttribute('crossOrigin', 'anonymous');
image.src = "http://i.imgur.com/eD9pJBy.jpg"; // 625x469
// image.src = "http://i.imgur.com/EDllPEW.jpg"; // 2816x2112

image.onload = function() {

    var fabricImage = new fabric.Image(image, {
      width: 625, height: 469, angle: , opacity: 1
    })

    canvas.add(fabricImage);
    createPdf();

}

Leave a Reply