When I first faced this issue, we had an analytics page, which we wanted to convert into a pdf. My instinct was to add a print.css file and let the browser handle all the dirty work. Long story short, this doesn’t work.

With a print specific stylesheet, I found myself nullifying most of my web specific styles. The end result was not much appealing either. Also, it’s hard to style contents of a PDF as html. What renders fine in the browser looks terrible on a PDF.

We started generating PDFs on server side, using a PhantomJS instance. You can see this server side approach in action at PFRepo : https://pfrepo.me. It’s used to generate pdf version of web resumes)

A better way is to render pdf directly on the frontend. The client side approach is fast (nothing to transmit over network), has less moving parts (no headless browsers) and precise. It also lets you continue to design html instead of thinking in terms of PDF.

Generating a pdf on the client side is a 3 step process :

Convert the DOM into svg

Convert the svg into png

Convert the png into pdf

I’m using React in this example, but the same approach can work with Angular, Vue or any other frontend system. We just need vanilla js.

In the IDE below, you can see two rendered pages. One assuming that our content fits on a single page, and the other where the size of the content might be dynamic and need more that one pages.

Step 1: Convert the A4 DOM into svg

html2canvas is a good library to convert DOM to svg. The api is fairly simple.