0

我需要将我的@manufacturers 数组呈现为 pdf,但只能通过单击视图中的某个链接来实现...现在我有这样的代码

def index
    @manufacturers = Manufacturer.all


    respond_to do |format|
      format.html # index.html.erb
      format.json { render json: @manufacturers }
      format.pdf { render :layout => false }
    end
  end

我在网络上看到了很多例子,但我没有找到明确和实际的例子......我的数组@manufacturers 在 a4 pdf 表中有多简单?

4

2 回答 2

1

除了 prawn,还可以使用 prawnto rails 插件来帮助将 PDF 呈现为模板。

有关插件,请参阅https://github.com/prior/prawnto ,有关如何使用它,请参阅http://railscasts.com/episodes/153-pdfs-with-prawn 。

于 2012-11-27T23:14:47.710 回答
0

[注意:报告宝石目前仅在信纸大小的纸张上生成,欢迎使用 A4 补丁!]

您可以使用Report gem,它使用 Prawn 以及 XLSX 和 CSV 生成 PDF。

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

require 'report'
class ManufacturerReport < Report
  table 'Manufacturers' do
    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-04T00:05:57.043 回答