On and off over the last few months, we have been searching for a solution to print a webpage, formatted correctly by a print CSS file, into a PDF file. One of our web projects uses print CSS heavily in order for users to have a “pretty” view of content. The trouble was that some of those pages, by necessity, were hundreds of pages long, with some rather complex/heavy CSS formatting. This caused some clients with old/slow printers to complain, citing very long print times. Upon further inspection at the client’s sites, we found that the printers were choking on the data. We didn’t want to split up the pages, or radically change this workflow, so we embarked on a journey to find a way to easily create PDF files of these troublesome pages.
Being a PHP shop, we did a quick search for ‘php html to pdf’, which gave us plenty of results. It seemed that the leading product in this area was wkhtmltopdf. However, after playing around with the product and attempting an installation on an Ubuntu server, we saw a lot of dependencies being installed on the machine, and encountered numerous errors trying to generate the PDF. There were other concerns regarding the age and activity level of the project. We had one strong contender in wkhtmltopdf, but decided to continue researching.
Our attention quickly turned to PrinceXML after viewing some samples and some great reviews, but were ultimately unable to justify the rather steep server license fee. DocRaptor was also considered, and was more reasonable, but we tend to shy away from third-party web services only because we focus on open-source software. With limited research, these two seemed to be very good.
After all this, we discovered the excellent PhantomJS product. The binary was easily installed on the server with no additional dependencies required, and came with a great deal of example code, including a working ‘print to PDF’ function out-of-the-box. With some minor tweaks, we customized the script for our use case, and had a PDF copy of our webpages in minutes. PhantomJS has been around since 2011 and is used by a variety of open source products, listed on their website. In a later post, we will detail how we integrate PhantomJS with Yii, expanding on the PhantomJS Yii extension.