高级示例
这是带有示例的高级方法
class FundsController < ApplicationController
def index
@funds = Fund.all_funds(current_user)
end
def show
@fund = Fund.find(params[:id])
respond_to do |format|
format.html
format.pdf do
pdf = FundsPdf.new(@fund, view_context)
send_data pdf.render, filename:
"fund_#{@fund.created_at.strftime("%d/%m/%Y")}.pdf",
type: "application/pdf"
end
end
end
end
我上面的代码我们有这条线 FundsPdf.new(@fund, view_context)
。这里我们用 @fund 实例和 view_context 初始化 FundsPdf 类,以在 FundsPdf 中使用辅助方法。FundsPdf 看起来像这样
class FundPdf < Prawn::Document
def initialize(fund, view)
super()
@fund = fund
@view = view
upper_half
lower_half
end
def upper_half
logopath = "#{Rails.root}/app/assets/images/logo.png"
image logopath, :width => 197, :height => 91
move_down 10
draw_text "Receipt", :at => [220, 575], size: 22
move_down 80
text "Hello #{@invoice.customer.profile.first_name.capitalize},"
end
def thanks_message
move_down 15
text "Thank you for your order.Print this receipt as
confirmation of your order.",
:indent_paragraphs => 40, :size => 13
end
end
这是使用 Prawn gem 生成 PDF 的最佳方法之一。