Javascript : Convert HTML + CSS to PDF. Print HTML in Seconds
A personal project I’m currently working on involves turning a styled HTML node tree into a printable PDF asset on client side.
I spent a long time searching for the definitive solution and went through a lot of hardships.
I will share with you my solution, which I believe is very easy to use, and I’ll go about pros / cons of other approaches.
It will take only two minutes of implementation.
Setup
FYI : I work with React so I’m using
npm / yarn
to add libraries using the ES6import
statement. Not using those package managers, you could integrate libraries using a simple<script></script>
tag.
It will take you :
- Two Javascript libraries running on client side.
- 5 actual lines of code in Javascript
It requires :
- Basic Javascript knowledge
- jsPDF :
yarn add jspdf
- html2canvas :
yarn add html2canvas
Snippet
The process is as follows :
- The HTML node tree you want to transform into a PDF is first transformed into a canvas using
html2canvas
(line 4) - Then, an empty PDF structure is created using an A4 format. By the way, we tell jsPDF to use
mm
as the unit for the next operations (line 5) - Almost finished, we turn the canvas into a PNG image using
canvas.toDataURL('image/png')
(line 6). - This PNG image is then pasted onto the empty PDF at the coordinates
(0,0)
, resized at(211,298)
(line 6). A4 format is 210 mm wide, and 297 mm tall so I’m using one more millimeter when pasting the image to avoid white strips on edges. - Eventually, we prompt the browser to download the newly generated PDF using
pdf.save(filename)
(line 7).
The other function taking quality
as a parameter starting at 1 (default quality) allows you to get much more sharper PDF with an SVG look.
This quality
is just the scale used to first turn the HTML node tree into a canvas. The greater it is, the sharper and the heavier the PDF will get (using quality = 4
on a complex node structure of mine produces 60 MB PDFs, while quality = 1
produces 800 KB PDFs).
Considerations
This technique lets you print HTML based PDFs in seconds using 5 lines of code.
It has been tested on multiple browsers and as of the 1st of August 2018, no issue was encountered using my Chrome browser.
Nevertheless, consider the following few points :
- It is an image into a PDF. Not actual text.
- Those generated PDF files won’t let you select / copy / paste text as there isn’t text inside of it. Same goes for hyperlinks, etc.
- Your PDFs might get very heavy as the quality increases.
Still :
- Dead easy implementation
- Neither code reorganization nor tweaking.
- Works like charm on client side, leveraging on two battle-tested libraries (jsPDF and html2canvas).
- Using 3 or 4 as the
quality
modifier, your PDFs will look like SVG files. Ultra sharp with no blurriness. - Not many libraries allow a direct HTML + CSS to PDF conversion.