1. Technology
You can opt-out at any time. Please refer to our privacy policy for contact information.

Spotlight on Gems: Prawn


Prawn is a pure-Ruby library for generating PDF files. From your Ruby code, you'll be able to compose PDF files with any content and of any size. This is not only ideal for generating reports, but also for formatting documentation and providing a portable format for your program's output. Prawn is pure-Ruby, it has no compiled parts and doesn't rely on any third party libraries with restrictive licenses.

Installing Prawn

Prawn is pure-Ruby and has few dependencies. Prawn actually comes in a number of gems, but installing the prawn gem will install them all.

$ gem install prawn

Using Prawn

Prawn has a simple interface. Calling Prawn::Document.generate and supplying it a filename and a block will get you started. From there, use a set of methods such as text for rendering text and image to render images to compose your PDF document. When the block ends, the PDF will be rendered and written to disk.

The following is a "Hello world" program, which generates a PDF containing nothing but the text "Hello world."

#!/usr/bin/env ruby
require 'rubygems'
require 'prawn'

Prawn::Document.generate("prawn2.pdf") do
  text "Hello world!"

This interface is succinct and powerful, but it may not suit every need. One drawback is that all PDF rendering must be done in the block supplied to Prawn::Document.generate. The generate method is just a wrapper for what you can do yourself though. The following is functionally equivalent. Note that there's an extra call to the render method that wasn't in the first example, because generate took care of that for you. If you don't call render then nothing will be written to disk.

#!/usr/bin/env ruby
require 'rubygems'
require 'prawn'

pdf = Prawn::Document.new
pdf.text "Hello world!"
pdf.render_file "prawn1.pdf"

Since you have the PDF generator object stored in a variable, you can split up your PDF commands. Another advantage is you have better control over when the PDF is rendered. Since rendering a PDF can be expensive, you have the ability to wait until a more convenient time (when there is less server load, for example) to render the PDFs.

  1. About.com
  2. Technology
  3. Ruby
  4. Gems
  5. Spotlight on Gems: Prawn

©2014 About.com. All rights reserved.