How to convert HTML views into PDF in Rails

One of the most popular programs to convert HTML to PDF is wkhtmltopdf. And in this post, I am going to show you how to use wicked_pdf gem to quickly export your views into PDF using this program.

First, you would need to install wkhtmltopdf program in your platform (Linux or OSX). I am using Mac OSX so I can install it thanks to this post http://thelazylog.com/posts/how-to-install-wkhtmltopdf-on-osx-august-2014-903b6fe2-36ca-4093-a2c3-809f6d4f5a54. However, the installation instruction in my post earlier was not not enough if you want to use advanced features such as adding Header/Footer to your PDF. You need to install wkhtmltopdf version with qt patched in order to use these advanced features. Thus I recommend you to download and compile the source by following the steps in this blog: http://natepinchot.com/2014/01/31/building-static-wkhtmltopdf/.

Warning: These sources are big (about 1GB) and it would take a while for downloading and compiling, so have a cup of coffee in front of you before doing that :)

After installing wkhtmltopdf, make sure it's installed correctly by typing the following command into your terminal

wkhtmltopdf --version

You should see the version of wkhtmltopdf program you have installed. In my Mac, it looks something like this

wkhtmltopdf 0.12.2-dev (with patched qt)

Now, let's go back to your Rails app. I am going to use a gem called wicked_pdf. This is a very easy but powerful gem. It basically convert your input into corresponding options when calling wkhtmltopdf program. Add the following line to your Gemfile

gem 'wicked_pdf'

and run bundle install to update

In this example, I assume that I have a posts_controller in my app and I want to export a certain post to PDF. Here is how I do it

class PostsController < ApplicationController
  def show
    @post = Post.find(params[:id])
    respond_to do |format|
      format.html
      format.pdf{
        render pdf: @post.id
      }
    end
  end
end

Of course, you would need to create a template for PDF format at views/posts/show.pdf.erb
And now, when you go to /posts/1.pdf, you will see your PDF in the browser. Simple, right?

You can read more about several advanced config with this gem here: https://github.com/mileszs/wicked_pdf

Have a great day!