Entries Tagged 'Ruby on Rails' ↓

How to render a PDF document from a template in Rails

As part of a large, upcoming project that is going to need extensive reporting and letter templating functionality, I have been researching various PDF rendering techniques for Ruby on Rails. Here’s a nice solution I came up with that uses PDF Writer for Ruby.

First off, check out this wonderful RailsCasts video to get you up to speed with PDF::Writer.

Here’s the code I used in my controller:

def view
   @invoice = Invoice.find_by_id params[:id]

   pdf = PDF::Writer.new( :paper => 'A4' )
   pdf.select_font "Courier"
   pdf.add_image_from_file '/shared/images/logo.jpg', 300, 700, 250, 87
   pdf.left_margin = 55
   pdf.text render_to_string :layout => false
   send_data pdf.render, :filename => 'invoice.pdf',
                         :type => 'application/pdf',
                         :disposition => 'inline'
end

The app/views/invoices/view.rhtml file is just a normal erb template file but without the HTML tags - it’s plain text.

A word of caution about those coordinates (300,700) in the add_image_from_file argument list. In PDF::Writer, the coordinates 0,0 are bottom left! So 300, 700 means 300 across from the right, 700 up from the bottom.

Works a treat. Happy PDF rendering!

RESTfulness on Rails Rocks