【发布时间】:2021-09-17 07:22:11
【问题描述】:
我正在尝试使用 prawn gem 生成 pdf。目标是使用通过表单提交的数据创建自定义 pdf。这些示例可能是报告、发票、出生证明等。我已经初步成功地生成了 a pdf。这个名为“报告”。
#Controller
class TemplatesController < ApplicationController
before_action :set_template, only: %i[ show edit update destroy ]
def show
@templates = Template.all
respond_to do |format|
format.html
format.pdf do
pdf = ReportPdf.new
send_data pdf.render, filename: 'report.pdf', type: 'application/pdf',
disposition: "inline"
end
end
end
#....lots of code
# Only allow a list of trusted parameters through.
def template_params
params.require(:template).permit(:name, :address, :idnumber)
end
end
这可以工作并生成一个带有如下模板的pdf:
#My Report.pdf. Similar templates exist for birth certificates deeds, invoices and
other pdf documents
class ReportPdf < Prawn::Document
def initialize
super()
header
text_content
end
def header
#Inserts an image in the pdf file and sets its size.
image "#{Rails.root}/app/assets/images/logo.jpg", width: 230, height: 75
end
def text_content
bounding_box([0, y_position], :width => 270, :height => 300) do
text "This is a sample report by #{@template.name} who lives at #
{@template.address} etc etc"
end
end
end
最后,我想向用户展示一个表单:
<%=form_with url: templates_path(format: "pdf"), local: true,method: :get do |form| %>
<%= form.label :pdf_type %>
<%= form.select :pdf_type,
options_for_select([
['Report','Report'],
['Birth_certificate','Birth Certificate'],
['Deed','Deed'],
['Title','Title']]),
{}, {class: "form-control" } %>
<%= form.button "Download", class: "btn btn-primary" %>
<% end %>
可以看出,报告 pdf 被“绑定”到控制器操作,因此当前允许生成一个 pdf(“报告”)。没有灵活性。要生成不同类型的报告,我必须手动更改控制器代码 如何允许用户从表单中选择 pdf 类型并生成他选择的 pdf?
【问题讨论】:
标签: ruby-on-rails