Create PDF Documents In Ruby

pradeep's Avatar author of Create PDF Documents In Ruby
This is an article on Create PDF Documents In Ruby in Ruby on Rails.
PDF (Portable Document Format) is a very popular format which has wide range of uses from invoices to mathematical and scientific journals, which may include images, graphs and other embedded objects. PDF files' most important strength that their formatting looks the same everywhere i.e. all platforms and architectures, unlike other similar format like DOCX, DOC and ODT to name a few.

PDF has a good security features like digitally signing documents for authenticity, encrypt & password protect document to various level of security. This feature has made it an indispensable format, and is widely used by government, banks, law firms, etc. Like, banks send digitally signed statements, law firms & businesses send digitally signed contracts etc.

In this article we will be look at a really nice Ruby gem called Prawn which will be employed to create PDF documents from scratch, though in this article I'll only cover the basics, you can explore it yourself to create whatever you wish to.

Installing Prawn

Like all Ruby gems, Prawn too is super easy to install, just issue this command on the command line.

# gem install prawn

Creating PDF with Prawn

Follow the sample code below, I have commented at places to explain what the code snippet is required for.

require 'rubygems'
require 'prawn'

# Create a simple PDF and save it
pdf =
pdf.text "Welcome to Go4expert"
pdf.render_file "g4e.pdf"

# now lets look at some formatting, like text size and alignment
pdf.text "Welcome to Go4expert", :align => :center, :size => 18
pdf.text "A programming forum", :align => :center, :size => 15

pdf.text "lots of programming" * 10, :align => :justify

## change font
pdf.font "Georgia"
pdf.text "Hello World!!"

## color your text
pdf.text "Ruby in Red", :color => "FF0000"

## using a custom font
pdf.font("fonts/Monaco.ttf") do
   pdf.text "Text in Monaco TTF font."

## add an image, with optional height width params
pdf.text "Image below"
pdf.image "images/image1.jpg", :width: 100, :height => 100

## create a table, it's really easy
table = pdf.make_table( ["row1","Name1"], ["row 2","Name2"] )

## generate options, like setting page size & orientation
pdf.generate("my_custom.pdf", :page_size => "LETTER", :page_layout => :landscape)
I hope this introduction was useful, I have only scratched the surface, you can use Prawn to create objects, draw graphs, pie charts etc.