ParsaLabs | Blog

A publication about the web and more.

PDF Generation With WKHTMLTOPDF

| Comments

Recently, I’ve had the need to be able to generate PDF files from HTML content. Programmatically generating PDF used to be a hard problem in software development. But there are some utilities that has made this task much easier to accomplish. The most stable I have found so far is a shell utility called wkhtmltopdf. Since I primarily develop apps with Ruby on Rails, there are also a few awesome plugins and gems available that help integrate wkhtmltopdf functionalities into any rails app through ruby APIs. For example: PDFKit, Wicked_pdf, etc. However, you still need to manually install the shell utility yourself, manually. And that’s the tricky part (especially, when you develop and deploy on different platforms). But I managed to finally figure it out, and thought I’d share my recipe in this blog post. Here it goes:

Installing wkhtmltopdf on Mac OS X (for my development)

While many might argue that brew install wkhtmltopdf is the best option (and using homebrew package manager is generally the best option), I had a few issues with it. First of all, it seemed like homebrew installed an older version of wkhtmltopdf binary for me, therefore I was not running the latest binary with all the updates and patches (particularly for QT). And as a result I was faced with many bugs when generating pdf files: for instance, every time my rails app called wkhtmltopdf, an icon would appear in Dock and the application would halt, and I had to manually click on it for execution to resume. Also, I experienced many instances of split text bug in the generated pdf. and more..

So, I decided to install the official Mac OS release:

  • I downloaded the .dmg
  • double-clicked to open it
  • dragged it to Applications folder

and did the following in the terminal:

1
2
cd /usr/local/bin
ln -s /Applications/wkhtmltopdf.app/Contents/MacOS/wkhtmltopdf wkhtmltopdf

Your wkhtmltopdf shell utility should now be installed properly. Test it by restarting the terminal and typing: wkhtmltopdf --help.

Installing wkhtmltopdf on Linux

This is pretty trivial. Just download a linux version of the static binary (for example this one) and place it in a path that’s accessible by your rails app.

Pointing to wkhtmltopdf (in PDFKit config)

Last step is to point to the correct binary for PDFKit to work on both development and production server. Here’s my config:

1
2
3
4
5
6
7
8
9
PDFKit.configure do |config|
  
  if RUBY_PLATFORM.include? "darwin" # My development Mac OSX
    config.wkhtmltopdf = '/usr/local/bin/wkhtmltopdf'
  else
    config.wkhtmltopdf = '/path/to/wkhtmltopdf-static-binary' # customize this for your production app.
  end
  
end

Hope this was useful. :)

Comments