5

I have an rails application that is joining any count of pdf files. Now I need to add a numbering to the joined pdf using ruby.

Is there a state of the art way to add text or other content to an existing pdf file using ruby?

1

3 Answers 3

2

Working with PDF's is really challenging in Ruby/Rails (so I have found out!)

This is the way I was able to add text dynamically to a PDF in rails.

add this gem to your gem file gem "combine_pdf"

and then you can use code like this:

# get the record from the database to add dynamically to the pdf
user = User.last

# get the existing pdf
pdf = CombinePDF.load "#{Rails.root}/public/pdf/existing_pdf.pdf"

# create a textbox and add it to the existing pdf on page 2
pdf.pages[1].textbox "#{user.first_name} #{user.last_name}", height: 20, width: 70, y: 596, x: 72

# output the new pdf which now contains your dynamic data
pdf.save "#{Rails.root}/public/pdf/output#{Time.now.to_s}.pdf"

You can find details of the textbox method here: https://www.rubydoc.info/gems/combine_pdf/0.2.5/CombinePDF/Page_Methods#textbox-instance_method

I spent days on this working through a number of different gems: prawn wicked_pdf pdfkit fillable_pdf

But this was by far the most smooth solution for me as of 2019.

I hope this saves someone a lot of time so they don't have to go through all the trial and error I had to with PDF's!!

Sign up to request clarification or add additional context in comments.

Comments

1

This solution worked well for me...

Prawn::Document.generate("output.pdf", :template => "/path/to/template.pdf") do
  text "This is a text in a copied pdf.", :align => :center
end

1 Comment

Be aware that Prawn is not supporting templates since December 2013:groups.google.com/forum/#!topic/prawn-ruby/S6gXA-i0-do
1

You can use CombinePDF for that.

I wrote it because Prawn dropped their template support and I needed a native replacement.

Your code might look something like this:

pdf = CombinePDF.new
pdf << CombinePDF.new("file1.pdf")
pdf << CombinePDF.new("file2.pdf")
pdf.number_pages
pdf.save "output.pdf"

look at the documentation for the different formatting options - I love to surround the numbering with a rounded box (it's in the features, should be easy to play with).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.