PhantomJS for HTML to PDF Rendering

Several years ago, I was assigned the task of generating large PDFs from HTML using dompdf.  The rules were simple, write the HTML and corresponding CSS, pass this off to dompdf and it spits out the content in PDF format, or so I thought.  But, the results were far from fantastic.  CSS was barely supported, element position was mostly ignored, images never seemed to display correctly, and rendering time was abysmal.  We ended up writing two completely separate HTML documents, one for display in the browser and one for conversion to dompdf.

Fast-forward to present day, I found myself once again needing to convert HTML to PDF and dreaded returning to using dompdf or its ilk.  I took to the internet in search of alternatives.  Low and behold, I found PhantomJS, the stand-alone headless webkit.  I was astonished to find that, not only did PhantomJS fully support HTML5 and CSS3 specifications, it also supports JavaScript and SVG!  A headless webkit gives you all the power of your favorite web browser, it just doesn't display anything.  This makes it the perfect tool for integrating with your website's backend.  PhantomJS includes a convenient JavaScript API which makes it easy to manipulate the source just as you would using a browser's DOM.  I was able to take my already complete HTML document (which included a client-side generated google chart), pass it off to PhantomJS's rasterize example script, and it spit out a beautifully rendered PDF in no time at all exactly as it appeared in my browser.

One down-side is that PhantomJS is a stand-alone application.  It must be compiled and installed on the system you want to use it on.  Fortunately, there are some very kind volunteers, who take it upon themselves to compile binaries for some of the most common operating systems.  In my case, I found a compatible linux binary, copied it to the server, and it was ready to go.

Rendering is one of many features of PhantomJS, but this one alone makes it stand above it's predecessors.  Next time you need to render your web content, take a look at PhantomJS.  You will not be dissapointed!

Want to Learn More?

This is just a sample of what we can do. We have 15 years of experience working in nearly every technology and industry. Whatever you are doing, we've done it and are prepared to tackle your project. Reach out and we will discuss it with you.