4

我有一个加入任何数量的 pdf 文件的 rails 应用程序。现在我需要使用 ruby​​ 为加入的 pdf 添加编号。

是否有最先进的方法可以使用 ruby​​ 将文本或其他内容添加到现有的 pdf 文件中?

4

3 回答 3

2

在 Ruby/Rails 中使用 PDF 确实具有挑战性(所以我发现了!)

这是我能够将文本动态添加到 Rails 中的 PDF 的方式。

将此 gem 添加到您的 gem 文件中gem "combine_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 的所有反复试验!

于 2019-07-29T16:34:57.400 回答
1

这个解决方案对我很有效......

Prawn::Document.generate("output.pdf", :template => "/path/to/template.pdf") do
  text "This is a text in a copied pdf.", :align => :center
end
于 2013-10-18T13:31:19.047 回答
1

您可以为此使用CombinePDF

我写它是因为 Prawn 放弃了他们的模板支持,我需要一个本地替换。

您的代码可能如下所示:

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

查看不同格式选项的文档 - 我喜欢用圆角框包围编号(它在功能中,应该很容易使用)。

于 2014-12-07T13:05:13.237 回答