2016-12-14 81 views
0

我想通過在我的rails應用程序中使用wicked_pdf寶石來生成pdf。我在我的文件中有以下代碼。無法使用wicked_pdf gem在rails中生成pdf?

gemfile 

gem 'wicked_pdf' 
gem 'wkhtmltopdf-binary' 

和在配置/初始化/ wicked_pdf.rb文件

WickedPdf.config = { 
    # Path to the wkhtmltopdf executable: This usually isn't needed if using 
    # one of the wkhtmltopdf-binary family of gems. 
    # exe_path: '/usr/local/bin/wkhtmltopdf', 
    # or 
    # exe_path: Gem.bin_path('wkhtmltopdf-binary', 'wkhtmltopdf') 

    # Layout file to be used for all PDFs 
    # (but can be overridden in `render :pdf` calls) 
    # layout: 'pdf.html', 
} 
    module WickedPdfHelper 
    if Rails.env.development? 
    if RbConfig::CONFIG['host_os'] =~ /linux/ 
     executable = RbConfig::CONFIG['host_cpu'] == 'x86_64' ? 
'wkhtmltopdf_linux_x64' : 'wkhtmltopdf_linux_386' 
    elsif RbConfig::CONFIG['host_os'] =~ /darwin/ 
     executable = 'wkhtmltopdf_darwin_386' 
    else 
     raise 'Invalid platform. Must be running linux or intel-based Mac OS.' 
    end 

    WickedPdf.config = { exe_path: 
"#{Gem.bin_path('wkhtmltopdf-binary').match(/(.+)\/.+/).captures.first}/#{executable}" 
} 
    end 
end 

和在控制器

def show 
    respond_to do |format| 
     format.html 
     format.pdf do 
    render pdf: "file_name" # Excluding ".pdf" extension. 
     end 
    end 
    end 

/config/initializers/mime_types.rb

Mime::Type.register "application/xls", :xls 
Mime::Type.register "application/xlsx", :xlsx 
Mime::Type.register "application/pdf", :pdf unless Mime::Type.lookup_by_extension(:pdf) 

和文件中views/invoises/show.pdf.erb

<p> 
     Invoice No: 
     <%= @invoise.invoice_no %> 
    </p> 

    <p> 
    Due date: 
    <%= @invoise.due_date %> 
    </p> 

    <p> 
    Total Amount: 
    <%= @invoise.total_amount %> 
    </p> 

,我在瀏覽器中點擊URL是/invoises/BRUqWOeEVNSN6GCwxQqLGg%253D%253D.pdf

蔭無法生成PDF文件。而且我也沒有得到任何錯誤。當我點擊上面的網址時,我的網頁不斷加載。我沒有得到任何輸出。

回答

0

可以這樣做(例如基於RailsCasts系列):

的environment.rb

require 'pdf/writer' 
Mime::Type.register 'application/pdf', :pdf 

products_controller.rb

def index 
    @products = Product.find(:all) 
    respond_to do |format| 
    format.html 
    format.pdf do 
     send_data ProductDrawer.draw(@products), filename: 'products.pdf', type: 'application/pdf', disposition: 'inline' 
    end 
    end 
end 

product_drawer.rb

def self.draw(products) 
    pdf = PDF::Writer.new 
    products.each do |product| 
    pdf.text product.name 
    end 
    pdf.render 
end 

的意見/產品/ index.html.erb

<p><%= link_to 'PDF Format', formatted_products_path(:pdf) %></p> 

我認爲這是實現此功能更好的方法。

相關問題