Pdf Writer and Rails Pdf

Yesterday, while trying an elegant way to add pdf functionalities to our last application, I discovered RailsPdf that acts on top of the well known pdf-writer gem adding the amazing ability to move all the pdf-writer instruction in a .rpdf view file!

By act in this way you are able to keep your controller clean and to add your pdf rendering among with all the others (rss,ics, ecc..) by using the respond_to block

Let’s view a sample of this:


We first need to install both RailsPdf and PdfWriter, to do this just point your terminal inside a fresh rails application and write:

gem install pdf-writer ruby script/plugin install svn://rubyforge.org/var/svn/railspdfplugin/railspdf


Next we have to add a line in our environment.rb file that tells our application how to work with .pdf files:

Mime::Type.register "application/pdf", :pdf

First try

Let’s now create a controller with an action that can render both .html and .pdf formats:

class DemoController < ApplicationController

def index

respond_to do |wants|

wants.pdf { render :template=>’pdfindex’ }





Now we have just to write our ‘pdfindex.rpdf’ file; railspdf plugin help us giving in our view a ‘pdf’ variable that is an instance of PDF::Writer that we can use to create our output:

pdf.select_font "Times-Roman" pdf.text "Hello word!", :font_size => 72, :justification => :center

Save the pdf to a file

If we need to store somewhere the pdf just created we can use the render_to_string function as follow:

# this variable tell railspdf plugin not to add header infos while creating the pdf

@rails_pdf_inline = 1

f = File.open(File.join(RAILS_ROOT,"pdf","demopdf"), ‘w’)

f.write(render_to_string :template=>’pdfindex’)



RailsPdf is a very simple yet useful plug-in that helped me keep my controllers clean. Hope it will be useful to you too.

Leave a Comment