在线填写并更新上传的PDF表单并将其保存回服务器 – Ruby on Rails

这是要求:

在我在Ruby on Rails中开发的web应用程序中,我们需要选择将PDF form template上传到系统,在浏览器中将其恢复,用户应该能够在线填写PDF表单并最终保存它回到服务器。

然后,用户将从应用程序下载更新的PDF表单。 我搜索了很多,但找不到合适的解决方案。 请建议。

正如我所说的已经嵌入的表单字段的预建PDF,我使用pdtk Available Here和active_pdftk gem 此处可用 。 这是我使用的标准流程,但您的可能会有所不同:

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

这个例子将取@form并从@object populate它,然后将它作为填充和展平的PDF呈现给最终用户。 如果您只是需要将其保存回数据库,我相信您可以使用某种上传器来解决这个问题。