nic*_*abs 6 ruby pdf ruby-on-rails block prawn
我正在尝试用Prawn生成PDF报告,我可以通过传递单个ID轻松地对show动作进行报告,但我想生成一个包含每个记录的报告.像标准的rails scaffold索引页面.使用rails它看起来像这样:
<% @customer.each do |customer| %>
<%= customer.id %>
<%= customer.name %>
<%end%>
Run Code Online (Sandbox Code Playgroud)
简单!
但是我不确定如何用Prawn做到这一点..
就像是:
def index
@customer = Customer.all
respond_to do |format|
format.html
Prawn::Document.generate("customer_list.pdf") do |pdf|
pdf.text "#{@customer.id} "
pdf.text "#{@customer.name} "
end
end
end
Run Code Online (Sandbox Code Playgroud)
这显然是不对的.
有任何想法吗?谢谢.
使用Prawn,Gemfile => gem'prawn ',bundle很容易
假设您有客户模型:
customers_controller.rb
def show
@customer = Customer.find(params[:id])
respond_to do |format|
format.html
format.pdf do
pdf = CustomerPdf.new(@customer)
send_data pdf.render, filename: "customer_#{id}.pdf",
type: "application/pdf",
disposition: "inline"
end
end
end
Run Code Online (Sandbox Code Playgroud)
然后在apps目录下创建pdfs文件夹,并创建文件customer_pdf.rb
class CustomerPdf< Prawn::Document
def initialize(customer)
super()
@customer = customer
text "Id\##{@customer.id}"
text "Name\##{@customer.name}"
end
end
Run Code Online (Sandbox Code Playgroud)
show.html.erb
<div class="pdf_link">
<%= link_to "E-version", customer_path(@customer, :format => "pdf") %>
</div>
Run Code Online (Sandbox Code Playgroud)
编辑:
并且不要忘记将pdf包含在config/initializers/mime_types.rb中
Mime::Type.register "application/pdf", :pdf
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2953 次 |
| 最近记录: |