Generating PDF’s with Prawn and Ruby

In this post we will generate PDF’s with Ruby, exploring the exemplary use case of creating customer invoices. In order to output PDF’s from your (custom) billing system, you’ll need a library that exports PDF’s. There are different ways to achieve HTML to PDF conversion in Ruby. Let’s take a closer look.

HTML to PDF libraries

Two major players in this field are PDFlib and Prawn. PDFlib is a commercial library, and as such more advanced than Prawn. You’ll find table configuration and formatting to be a helpful feature. PDFlib has many more bindings, with support for PHP, Perl, Python, Ruby, Java, .NET and C++/C.

Yet, the Prawn ‘API’ will feel more natural to a Rubyists The PDFlib extension doesn’t feel like Ruby most of the time, it’s just a wrapper for the normal PDFlib C calls. Plus: Prawn is open source (and thus free of charge).

Because Prawn is pure Ruby and all of its runtime dependencies are maintained by Prawn itself, it should work pretty much anywhere.

With Prawn you can (and will have to) do all the content styling and positioning on your own, using its DSL. You actually have full control over how items are displayed and where pages break. In case you are interested in Prawn’s advanced formatting options, please refer to this excellent post on SitePoint.

To showcase the power of Prawn, I build a Sinatra Prawn example app using the library and anynines to output PDF’s. Naturally you can find the code on GitHub.

Using Prawn

Prawn is distributed via RubyGems, and can be installed the usual way that you install gems: by simply typing gem install prawn on the command line. Your app.rb will look like the following example:

require "prawn"
Prawn::Document.generate("hello.pdf") do
  text "Hello World!"

The Prawn manual has many more beginner friendly examples.

Setting up Sinatra

Sinatra is a DSL for creating web applications in Ruby, with seemingly minimal effort. To use Sinatra for our example app, we write the following in our app.rb:

require 'sinatra'
get '/' do
  'Hello world!'

To install the Sinatra gem, run gem install sinatra in your terminal.
To view your mini Sinatra application in your browser, paste ruby app.rb in your terminal and open localhost:4567.

Connecting the dots: Prawn and Sinatra

Using both Prawn and Sinatra to output a PDF, your app.rb file will look something like this:

require 'rubygems'
require 'bundler/setup'
require 'sinatra'
require 'prawn'
get '/' do
  content_type 'application/pdf'
  pdf =
  pdf.text "Hello Anynines, Prawn and Sinatra"

And your Gemfile should look like the following:

source ''
gem 'sinatra'
gem 'prawn'

Pushing your invoice app online

Check your manifest.yml to look like the manifest example file. To deploy:

cf api
cf login
cf push

Open your app in the browser and marvel at your accomplishments!

Leave a Reply

Your email address will not be published. Required fields are marked *