Friday, February 18, 2011

Overflow / page break examples in Prawn PDF generation

I have been using Prawn for a while. Here I gather several overflow / page break examples.


1. Text paragraph overflow

Having several lines of text and I want whole block of text stick together

# gem "prawn", "0.11.1.pre"
Prawn::Document.generate("text_group_overflow_question.pdf") do
10.times do
text "I am part of a paragraph"
end
end

Solution is using group to hold them together

# gem "prawn", "0.11.1.pre"
Prawn::Document.generate("text_group_overflow_question.pdf") do
group do
10.times do
text "I am part of a paragraph"
end
end
end


2. Table rows overflow

Sometime there is no enough space for the last table row when it reaches the end of page, and Prawn does not move it to next page. That's why we have to manually add a page break:

# gem "prawn", "0.8.4"
# Sometime there is no enough space for the last table row when it reaches the end of page
Prawn::Document.generate("text_group_overflow_question.pdf") do |pdf|
add_page_break_if_overflow(pdf) do |pdf|
# generating table here
# ...
end
end
def add_page_break_if_overflow(pdf, &block)
current_page = pdf.page_count
roll = pdf.transaction do
yield(pdf)
pdf.rollback if pdf.page_count > current_page
end
if roll == false
pdf.start_new_page
yield(pdf)
end
end


More code snippets available at https://gist.github.com/3dd13

2 comments:

  1. Thanks for the tip. I've just included in my code!

    ReplyDelete
  2. Really nice blog post.provided a helpful information.I hope that you will post more updates Ruby on Rails Online Course Bangalore

    ReplyDelete