2012-04-02 80 views
5

我正在嘗試生成一份PDF格式的報告,我可以通過傳遞單個ID來輕鬆地完成關於展示操作的報告,但是我想生成一個報告與其中的每一條記錄。就像標準的導軌腳手架索引頁面一樣。使用軌道它看起來像這樣:Ruby on Rails&Prawn PDF - 創建客戶列表

<% @customer.each do |customer| %> 
<%= customer.id %> 
<%= customer.name %> 
<%end%> 

簡單!

但我不知道如何用蝦做..

喜歡的東西:

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 

其中明確是不正確的。

任何想法?謝謝。

+0

我知道你問大蝦,但我已經通過生成我的報告,HTML/CSS,然後將其轉換爲PDF格式,採用了更好的體驗' wkhtmltopdf'應用程序。有一個名爲'PDFKit'的封裝寶石,可以讓它輕鬆工作。 wkhtmltopdf:http://code.google.com/p/wkhtmltopdf/和pdfkit:https://github.com/pdfkit/PDFKit用於生成複雜報告我發現使用HTML生成它們更容易,而不是使用PDF /直接對蝦。 – 2012-04-02 22:33:04

回答

5

它很容易與的Gemfile =>寶石 '大蝦',

做比方說你有客戶型號:

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 

然後就創建PDF文件文件夾下的應用目錄下,並創建文件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到配置/初始化/ mime_types.rb

Mime::Type.register "application/pdf", :pdf 
+0

這是不是隻顯示來自show path的一個客戶的PDF?我試圖列出每個客戶的名單。謝謝。 – nicktabs 2012-04-02 20:49:18

+0

是的,這個例子更多地顯示'customers#show'而不是'customers#index',但是這個想法是相似的。而不是在CustomerPdf中採用一個'customer'對象,而是讓您的客戶數組遍歷並調用相同的'text()'方法,然後附加一個換行符。 – 2012-04-02 22:31:24

+0

當然這個想法會類似 – 2012-04-03 03:11:13

2

我覺得你的問題很好的解決方案是自定義的呈現。 Jose Valim(!Rails核心開發人員)在他的book中描述了最好的方法。第一章開頭免費提供here。這一章真的是你需要的。

1

這是我如何做到這一點:

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