Wednesday, May 11, 2016

How to create a watermark in Prawn (the Ruby library for writing PDFs)

 Prawn::Stamp is no good since, since you have to specifically call it for each instance of use, and you won't necessarily know how many pages you are going to get if generating the PDF dynamically from user generated content.

If you use #repeat, this method is going to write over existing text/drawings towards the end of PDF generation. But a watermark should be in the background, not 'stamped' on top.

Here's the solution:

  def watermark(watermark)
    function = lambda {@pdf.formatted_text_box([{:text => "#{watermark}", :color => '5B5B5B', :size => 60}], :rotate => 30, :rotate_around => :center, :align => :center, :valign => :center)}
    # call the function for the first page
    function.call
    # call the function for every subsequent page that is created
    @pdf.on_page_create {function.call}
  end


The method lets you use any string and centres it in the middle of the page irrespective of length.

Calling the function with #on_page_create ensures that the watermark is drawn first; other objects are then drawn on top.

Now watermark("Draft"), for example, can be used in any Prawn::Document.

No comments:

Post a Comment