Creating an application form style layout using Prawn

I used the excellent Prawn gem recently to create a PDF. I needed an application form style like layout for the PDF like this:

Simple form layout

Simple form layout

Using Prawn this is straight forward. We just create two bounding boxes one for the left side and one for the right side of the page. Then we render the labels into the left bounding box and the form boxes into the right bounding box.

require "prawn"
Prawn::Document.generate("form.pdf") do
move_down 5
text "Application form", style: :bold, size: 25
bounding_box([0,cursor], width: bounds.width, height: 120) do
fill_color "DCDCDC"
fill_rectangle [0, cursor], bounds.right, bounds.top
fill_color "000000"
transparent(0.5) { stroke_bounds }
move_down 10
float do
bounding_box([5, cursor], width: 250, height: 200) do
["First name(s):", "Last name:", "Address line 1:", "Address line 2:"].each do |label|
pad(5) { text label }
end
end
end
bounding_box([260, cursor], width: 250, height: 200) do
stroke_color "000000"
fill_color "ffffff"
4.times do
fill_and_stroke_rectangle([5, cursor], 240, 18)
move_down 24
end
end
end
end

view raw
form.rb
hosted with ❤ by GitHub

Filling in the fields

filled-in-form

Filled in form

In some case I need to fill in the fields as well so I generalised the code into a method that takes a hash:

require "prawn"
def form(pdf, fields)
pdf.float do
pdf.bounding_box([5, pdf.cursor], width: 250, height: 200) do
fields.keys.each do |label|
pdf.pad(5) { pdf.text label }
end
end
end
pdf.bounding_box([260, pdf.cursor], width: 250, height: 200) do
pdf.stroke_color "000000"
fields.values.each do |value|
pdf.fill_color "ffffff"
pdf.fill_and_stroke_rectangle([5, pdf.cursor], 240, 18)
fill_color "000000"
pdf.text_box value, at: [10, pdf.cursor5]
pdf.move_down 24
end
end
end
Prawn::Document.generate("filledinform.pdf") do
move_down 5
text "Application form", style: :bold, size: 25
bounding_box([0,cursor], width: bounds.width, height: 120) do
fill_color "DCDCDC"
fill_rectangle [0, cursor], bounds.right, bounds.top
fill_color "000000"
transparent(0.5) { stroke_bounds }
move_down 10
form_fields = {
"First name" => "John",
"Last name" => "Doe",
"Address line 1:" => "20 Shrimp lane",
"Address line 2:" => ""
}
form(self, form_fields)
end
end

view raw
filledin_form.rb
hosted with ❤ by GitHub

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s