How to edit or write on existing PDF with Ruby?

前端 未结 7 1150
眼角桃花
眼角桃花 2020-12-01 10:35

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 resul

7条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-01 10:45

    You don't need to use a combination of gems you can use just one gem!

    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!!

提交回复
热议问题