Sunday, June 28, 2009

Rails view: Export to pdf

This method exports html views in PDF using the exact same CSS and HTML you display on your site. This means that you don't need an extra effort in reformating everything to look nice on a PDF file.

This tutorial is mainly based on the method described by Jim Neath (site) with the necessary windows tweak.

1. Install

Download and install PrinceXML

Install the princely plugin (interface between Prince and rails)

 script/plugin install git://github.com/mbleigh/princely.git

2. Tweaking for Windows

The following trick is necessary to make it work under Windows.

Change the path of the application in the file \vendor\plugins\princely\lib\prince.rb with the following line :

@exe_path = "C:\\Program Files\\Prince\\Engine\\bin\\prince" .chomp

the old line was : @exe_path = `which prince`.chomp

Add

pdf.binmode #this is new

under the line where you see:

pdf = IO.popen(path, "w+")

That should be ok after this.

3. Usage

In your views:

Copy the view you want to print, modify it to display only what you want to print (using CSS and HTML like a normal view) and rename it (example : show.pdf.erb instead of show.html.erb)

In your controller:

edit the corresponding action to add a new render method for the PDF file

# GET /post/1
# GET /post/1.xml
def show
@post = Post.find(params[:id])

respond_to do |format|
format.html # show.html.erb
format.xml  { render :xml => @post }
format.pdf do
render :pdf => "filename", :stylesheets => ["application", "prince"], :layout => "pdf"
end
end
end

That's it

When you call, /posts/show/5.pdf you get a pdf file of the record id you have called.
In my example, the record id was 5.

More information
Thanks to mikedc55 for the tweak on windows.

1 comment:

Admiral Adney said...

I was seeking for ruby on rails development and set down up on your mail and i should state thanks for distributing such helpful information.