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
1 comments:
Awesome, thanks!
I was struggling with getting the pdf generation to work, till I saw in your example that the template can be passed as a parameter in the respond format block :-)
Looks like you have stopped blogging after a 3 month burst back in early 2010; you should get back into it! More people might get their problem resolved from one of your blogposts, thanks to google and serendipity.
Post a Comment