12

我需要能够将Rails 3项目中的一些视图呈现为 PDF。我以前从未在 ruby​​/rails 中使用过 PDF 生成技术,因此我研究了一些流行的方法,例如PrawnPDF::Writer,但到目前为止我发现的所有示例和文章似乎都已过时,仅适用于 rails 2.x . 我还没有看到一个有效的 Rails3 例子;尝试自己安装 prawn 和 prawnto gems 并复制此 Railscasts episode中描述的示例,但我收到了 prawnto 方法无法识别的错误。我不确定这是实现错误还是只是不兼容的迹象,但看到其他人在网上分享了在 Rails3 中不再为他们工作我没有费心进一步跟踪代码。

有没有人找到在 Rails3 中生成 pdf 的可靠解决方案?您能否分享它或将我指向外部资源和文档?非常感谢!

4

5 回答 5

11

一个老问题的新答案,以防其他人偶然发现:WickedPDF(它使用 wkhtmltopdf 就像 PDFkit 一样)使这变得轻而易举。

https://github.com/mileszs/wicked_pdf

于 2011-07-09T15:58:01.087 回答
11

Prawn确实适用于 Rails 3。我个人使用它没有任何问题。您必须获得最新版本的 gem和 rails 的prawto插件。

PDFkit确实具有使用 Webkit 渲染引擎的优势,因此您可以使用 CSS 来定义您的布局,并且您可以通过 Safari 和 Chrome 免费获得匹配的网页。它的学习曲线比 Prawn 稍微好一些。

于 2010-11-07T23:18:09.033 回答
7

你见过PDFkit吗?我很确定它适用于 Rails 3,它是一个 Rack 中间件,可以将任何 HTML 页面转换为与以 .pdf 结尾的路由匹配的 PDF

于 2010-11-07T13:25:45.550 回答
2

关于虾,这里是 Rails 3 的无缝集成,似乎工作得很好:https ://github.com/Whoops/prawn-rails

于 2013-08-25T10:29:19.750 回答
1

您可以使用生成 PDF 以及 XLSX 和 CSV的Report gem。

# 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,将在 tmp 目录中生成 PDF:

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

您可以在控制器中执行此操作,例如:

@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

最终结果:

PDF格式

pdf

XLSX

xlsx

请注意,XLSX 会自动为您添加一个自动过滤器。

于 2013-04-04T17:33:01.850 回答