Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Watermark in existing PDF in Ruby

I would like to add a dynamically generated text. Is there a way to watermark an existing PDF in Ruby?

like image 836
Mike Avatar asked Apr 26 '10 19:04

Mike


People also ask

Can I add a watermark to a PDF file?

Choose Document > Watermark > Add. Specify the watermark: To reuse a watermark and watermark options that you saved in an earlier session, select it from the Saved Settings menu. To create a text watermark, select Text, and type the text in the box.


1 Answers

This will do it:

PDF::Reader to count the number of pages in the file.

Prawn to create a new PDF document using each page of the input pdf as a template.

require 'prawn'
require 'pdf-reader'

input_filename = 'input.pdf'
output_filename = 'output.pdf'

page_count = PDF::Reader.new(input_filename).page_count

Prawn::Document.generate(output_filename, :skip_page_creation => true) do |pdf|

  page_count.times do |num|
    pdf.start_new_page(:template => input_filename, :template_page => num+1)
    pdf.text('WATERMARK')
  end

end

However, in my testing the output file size was huge with the latest Gem version of Prawn (0.12), but after pointing my Gemfile at the master branch on github, all worked fine.

like image 60
Unixmonkey Avatar answered Oct 11 '22 01:10

Unixmonkey