Tao Programmer

"What I follow is Tao - beyond all techniques! When I first began to program I would see before me the whole problem in one mass. After three years I no longer saw this mass. Instead, I used subroutines. But now I see nothing. My whole being exists in a formless void. My senses are idle. My spirit, free to work without plan, follows its own instinct. In short, my program writes itself. True, sometimes there are difficult problems. I see them coming, I slow down, I watch silently. Then I change a single line of code and the difficulties vanish like puffs of idle smoke. I then compile the program. I sit still and let the joy of the work fill my being. I close my eyes for a moment and then log off."

Tao of Programming - 4.4

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