虾重复模板用不同的内容填充它

时间:2013-05-22 22:08:40

标签: templates repeat prawn

我希望使用prawn生成我的PDF的4页模板。我需要在我的pdf中重复这个模板多次,每次填充不同的内容。

如果我使用:

  Prawn::Document.generate('output.pdf', template: "a_template.pdf")

我在output.pdf中获取了一次模板,后续页面为空。

如果我使用

  ["John", "Jane"].each do |user|
    start_new_page template: 'a_template.pdf', page: 1
    text "Content filled on page 1 for user #{user}"
    3.times { |i| start_new_page template: 'a_template.pdf', template_page: i+2 }
  end

我收到文字"第1页填写的内容供用户使用..."在作为模板第一页的每个页面上重复和覆盖彼此。因此,对于每四个页面,我为在页面上相同位置呈现的所有用户提供内容。

有没有人知道如何让prawn多次包含一个模板,每次都用不同的内容填充模板?我想避免生成一堆PDF文件并将它们连接在一起......

即使我首先将模板连接在一起所需的次数,对于每个用户使用以下代码:

tmp_template = Tempfile.new ['template', '.pdf'], tmpdir

Prawn::Document.generate(tmp_template.path, skip_page_creation: true) do
  users.each do |u|
    4.times { |i| start_new_page template: card_tmpl, template_page: i+1 }
  end
end

然后做:

Prawn::Document.generate('output.pdf', template: tmp_template.path)

为后续用户填写后续模板副本,只要第一页的副本出现在新模板中,它仍然会显示相同的内容!

1 个答案:

答案 0 :(得分:2)

没有其他人出现,所以我做了以下事情。

首先创建没有任何页面的新PDF对象:

pdf = Prawn::Document.new skip_page_creation: true

然后为每个用户:

  1. 创建一个新的,完整的PDF填写所需模板,并将其保存到临时文件tempfile(使用Tempfile)。
  2. 将此临时文件包含在开头创建的PDF(pdf对象)中(假设模板有两页):
  3.       2.times { |i| pdf.start_new_page template: tempfile, template_page: i+1 }
    

    最后,渲染最终的PDF:

    pdf.render 'output.pdf'
    

    表现糟糕。但它的工作原理和这种方式生成的PDF都是用acrobat reader打开的。