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://github.com/thorny-sun/prawnto.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 http://github.com/thorny-sun/prawnto 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 Rails::Initializer.run 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::Document.new(... prawn options ...)
pdf.text "Hello WORLD!!", :size => 30, :align => :center
pdf.render
As opposed to the quick way of:
Prawn::Document.generate("file.pdf") do
    text "Hello WORLD!!", :size => 30, :align => :center
end
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).

Comments

  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!

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

    ReplyDelete
  3. Great! It is very useful. Thanks

    ReplyDelete
  4. Nice and good article. It is very useful for me to learn and understand easily. Thanks for sharing your valuable information and time.
    Please keep updating.
    Digital Marketing Training in Chennai

    Digital Marketing Course in Chennai

    ReplyDelete
  5. Nik Collection by DxO 5.2.0.0 Crack is the best software ever introduced by the company. It is very famous due to its user friendly interface .Nik Collection By DxO 5.2.0.0 + Crack Download

    ReplyDelete
  6. MOTU Digital Performer Crack is a professional and powerful audio processing tool. Digital Performer can be used in Windows system, has a new.MOTU Digital Performer 11.11.91406 crack

    ReplyDelete

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, Bluetooth Thunderbolt charging

My Views on Code Indentation

I have read many, many articles about the whole tab vs. space indentation thing. Personally, I don't necessarily agree with most of them. They will require the coder to use a specific indentation size and stick with it, even forcing that on other coders. First off, let me outline my method for indenting code. Then I will explain the reasons and advantages/disadvantages. When I indent code, I will use tabs, but only at the beginning of a line. To align something in the rest of the line, I will use spaces. If a line spills to the next line(s), I will indent that line two tabs further. Rationale: Tabs Why tabs? First off, they're compact in the file (1 byte each). This is really insignificant with current disk sizes, but still. If you indent in spaces, then your file will be larger (unless you indent with one space). Another advantage of tabs is that a tab is a tab. It doesn't specify by how many spaces the code is indented, but rather by how many tabs it is indente

Broadcom Bluetooth Driver: Installer or Virus??

My primary computer at the moment is an HP dv6 laptop (with Broadcom 2070 Bluetooth chip). Upon getting my laptop, I immediately wiped the hard drive and slapped on a fresh copy of Windows 7. Installed the drivers from HP, and everything was rolling along nicely... Fast-forward 4 months... Now I'm having some issues with Bluetooth communication between my phone (Android) and my laptop. So I reinstall the Bluetooth driver... The installation took a long  time, but eventually errored-out, and quit. Of course, I had left the computer unattended during this, and came back to an almost-empty hard drive (!!!!). Restored for backup, some minor data loss, no problem... I thought I had snagged a virus in the download (even though it was direct from HP's site). Redownload, scan with multiple scanners, run it ....... SAME RESULT!!! Giving up on the official installer, I just took the drivers that the installer unpacked, and manually installed them... That didn't solve my original pr