Thursday, August 8, 2013

wicked_pdf and stylesheets

There are several articles showing how to use wicked_pdf on a Ruby on Rails application, so I am not going to exlain that here. Setup is quite simple, and the gem is just awesome.

There are however a few things to notice:

Outputs on osx and ubuntu can be inconsistent

If you are using wkhtmltopdf-binary-11 on osx in development and the same binary in production on a ubuntu system the output of the pdf is most likely to be quite different. Solution: Develop on your local computer, fine-tune using an Ubuntu machine in Virtualbox.

Stylesheets don't 'behave'

You might get mixed results when using linked stylesheets. The simple solution is to inline your pdf or print stylesheet. Put this in your pdf layout file:
<style type="text/css">
<%= Rails.application.assets.find_asset('pdf_print.css').to_s.html_safe %>
This way your stylesheet will be inline, and all linking issues with wkhtmltopdf is resolved. If you have full paths for your assets, that will sometimes work as well. (e.g. if they are hosted on a cdn), but to my experience, inline CSS is more consistant when using wkhtmltopdf.

After writing this blog post, I found this repository:
It is a fully working example of generating pdf with linking to the assets instead of inline css. It is a fairly basic example, but it shows how to setup wicked_pdf with linked stylesheets.