I would like to add a dynamically generated text. Is there a way to watermark an existing PDF in Ruby?
问题:
回答1:
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.
回答2:
Another option is to use PDFTK. It can be used to add a watermark and create a new PDF. Maybe prawn will do the same thing with it's templating.
pdftk in.pdf background arecibo.pdf output wmark1.pdf
Some more info: http://rhodesmill.org/brandon/2009/pdf-watermark-margins/
There is a ruby wrapper gem called active_pdftk which supports backgrounding, so you don't have to do the shell commands yourself.
回答3:
Prawn doesn't support templates anymore...
Try the combine_pdf gem.
You can combine, watermark, page-number and add simple text to existing PDF files (including the creation of a simple table of contents without PDF links).
It's a very simple and basic PDF library, written in pure Ruby with no dependencies.
This example can fit your situation (it's from the readme file):
# load the logo as a pdf page
company_logo = CombinePDF.load("company_logo.pdf").pages[0]
# load the content file
pdf = CombinePDF.load "content_file.pdf"
# inject the logo to each page in the content
pdf.pages.each {|page| page << company_logo}
# save to a new file, with the logo.
pdf.save "content_with_logo.pdf"
回答4:
Check out Prawn(http://github.com/sandal/prawn) for just ruby and Prawnto(http://github.com/thorny-sun/prawnto) for Ruby on Rails.
You are probably going to want to either use the image embedding functionality or the background image functionality.
Here's an example of using a background image http://cracklabs.com/prawnto/code/prawn_demos/source/general/background
回答5:
Use Ruport.
1st result for Googling ruby pdf watermark
.