How to edit or write on existing PDF with Ruby?

Alex Kovshovik picture Alex Kovshovik · Feb 8, 2012 · Viewed 25.2k times · Source

I have a couple of PDF template files with complex content and several blank regions/areas in them. I need to be able to write text in those blank regions and save the resulting PDFs in a folder.

I googled for answers on this question quite intensively, but I didn't find definite answers. One of the better solutions is PDF::Toolkit, but it would require the purchase of Adobe Acrobat to add replaceable attributes to existing PDF documents.

The PHP world is blessed with FPDI that can be used to simply open a PDF file and write/draw on it over the existing content. There is a Ruby port of this library, but the last commit for it happened at the beginning of 2009. Also that project doesn't look like it is widely used and supported.

The question is: What is the better Ruby way of editing, writing or drawing on existing PDFs?

This question also doesn't seem to be answered on here. These questions are related, but not really the same:

Answer

Said Kaldybaev picture Said Kaldybaev · Feb 9, 2012

you have to definitely check out Prawn gem, by which you can generate any custom pdf files. You can actually use prawn to write in text into existing pdfs by treating the existing PDF as a template for your new Prawn document.

For example:

filename = "#{Prawn::DATADIR}/pdfs/multipage_template.pdf"
Prawn::Document.generate("full_template.pdf", :template => filename) do
  text "THis content is written on the first page of the template", :align => :center
end

This will write text onto the first page of the old pdf.

See more here: http://prawn.majesticseacreature.com/manual.pdf