正如我对已嵌入表单字段的预构建 PDF 所述,我使用 pdtk Available Here 和 active_pdftk gem Available Here。这是我使用的标准流程,但您的可能有所不同:
class Form
def populate(obj)
#Stream the PDF form into a TempFile in the tmp directory
template = stream
#turn the streamed file into a pdftk Form
#pdftk_path should be the path to the executable for pdftk
populated_form = ActivePdftk::Form.new(template,path: pdftk_path)
#This will generate the form_data Hash based on the fields in the form
#each form field is specified as a method with or without arguments
#fields with arguments are specified as method_name*args for splitting purposes
form_data = populated_form.fields.each_with_object({}) do |field,obj|
meth,args = field.name.split("*")
#set the Hash key to the value of the method with or without args
obj[field.name] = args ? obj.send(meth,args) : obj.send(meth)
end
fill(template,form_data)
end
private
def fdf(waiver_data,path)
@fdf ||= ActivePdftk::Fdf.new(waiver_data)
@fdf.save_to path
end
def fill(template,waiver_data)
rand_path = generate_tmp_file('.fdf')
initialize_pdftk.fill_form(template,
fdf(waiver_data,rand_path),
output:"#{rand_path.gsub(/fdf/,'pdf')}",
options:{flatten:true})
end
def initialize_pdftk
@pdftk ||= ActivePdftk::Wrapper.new(:path =>pdftk_path)
end
end
基本上,它的作用是将表单流式传输到临时文件。然后它将其转换为ActivePdftk::Form。然后它读取所有字段并构建Hash 的field_name => value 结构。从这里它生成一个fdf 文件并使用它来填充实际的 PDF 文件,然后将其输出到另一个扁平化的临时文件,以从最终结果中删除字段。
您的用例可能会有所不同,但希望此示例有助于您实现目标。我没有包含所有使用的方法,因为我假设您知道如何执行诸如读取文件之类的操作。此外,我的表单需要更多动态,例如带参数的方法。显然,如果您只是填写原始固定数据,这部分也可以稍作更改。
给定您的类的用法示例称为Form,并且您还有一些其他对象可以填写表格。
class SomeController < ApplicationController
def download_form
@form = Form.find(params[:form_id])
@object = MyObject.find(params[:my_object_id])
send_file(@form.populate(@object), type: :pdf, layout:false, disposition: 'attachment')
end
end
此示例将从@object 获取@form 和populate,然后将其作为填充和展平的PDF 呈现给最终用户。如果您只是需要将其保存回数据库,我相信您可以使用某种上传器解决这个问题。