Creating PDF in Ruby on Rails – PDF::Writer

PDF::Writer is my choice for creating PDF files in Ruby on Rails. Its simple, easy to use, and has all the features I am looking for.

Install PDF::Writer in Linux systems using this command…

gem install pdf-writer -y

Includes

We will require rubygems and pdf/writer.

require "rubygems"
require "pdf/writer"

The next line creates a new instance of PDF::Writer

pdf = PDF::Writer.new

Create a Heading(big font size)

pdf.select_font "Times-Roman"
pdf.text "Sample PDF Document", :font_size => 32, :justification => :center

The text function will add a string of text to the document, starting at the current position. It will wrap to keep within the margins – so you can specify text as big blocks. The text will go to the start of the next line when a return code “\n” is found.

The other arguments available for this function are…

:font_size
The font size to be used. If not specified, is either the last font size or the default font size of 12 points. Setting this value changes the current font_size.
:left
Gap to leave from the left margin
:right
Gap to leave from the right margin
:absolute_left
Absolute left position (overrides :left)
:absolute_right
Absolute right position (overrides :right)
:justification
This can be :left, :right, :center, :full
:leading
This defines the total height taken by the line, independent of the font height.
:spacing
Line spacing – usually set to one of 1, 1.5, 2 (line spacing as used in word processing)

Writing Text

pdf.text "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aliquam sodales velit ac ante. Suspendisse felis mi, convallis at, semper id, malesuada eu, mauris. Integer orci. Sed consectetuer orci. In hac habitasse platea dictumst. Duis nec pede. Ut lacinia eros ut magna. Maecenas lectus dui, lacinia vel, porttitor a, fringilla nec, turpis. Nulla odio nisi, mattis ac, porttitor at, malesuada ac, nibh. Nam suscipit mi ut justo. Phasellus aliquam lorem non velit ornare bibendum. Nullam mollis. Ut elementum rutrum justo. Pellentesque ac sapien. In facilisis lorem a enim. Curabitur vitae felis. In eget tellus nec ligula egestas semper. Nulla facilisis urna nec magna. Pellentesque fringilla pulvinar risus. Aliquam rutrum, nisi ut lobortis consequat, nisl felis posuere risus, at sollicitudin nibh dui et felis.

Fusce tristique dapibus neque. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Ut felis mi, dictum ut, vehicula non, fermentum quis, elit. Quisque ultricies purus quis enim. Integer turpis elit, porttitor quis, volutpat consequat, interdum vitae, quam. Donec tempus, dolor eget bibendum euismod, metus dolor imperdiet purus, vitae nonummy est mi non orci. Aenean eu massa. Fusce euismod. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos hymenaeos. Nullam quis massa id sem commodo eleifend. Cras eu velit rutrum leo egestas adipiscing. Nulla volutpat, lectus sit amet sagittis gravida, erat tortor condimentum sem, vitae sollicitudin lectus diam eget felis. Aliquam augue. Vestibulum viverra est. Fusce tellus ligula, euismod sed, placerat vel, cursus dictum, erat.", :font_size => 12

I used the text() – but this time with 12 as the font_size. The long text will wrap around and the \n will be converted to line breaks.

Inserting Images

PDF::Writer provides an easy way to insert images…

pdf.image "default.png"

That’s it – it will insert an image called ‘default.png’. The other option are…

:pad
The number of PDF userspace units that will be on all sides of the image. The default is 5 units.
:width
The desired width of the image. The image will be resized to this width with the aspect ratio kept. If unspecified, the image’s natural width will be used.
:resize
How to resize the image, either :width (resizes the image to be as wide as the margins) or :full (resizes the image to be as large as possible). May be a numeric value, used as a multiplier for the image size (e.g., 0.5 will shrink the image to half-sized). If this and :width are unspecified, the image’s natural size will be used. Mutually exclusive with the :width option.
:justification
The placement of the image. May be :center, :right, or :left. Defaults to :left.
:border
The border options. No default border. If specified, must be either true, which uses the default border, or a Hash.

Tables

Inserting tables are slightly more complicated than the last two items. If you are using SimpleTable, you have to add
require "pdf/simpletable"
along with the other includes.

table = PDF::SimpleTable.new
table.title = "Sample Tables"
table.column_order.push(*%w(first second))

table.columns["first"] = PDF::SimpleTable::Column.new("first")
table.columns["first"].heading = "First"

table.columns["second"] = PDF::SimpleTable::Column.new("second")
table.columns["second"].heading = "Second"

table.show_lines    = :all
table.show_headings = true
table.orientation   = :center
table.position      = :center

data = [
	{"first"=> "1", "second"=> "2"}, # First row
	{"first"=> "One", "second"=> "Two"}, # Second row
	{"first"=> "Mono", "second"=> "Di"}, # Third row
]

table.data.replace data
table.render_on(pdf)

The above code will create a table with two column and three rows of data. The code should be easy to decipher – so I am not going into any more explanation.

Saving the PDF

Finally, saving the created PDF…

pdf.save_as("report.pdf") 

Links

5 Comments

Comments are closed.