Pesquisar neste blogue

sexta-feira, 29 de junho de 2018

Generating PDF from a webpage using JavaScript

A requisite for a project i was working on a while back was to generate a reader like version of a webpage and export it to PDF.
I started by getting a printable format for the webpage which was not that difficult, just removing some classes and adding some css with Jquery.

Now came the fun part.

What if i could do all of this on the client side, using JavaScript.



Imagine you're the server and your project manager is the browser. What a fine day it would be when a project manager interrupts you with something he/she could do.
Moreover i would save some cpu cycles on the server and learn something new in the process.

So with the help of stackoverflow my journey began.
What do i need :

  • Something to generate PDF in JavaScript -I came across jsPDF it has a very simple API and is really simple to use.
  • Now i need something that can make like a screenshot of the element . Again with the help of StackOverflow i came across  - html2canvas .

Using both together is really simple

        html2canvas($("#canvas"), {
            onrendered: function(canvas) {         
                var imgData = canvas.toDataURL(
                    'image/png');              
                var doc = new jsPDF('p', 'mm');
                doc.addImage(imgData, 'PNG', 10, 10);
                doc.save('sample-file.pdf');
            }
        });



From post at stackoverflow.com

I do recommend taking a look at the of jsPDF Examples
If your files are coming out a bit on the large size you may also compress it -jsPDF constructor has a flag to enable compression. My pdf came from about 14 megs to 240kb.




 The trickiest bit happens when your image is bigger than a page. In that case you must treat your image like a sliding window, effective splitting the image through several pages. A good example code can be found on

Hopefully you find this useful, i have tried to gather most of the sources i went through to learn.
Credit to the devs @ stackoverflow .


And thanks to those that :