[英]Ruby on Rails & Prawn PDF - Create Customer List
我正在嘗試用Prawn生成PDF報告,我可以通過傳遞單個ID輕松地對show動作進行報告,但我想生成一個包含每個記錄的報告。 像標准的rails scaffold索引頁面。 使用rails它看起來像這樣:
<% @customer.each do |customer| %>
<%= customer.id %>
<%= customer.name %>
<%end%>
簡單!
但是我不確定如何用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
這顯然是不對的。
有任何想法嗎? 謝謝。
使用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
然后在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
show.html.erb
<div class="pdf_link">
<%= link_to "E-version", customer_path(@customer, :format => "pdf") %>
</div>
編輯:
並且不要忘記將pdf包含在config / initializers / mime_types.rb中
Mime::Type.register "application/pdf", :pdf
這是我怎么做的:
class CustomerPdf< Prawn::Document
def initialize(customer)
super(page_size: "A4", page_layout: :portrait)
@customers = customer
bullet_list
end
def bullet_list
@customers.each do |customer|
text "•#{customer.id}- #{customer.name} ", style: :bold
move_down 5
end
end
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.