Search code examples
ruby-on-railsrubypdfprawn

Background images using prawn on all pages


I have this code in the view

prawn_document(:page_size=> "A4", :top_margin => 80, :bottom_margin => 40,
               :background => "public/uploads/1.png") do |pdf|

  creation_date = Time.now.strftime('%d-%m-%Y')
  posts = @posts.each do |post|
    pdf.pad(10) do
      pdf.text post.title
      pdf.text post.text
    end
  end

  pdf.page_count.times do |i|
    pdf.go_to_page(i + 1)
    pdf.draw_text "Creation Date : " + creation_date, :at => [200, 780]
    pdf.draw_text "Page : #{i + 1} / #{pdf.page_count}", :at => [450, -3]
  end
end

This gives me the following output:

enter image description here

and this

enter image description here

As you can see in the first image, the image is not centered.

On the 2nd image you can see the image doesn't fit the full page.

I also tried adding the image to each page,the way I added the page number, but here the image overlaps text. But here I can position the image the way I want which works but only that it overlaps the text.

If I put in the header I cannot position and size the image.

So I need help getting the image to fit the page. The image is 700px x 700px.

I also tried using PDFkit, but couldn't get page numbers on that, I feel I am almost there using Prawn, but just this image. Even a different solution will be much appreciated.


Solution

  • Prawn cannot seem to stretch a background image to fit the page via an option, unfortunately. However, you can. The page the image needs to fit is static, it never changes size. Moreover, we know the exact dimensions:

    p Prawn::Document::PageGeometry::SIZES['A4']
    # => [595.28, 841.89]
    

    Thus, the best solution is to use an image editor of your choice and create an image of that size. That is, create a canvas of that size and fit your original image whichever way you want. You can choose to stretch it, although I would probably just proportionally shrink it to fit the width and center it vertically. But that's up to you. Just make sure to create a 595px x 842px image and it should fit nicely.