Showing posts with label pdf. Show all posts
Showing posts with label pdf. Show all posts

Generating PDF from HTML on RoR

Well, historically generating PDF on Ruby on Rails is not an easy task.
We used to use PDF::Writer or Prawn and learn it's syntax to generate PDF.
Now we can generate pdf for every html.erb template that we have, with the help from wkhtmltopdf and wicked_pdf plugin.

I will show you how to generate PDF for every html.erb template on a particular RoR application.

First, you have to have wkhtmltopdf binary.

http://code.google.com/p/wkhtmltopdf/downloads/list

Linux users, you'll want to download the static binary, unless you want to recompile Qt :)
Put that binary somewhere on your machine.

Now on a RoR application, install the plugin:
ruby script/plugin install git://github.com/mileszs/wicked_pdf.git
ruby script/generate wicked_pdf

Edit config/initializers/wicked_pdf.rb file so it is pointing to the wkhtmltopdf binary on your machine. This is the file content on my machine:

WICKED_PDF = {
  #:wkhtmltopdf => '/usr/local/bin/wkhtmltopdf',
  #:layout => "pdf.html",
  :exe_path => '/usr/bin/wkhtmltopdf'
}

Ok, now all the preparations has been done, let me show you how to use it on a controller.

def new
  @movie = Movie.new
  respond_to do |format|
    format.html # new.html.erb
    format.pdf do
      render :pdf => "file_name",
             :template => "movies/new.html.erb"
    end
    format.xml  { render :xml => @movie }
  end
end

Here is the sample file generated:
file_name.pdf