在我的 rails 应用程序中,用户在不同的模型中输入了大量数据。用户应该有可能从他在不同模型中输入的所有数据创建一个 pdf 文件。哪个 ruby gem 提供此功能以及如何使用它?我已经研究过 Prawn,但无法弄清楚,它是否提供了使用来自不同模型的数据创建一个 pdf 的功能。
这里排序教程如何使用prawn pdf打印相关模型
例如我有父模型,它有很多汽车(相关模型)
class Parent < ActiveRecord::Base
has_many :cars, dependent: :destroy
accepts_nested_attributes_for :cars, allow_destroy: :true
end
在我的控制器中,我定义如下
class ParentsController < ApplicationController
def show
@parent = Parent.find(params[:id])
respond_to do |format|
format.html
format.pdf do
# here you call prawn pdf class (see below)
pdf = ParentPdf.new(@parent)
send_data pdf.render, filename: 'family.pdf',
type: 'application/pdf',
disposition: 'inline'
end
end
end
end
end
end
您可以按照 app/pdf/parent_pdf.rb 创建文件夹和文件,它继承自 Prawn::Document 类
class ParentPdf < Prawn::Document
def initialize(parent)
# init margin and size
super(top_margin: 5, left_margin: 5, page_size: 'A4', page_layout: :landscape, print_scaling: :none)
# pass argument to variable
@parent = parent
# here is you access related models like you access from your controller
@cars = @parent.cars
# you print the model
print_header
# and print related model
print_detail
end
def print_header
bounding_box([420, 510], width: 350, height: 90) do
text "name: #{@parent.name}", size: 11
end
end
def print_detail
font 'Helvetica'
font_size 9
@cars.each do |car|
text "car: #{car.name}", size: 11
end
end
end
最后是通过超链接打印pdf的命令
<%= link_to 'print pdf', parent_path(parent, format: "pdf"), :class => 'btn btn-sm btn-secondary' %>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句