On several of the projects that I maintain we have to create a PDF export of something (usually reports and invoices). I always find that the quickest, least painful way of doing this is to use wkhtmltopdf to convert an HTML page to a PDF. Until recently, it's been an abandoned project (I've been using 0.11 for years) and I'm happy to say that it's been updated to 0.12 recently! I also learned a couple new things.

Run the process through x11

I've run into a couple of problems with pages not rendering correctly and in order to fix them I had to run the process with an X11 server. I don't want a GUI running on my server so I run the process through xvfb.

First you need to install the executable:

## Unbuntu
sudo apt-get install xvfb
## RHEL
sudo yum install xorg-x11-server-Xvfb

And then the command line is a little more complicated:

xvfb-run --server-args="-screen 4, 1280x1024x24" wkhtmltopdf --use-xserver http://www.google.com/ output.pdf

Debug Javascript

If you're like me and have to run some JavaScript in order to generate graphs you can run into problems that are hard to troubleshoot because of the headless nature of wkhtmltopdf. You can add the --debug-javascript option and it will print any console functions to stderr.

xvfb-run --server-args="-screen 4, 1280x1024x24" wkhtmltopdf --use-xserver --debug-javascript http://www.google.com/ output.pdf

Specify print media type

If you run wkhtmltopdf normally it will create a PDF of the screen exactly as you see it. This is nice but you can also specify that wkhtmltopdf set the media type to print (@media print) so you can specify a different look for the PDF:

xvfb-run --server-args="-screen 4, 1280x1024x24" wkhtmltopdf --use-xserver --print-media-type http://www.google.com/ output.pdf

The other nice thing about this is that then if someone prints the page it will also have a nice layout.