Generating PDFs from Web Pages on the Fly with jsPDF
The Portable Document Format has been one the major innovations in the fields of desktop publishing and office automations.
It’s widely used in web publishing too, but unfortunately very often in wrong ways – like using it to replace contents that should have been built with HTML. This causes many problems regarding usability, accessibility, SEO and so on.
However, there are some cases in which PDF files are required: when a document needs to be archived and must be used outside the web (for example an invoice) or when you need a deep control on printing.
It was just the need to control printing that brought me to research a way to easily generate a PDF.
The purpose of this article is not to simply explain how a PDF can be created (there are many easy way to do this), but also to focus on the circumstances where a PDF file can solve a problem, and how a simple tool like jsPDF can help with this.
Dealing with Printing
Anyone who has dealt with CSS printing rules knows how difficult it is to achieve a decent level of cross-browser compatibility (take a look, for example, at the Page-break support table at Can I Use). Therefore, when I need to build something that must be printed, I always try to avoid CSS, and the simplest solution is to use PDF.
I’m not talking here about the simple conversion of HTML to PDF. (I’ve tried several tools of that type, but none of them has fully satisfied me.) My goal is to have complete control over the positioning and size of elements, page breaks and so on.
When I started my project, some months ago, I searched for a JS library, and finally I found two candidates: jsPDF and pdfmake. pdfmake seems to be well documented and very easy to use, but since it was a beta version, I decided for jsPDF.
PDF Building with jsPDF
The jsPDF documentation is fairly minimal, consisting of a single page along with some demos, and a little more information in the source file (or in its jsDoc pages), so keep in mind that using it for complex projects can be a little hard in the beginning.
Anyway, jsPDF is very easy for basic PDF files generation. Take a look to a simple “Hello World” example:
This HTML page generates a one-page PDF file and saves it on your computer. First you have to link to the jsPDF library (in this case, from cdnjs.com), then a jsPDF instance is created, a line of text is added, and the result is saved as
Note that I’ve used the 1.0.272 version, and that it’s not the latest: at the time of writing this, the most recent version is the 1.1.135, but it has many issues, so I am still using the previous one.
You can see how extremely simple it is to build a basic PDF file (you can find more examples at the jsPDF site).
Continue reading %Generating PDFs from Web Pages on the Fly with jsPDF%