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:
You can edit the PDF in Adobe Acrobat or another PDF editing tool that allows you to access forms in a PDF and create new ones. Microsoft Word can also import PDF files and turn them into editable Word documents, although they may be slightly altered in the process.
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
Since Prawn has removed the template feature (it was full of bugs) the easiest way I've found is the following:
Rough Example:
require 'prawn' require 'pdf/toolkit' template_filename = 'some/dir/Awesome-Graphics.pdf' prawn_filename = 'temp.pdf' output_filename = 'output.pdf' Prawn::Document.generate(prawn_filename) do # Generate whatever you want here. text_box "This is some new text!", :at => [100, 300] end PDF::Toolkit.pdftk(prawn_filename, "background", template_filename, "output", output_filename)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With