您不需要使用多种宝石的组合,您可以只使用一颗宝石!
在 Ruby/Rails 中使用 PDF 确实具有挑战性(所以我发现了!)
这是我能够将文本动态添加到 Rails 中的 PDF 的方式。
将此 gem 添加到您的 gem 文件 gemcombine_pdf
然后你可以使用这样的代码:
# 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"
您可以在此处找到文本框方法的详细信息:https ://www.rubydoc.info/gems/combine_pdf/0.2.5/CombinePDF/Page_Methods#textbox-instance_method
我花了几天时间研究了许多不同的宝石:prawn
wicked_pdf
pdfkit
fillable_pdf
但这对我来说是 2019 年迄今为止最顺利的解决方案。
我希望这可以为某人节省很多时间,这样他们就不必经历我对 PDF 的所有反复试验!