Skip to content

Instantly share code, notes, and snippets.

@chapados
Created October 17, 2008 20:57
Show Gist options
  • Save chapados/17528 to your computer and use it in GitHub Desktop.
Save chapados/17528 to your computer and use it in GitHub Desktop.
require 'java'
require 'iText-2.1.3.jar'
module Java
import 'java.io.FileOutputStream'
import 'com.lowagie.text.pdf.PdfReader'
import 'com.lowagie.text.pdf.PdfStamper'
import 'com.lowagie.text.pdf.PdfWriter'
import 'com.lowagie.text.pdf.BaseFont'
end
def stamp_pdf(src, target=nil, message=nil)
include Java
target ||= File.join(File.dirname(src), "#{File.basename(src, '.*')}-stamped.pdf")
message ||= "JRuby + iText FTW!"
reader = PdfReader.new(src)
stamper = PdfStamper.new(reader, FileOutputStream.new(target))
base_font = BaseFont.create_font(BaseFont::HELVETICA, BaseFont::WINANSI, BaseFont::NOT_EMBEDDED)
page_count = reader.number_of_pages
page_count.times do |i|
page_num = i + 1 # itext uses 1-index page numbers...
over = stamper.over_content(page_num)
over.begin_text
over.setFontAndSize(base_font, 25)
over.setTextMatrix(100, 30) # x, y location - bottom left = (0,0)
over.show_text(message)
over.end_text
over.stroke
end
stamper.close
end
if __FILE__ == $0
stamp_pdf(*ARGV)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment