首页 文章

从Rails 3生成pdf - 可以选择哪种工具?

提问于
浏览
11

我需要能够从 Rails 3 项目中将一些视图呈现为PDF . 我之前从未使用过ruby / rails的PDF生成技术,因此我研究了一些流行的方法,如Prawn和PDF :: Writer,但到目前为止我发现的所有示例和文章似乎都过时了,只适用于rails 2.x . 我还没有看到一个有效的Rails3示例;尝试自己安装虾和prawnto宝石并重现this Railscasts episode中描述的例子,但我不知道这是一个实现错误还是只是一个不兼容的迹象,但是看到其他人在网上分享这个对象不再适用于他们在Rails3中我没有打扰进一步跟踪代码 .

有没有人在Rails3中找到一个可靠的pdf生成解决方案?您可以分享它或指向外部资源和文档吗?十分感谢!

5 回答

  • 7

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

    https://github.com/mileszs/wicked_pdf

  • 11

    Prawn确实与Rails 3一起使用 . 我亲自使用它没有任何问题 . 你必须获得gem的最新版本和rails的prawnto插件 .

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

  • 2

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

  • 1

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

  • 11

    您可以使用Report gem,它生成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 时,将在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

    the pdf

    XLSX

    the xlsx

    请注意,XLSX会自动为您添加自动过滤器 .

相关问题