Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing the background color of a pdf with Prawn?

Tags:

ruby

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?

like image 957
Alex Harris Avatar asked Apr 30 '15 03:04

Alex Harris


People also ask

Can I change PDF background color?

Choose Tools > Edit PDF. The Edit PDF toolset is displayed in the secondary toolbar. In the secondary toolbar, choose More > Background > Update. Click OK, or make other changes to the background options and then click OK.

How do I change the background color of a PDF permanently?

When the PDF file is loaded completely, click “Tools” and look for “Background”, and then select “Add Background”. Now another window will appear, tick the box besides “From color” and simply select the new color that you wish to use and then click “OK”. To keep the changes made, go to “File” and then hit “Save”.


1 Answers

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
like image 174
Luke Fritz Avatar answered Oct 06 '22 04:10

Luke Fritz