Skip to main content

Generating PDFs in Rails with Prawn and Prawnto

There are several different PDF generation libraries available for Rails apps. Some of these are PDF::Writer, Prawn, Ruport, RGhost, and FlyingSaucer (for JRuby). First off, Ruport is basically a higher-level API for PDF::Writer. FlyingSaucer is only for JRuby (because JRuby allows for loading of Java classes). Not having any experience with RGhost, I can't exactly write a guide for using it. So now it's basically between Prawn and PDF::Writer, unless there's another library I haven't hear of. However, to my dismay, there is not UTF-8 support in PDF::Writer. So Prawn ends up being the PDF generation library of choice.

One thing to keep in mind is that Prawn and Prawnto are beta-stage (sometimes even alpha) libraries, so some code hacking is going to be necessary. Also note the Prawnto is not maintained or tested by the Prawn developers, so there's no guarantee that it'll work with future versions (especially since Prawnto's developer has been "below the radar" for a little while). You have been warned.

Now to easily follow the Model-View-Controller philosophy of Rails, we use Prawnto. Without Prawnto (following the official method), we would subclass Prawn::Document (and send the PDF using the send_data method), which sort of takes away from the "automagic" of Rails. Instead of doing the interaction between your PDF code and controller manually, we can use Prawnto in order to place code inside views (with a .pdf.prawn extension). This will "automagically" instantiate a PDF object, pass it to the view, and then send it, all behind-the-scenes. It'll also allow for cool Rails functionality like helpers and partials. Keep in mind that all of this can be done using the official method (recommended by the Prawn developers, see below for link), but it'll require more manual coding.

So let's get started with all of this by installing Prawn and Prawnto. Prawn is available as a gem, a simple gem install prawn will do the trick. Prawnto is not available as a gem, however, and you will have to pull the plugin from a git repository. To do that, run this command: script/plugin install git:// in the root of your Rails project. Of course, you must have git installed in order to do this. If you don't want to install git (maybe you're running Windows), you can download the master branch at and unpack that into your vendor/plugins/prawnto directory in the root of your Rails project.

Now that everything is installed, the Rails project has to be configured. Inside the config/environment.rb file, in the do |config| ... end block, insert these two lines:
config.gem 'prawn-core', :lib => 'prawn/core'
config.gem 'prawn-layout', :lib => 'prawn/layout'

That's really all that's needed to get started with using Prawn and Prawnto. So now let's take a look into how this would actually be used.

Let's assume that we have a Book model. It's not crucially important what information this model contains for demonstrating how to work with Prawn. So now we have a books_controller.rb file in our controllers directory. In our views/books directory, we have various .html.erb files for our actions. Let's also assume that we definitely have an index.html.erb and show.html.erb.

Now, to create a link to the PDF, we can use this link_to syntax (substitute :show for :index in the different views):
link_to 'Print (PDF)', {:controller => :books, :action => :index, :format => :pdf}
This will create a link to location with .pdf on the end.

Now, we have to make our controller respond to the PDF format. To do so, we add the following into the respond_to do |format| ... end:
format.pdf { render :layout => false } if params[:format] == 'pdf'
prawnto :filename => "print.pdf", :prawn => { ... prawn options ... }
Basically, this will make prawnto render the PDF. In most cases, we do not want to render a layout, so we force format.pdf to not render a layout. The if params[:format] == 'pdf' is a safeguard to only render the PDF format if the PDF format is requested. As for the prawnto options, the filename can be specified as anything you desire (doesn't even have to end with .pdf, but that's usually not a good idea). If omitted, the filename will be [action name].pdf. The options specified by [prawn options] hash are options that will be used to create the Prawn::Document object. So the margins, page orientation, etc are specified here. For a full reference on the options, see the Prawn Documentation.

Great, now our controller can respond, but we won't get anywhere, because we don't have the PDF views yet. To do so, we create files (in the views/books directory) with a .pdf.prawn extension. For this example, we would have index.pdf.prawn and show.pdf.prawn. Past this point, it's absolutely essential to have knowledge of Prawn and how to generate PDFs with it. Please note that this is not a tutorial on Prawn (maybe in another post...).

Prawnto will instantiate a Prawn::Document object and allow it to be accessed as the variable pdf inside your .pdf.prawn views. So a simple "Hello World!" message inside the index.pdf.prawn file would look something like this:
pdf.text "Hello WORLD!!", :size => 30, :align => :center
This is the same code that would be used when generating a PDF file like this:
pdf = prawn options ...)
pdf.text "Hello WORLD!!", :size => 30, :align => :center
As opposed to the quick way of:
Prawn::Document.generate("file.pdf") do
    text "Hello WORLD!!", :size => 30, :align => :center
So essentially all of the Prawn methods will just be accessed through the pdf object.

Another cool feature of Prawnto is partials. Actually, I'm not sure if this automagically performed by Rails, or if some work is required from Prawnto. But anyway, you can use partials with PDFs, just like you use partials with normal views. Just name them _[partial name].pdf.prawn. Then, inside, let's say, show.pdf.prawn, you could render the author_info partial with:
render :partial => 'author_info', :locals => {:ppdf => pdf}
The :locals => {:ppdf => pdf} will create the ppdf (parent-pdf) variable for use inside the partial (instead of pdf., use ppdf. inside the partial). I believe that this is a limitation of Prawnto. I've tried :locals => {:pdf => pdf}, but then nothing rendered at all. This is a very minor inconvenience that should not prevent anybody from using partials with Prawnto.

Other than those features, all features of Rails views apply. That means you can use helpers, instance variables (set in controller, of course), and all of the other coll Rails features. The only thing to keep in mind is that all of the code inside the .pdf.prawn files is treated as Ruby code. So, no ERB tags like you use in .html.erb files.

I hope that now you are prepared to easily generate PDFs in your Rails application. A word of advice is to keep in mind that these libraries are beta-level, and could be unstable!! So to finish off, I'll leave you some sites that could prove useful when using Prawn:

  • Main Prawn site (with documentation for core features and layout stuff), also contains examples.
  • Prawn Google Group
  • Prawn GitHub repo (if you're feeling adventurous, use the bleeding edge - not recommended!!)
  • Prawnto site (sometimes down). This site is hard to read (bad choice of colors), but contains some useful information
  • Prawnto GitHub repo
  • The official method of using Prawn in Rail projects. Sometimes, Prawnto will not work, but this setup is tested by the Prawn developers to work. If you use this method, you should pretty much start with that method from scratch, instead of following any of these instructions.
P.S. In case you're wondering what happened to Prawn::Format, and why it's not in here: Prawn::Format does not have anyone maintaining it, and therefore has been "retired" for the time being. You can research how to use it on your own, but there is absolutely no expectation of Prawn::Format working with Prawn after version 0.7 is released.

EDITED on 12/15/2009 based on suggestions from Gregory Brown (Prawn dev).


  1. Thanks for posting this up - it's really helpful! I've found the documentation for both Prawn and Prawnto to be lacking for the moment.

    And yes, I agree! that Prawn site is ugly and has really bad color choice!

  2. Thanks . I found this post useful . Thank you again.


Post a Comment

Popular posts from this blog

Linux on XPS 15 9550/9560 with TB16 Dock [Update:3/29]

Finally got a laptop to replace my fat tower at work - Dell XPS 15 9560. I was allowed to choose which one I wanted and chose the XPS for its Linux support since Dell ships developer edition XPS's running Ubuntu so I figured Linux support would be better than other manufacturers. At first they got me the model with the 4K screen but my monitors are 2K and multi-dpi support in Linux is virtually non-existent and even hi-dpi support on its own is pretty terrible. So I got it exchanged for the model with the regular 1080p screen (which happened to also be the updated 9560 model), which works much better. I'm very glad to report that pretty much everything works, including the TB16 desktop dock, with just a bit of settings tweaking. This post is to help anybody considering getting this setup or looking for help getting things working. For now, I am running Kubuntu 16.04 with KDE Neon installed.

List of things I explicitly tested and work:
WiFi, BluetoothThunderbolt charging from T…

Listening for Window Resize events with Prototype

Recently, I came across an issue I had with full-screen (more specifically, full-viewport) canvas drawing. It all worked fine, except that the canvas dimensions must be specified in pixels, as opposed to percentages. This means you can't just set the canvas' width and height to "100%" and be done with it...

The dimensions were automatically set when the page loaded, but if the user resized the browser window after that, the canvas would stay the same size, and would be either too big or too small. Thus, the canvas must be resized every time the browser window is resized.

Prototype makes all of this easy. All that's necessary is to attach a listener to the onresize event of the window object, and then use document.viewport.getDimensions() to determine the new width and height.

Here's some sample code:

Event.observe(window, "resize", function() { var width = document.viewport.getWidth(); var height = document.viewport.getHeight(); var dims …

Drawing Dashed Lines on an HTML5 Canvas

The canvas element in HTML is great, but has one strange shortcoming: it cannot draw dashed lines (natively). However, dashed lines seem like a pretty common thing to draw, which only highlights the problem.

Looking around, I've noticed several solutions to this problem. Some use trig, and others use their own libraries that must be imported. So in the end, I decided to create my own method.

This code will add the function to all canvas elements, both those already on the page, and any that are dynamically added later.

Here is the code:
CanvasRenderingContext2D.prototype.dashedLine = function(x1, y1, x2, y2, dashLen) { if (dashLen == undefined) dashLen = 2; this.beginPath(); this.moveTo(x1, y1); var dX = x2 - x1; var dY = y2 - y1; var dashes = Math.floor(Math.sqrt(dX * dX + dY * dY) / dashLen); var dashX = dX / dashes; var dashY = dY / dashes; var q = 0; while (q++ < dashes) { x1 += dashX; y1 += dashY; this[q …