首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >无法在rails中用wicked_pdf gem生成pdf?

无法在rails中用wicked_pdf gem生成pdf?
EN

Stack Overflow用户
提问于 2016-12-14 14:30:03
回答 1查看 971关注 0票数 0

我试图在我的pdf应用程序中使用wicked_pdf gem来生成rails。我的文件中有下面的代码。

代码语言:javascript
复制
gemfile

 gem 'wicked_pdf'
 gem 'wkhtmltopdf-binary'

和config/initializers/ and _pdf.rb文件中的

代码语言:javascript
复制
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

在控制器中

代码语言:javascript
复制
  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

代码语言:javascript
复制
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

代码语言:javascript
复制
    <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文件。我也不会犯任何错误。当我点击上面的网址时,我的网页将继续加载。我没有得到任何输出。

EN

回答 1

Stack Overflow用户

发布于 2016-12-15 21:11:17

您可以这样做(基于RailsCasts系列的示例):

environment.rb

代码语言:javascript
复制
require 'pdf/writer'
Mime::Type.register 'application/pdf', :pdf

products_controller.rb

代码语言:javascript
复制
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

代码语言:javascript
复制
def self.draw(products)
  pdf = PDF::Writer.new
  products.each do |product|
    pdf.text product.name
  end
  pdf.render
end

views/products/index.html.erb

代码语言:javascript
复制
<p><%= link_to 'PDF Format', formatted_products_path(:pdf) %></p>

我认为这是实现此功能的更好方法。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41145091

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档