2010-11-07 55 views
11

我需要能夠渲染一些看法爲PDF從的Rails 3項目。我以前從來沒有使用的Ruby/Rails PDF生成技術,所以我研究了一些常用的方法,如PDF ::作家,但我發現的例子和文章到目前爲止似乎已經過時,只適用於導軌2.x.我還沒有看到一個工作Rails3的例子;嘗試自己安裝蝦和prawnto寶石,並再現this Railscasts episode中描述的示例,但我得到的prawnto方法的錯誤未被識別。我不確定這是否是一個實現錯誤或只是一個不兼容的跡象,但看到別人在網上說對蝦在Rails3中不再爲他們工作的我沒有理會另外的跟蹤代碼上共享。從Rails 3生成pdf - 選擇什麼工具?

有沒有人發現,在Rails3中生成PDF工作可靠的解決方案?你能分享一下嗎,還是指向我的外部資源和文檔? 非常感謝!

+1

也Theres上PDFKit一個railscast - http://railscasts.com/episodes/220-pdfkit – alternative 2010-11-07 13:25:40

+0

wicked_pdf是怎麼我現在正在做這些,請參閱@Thilo的答案 – wesgarrison 2011-07-21 15:19:22

回答

7

你見過PDFkit?我敢肯定,這與Rails 3一起工作,它是一個Rack中間件,可以將任何HTML頁面轉換爲PDF格式,以匹配以.pdf結尾的路徑。

11

Prawn可以與Rails 3配合使用。我親自使用過它沒有問題。您必須獲取最新版本的gem prawnto插件。

PDFkit確實具有使用Webkit渲染引擎的優勢,因此您可以使用CSS來定義佈局,並且可以通過Safari和Chrome免費獲得匹配的網頁。它的學習曲線略好於蝦仁。

+1

prawnto不適用於Rails 3,現在看起來已經死了。 – m33lky 2011-11-12 06:21:16

+0

是的,Prawnto現在已經死了。但蝦仍然可以用於導軌。 [瑞安貝茨顯示瞭如何](http://railscasts.com/episodes/153-pdfs-with-prawn-revised) – edgerunner 2011-11-12 23:33:23

1

可以使用Report寶石,它生成的PDF,但也XLSX和CSV。

# a fake Manufacturer class - you probably have an ActiveRecord model 
Manufacturer = Struct.new(:name, :gsa) 

require 'report' 
class ManufacturerReport < Report 
    table 'Manufacturers' do # you can have multiple tables, which translate into multiple sheets in XLSX 
    head do 
     row 'Manufacturer report' 
    end 
    body do 
     rows :manufacturers 
     column 'Name', :name 
     column 'GSA?', :gsa 
    end 
    end 
    # you would want this so that you can pass in an array 
    # attr_reader :manufacturers 
    # def initialize(manufacturers) 
    # @manufacturers = manufacturers 
    # end 
    def manufacturers 
    [ 
     Manufacturer.new('Ford', true), 
     Manufacturer.new('Fischer', false), 
     Manufacturer.new('Tesla', nil), 
    ] 
    end 
end 

當你調用report.pdf.path,一個PDF的產生在tmp目錄:

@manufacturers = Manufacturer.all 
respond_to do |format| 
    format.html # index.html.erb 
    format.json { render json: @manufacturers } 
    format.pdf do 
    report = ManufacturerReport.new(@manufacturers) # using the commented-out code 
    send_file report.pdf.path, :type => 'application/pdf', :disposition => 'attachment', :filename => 'ManufacturersReport.pdf' 
    # tmp files are periodically cleaned up by the operating system, but if you want to be extra clean you can call 
    # report.cleanup 
    # but this may remove the tmp files before apache/nginx/etc. finishes delivering the file 
    end 
end 

最終結果:

report = ManufacturerReport.new 
puts report.pdf.path #=> /tmp/185051406_Report__Pdf.pdf 
puts report.xlsx.path #=> /tmp/185050541_Report__Xlsx.xlsx 

你可以在你的控制器喜歡做

PDF

the pdf

XLSX

the xlsx

注意,XLSX具有自動篩選會自動爲你添加。