O'Reilly logo

Ruby Cookbook by Leonard Richardson, Lucas Carlson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

12.13. Generating PDF Files

Problem

You want to create a text or graphical document as a PDF, where you have complete control over the layout.

Solution

Use Austin Zeigler's PDF::Writer library, available as the pdf-writer gem. Its API gives you fine-grained control over the placement of text, images, and shapes.

This code uses PDF::Writer to produce a simple flyer with an image and a border (Figure 12-7). It assumes you've got a graphic called sue.png to insert into the document:

The flyer

Figure 12-7. The flyer

	require 'rubygems'
	require ' 
pdf/writer'                                   # => false

	# Putting "false" on the next line suppresses a huge output dump when
	# you run this code in irb.
	 
pdf = PDF::Writer.new; false

	pdf.text("LOST\nDINOSAUR", :justification => :center, :font_size => 42,
	         :left => 50, :right => 50)
	pdf.image("sue.png", :left=> 100, :justification => :center, :resize => 0.75)
	pdf.text(%{Three-year-old <i>Tyrannosaurus rex</i>\nSpayed\nResponds to "Sue"},
	         :left => 80, :font_size => 20, :justification => :left)
	pdf.text("(555) 010-7829", :justification => :center, :font_size => 36)

	pdf.rectangle(pdf.left_margin + 25, pdf.y-25,
	              pdf.margin_width-50, pdf.margin_height-pdf.y+50).stroke; false

	pdf.save_as('flyer.pdf')

Discussion

So long as you're only calling Writer#text and Writer#image, PDF generation is easy. PDF automatically adds new text and images to the bottom of the current text, creating new pages as ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required