Alex Harris
Alex Harris

Reputation: 6402

Changing the background color of a pdf with Prawn?

I can't for the life of me find any documentation on how to change the background color of a pdf to something besides white?

Upvotes: 6

Views: 3524

Answers (1)

Luke Fritz
Luke Fritz

Reputation: 118

You could have the first element on a page be a filled rectangle that takes up the entire page. canvas will let you work with the bounds of the entire page.

canvas do
  fill_color "FFFFCC"
  fill_rectangle [bounds.left, bounds.top], bounds.right, bounds.top
end

The following script would create this PDF.

require "prawn"

def background_color(color)
  tmp_color = fill_color
  canvas do
    fill_color color
    fill_rectangle [bounds.left, bounds.top], bounds.right, bounds.top
  end
  fill_color tmp_color
end

Prawn::Document.generate("colored-pages.pdf") do
  fill_color "FF0000"

  background_color "FFFFCC"
  text "Text on page 1"

  start_new_page
  background_color "FFCCFF"
  text "Text on page 2"

  start_new_page
  background_color "CCFFFF"
  text "Text on page 3"

  start_new_page
  background_color "CCFFCC"
  text "Text on page 4"
end

Upvotes: 8

Related Questions