Published at 02.04.2014
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.
Table of Contents
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.
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:
Prawn::Document.generate("hello.pdf") do text "Hello World!" end
The Prawn manual has many more beginner friendly examples.
get '/' do 'Hello world!' end
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.
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 = Prawn::Document.new pdf.text "Hello Anynines, Prawn and Sinatra" pdf.render end
And your Gemfile should look like the following:
gem 'sinatra' gem 'prawn'
Check your manifest.yml to look like the manifest example file. To deploy:
cf api https://api.aws.ie.a9s.eu cf login cf push
Open your app in the browser and marvel at your accomplishments!