Jun 19

Creating PDF documents with tables in Ruby, Rails

I started to use "Ruby FPDF":http://zeropluszero.com/software/fpdf/ to create PDF documents from our new Rails application "MojGost.com":http://www.mojgost.com. Ruby FPFD like it's "PHP counterpart":http://www.fpdf.org/ does not have methods for creating tables. However, there are many examples and scripts available and that allowed me to quickly write small Ruby module which adds few methods for easy table creation.

I started to use "Ruby FPDF":http://zeropluszero.com/software/fpdf/ to create PDF documents from our new Rails application "MojGost.com":http://www.mojgost.com. Ruby FPFD like it's "PHP counterpart":http://www.fpdf.org/ does not have methods for creating tables. However, there are many examples and scripts available and that allowed me to quickly write small Ruby module which adds few methods for easy table creation.Fpdf::Table main features:
  • word wraping text in cells, based on width of columns
  • page breaks on rows if table is too long

Download Fpdf::Table or see some examples below.

Example 1. simple table


require 'FPDF'
require 'fpdf/table'

class FPDF
  include Fpdf::Table
end

pdf = FPDF.new
pdf.AddPage
pdf.SetFont('helvetica','',10)
data = [
  ['100', 'lorem ipsum dorem'],
  ['100', 'lorem ipsum dorem'],
  ['100', 'lorem ipsum dorem'],
]
pdf.table(data)
pdf.Output('test_fpdf_table_1.pdf')

View Example 1 PDF

Example 2. width, word-wrap, aligment, page break


require 'FPDF'
require 'fpdf/table'

class FPDF
  include Fpdf::Table
end

pdf = FPDF.new
pdf.AddPage
pdf.SetFont('helvetica','',10)

data = []
30.times { |i| data << [i.to_s, '-', 'Lorem ipsum dolor sit' * 10] }

columns = [
  {:title => '#1', :aligment => 'R', :width => 20},  
  {:title => '#2', :width => 20},
  {:title => 'Text'}  
]

pdf.table(data, columns)
pdf.Output('test_fpdf_table_2.pdf')

View Example 2 PDF