Go4Expert

Go4Expert (http://www.go4expert.com/)
-   Ruby on Rails (http://www.go4expert.com/articles/ruby/)
-   -   Create PDF Documents In Ruby (http://www.go4expert.com/articles/create-pdf-documents-ruby-t29920/)

pradeep 29Nov2013 19:21

Create PDF Documents In Ruby
 
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.

Code:

# 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.

Code:

require 'rubygems'
require 'prawn'

# Create a simple PDF and save it
pdf = Prawn::Document.new
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."
end

## 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"] )
table.draw

## 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.


All times are GMT +5.5. The time now is 16:00.