Ruby On Rails, Design, Simplicity, Web 2.0, Ajax, Mac and Tons of Pizza.

Aug 07

PdfWriter and RailsPdf

Posted by Sandro Paganotti in Ruby on Rails - comments are closed digg this add to delicious

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:

Installation

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

Configuration

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' }
               wants.html
            end
     end 

end

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') 
            f.close

Conclusions

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

Sandro

Comments

  • Emmanuel Oga

    Posted on August 08

    Hi! You can also try ruport. It has not (at least no by default) a templated pdf generation. But it encourages the separation of the pdf generation and the rails code. You can see a basic, complete demo here: http://groups.google.com/group/ruby-reports/browse_thread/thread/19faefcd61f3518d/e1ecf62d40feac7c#e1ecf62d40feac7c Cheers!

Post a comment

Categories:

Tags:

Powered by Mephisto, Valid XHTML 1.1, Valid CSS - Supported by Wave Factory