Ruby on Rails & Prawn PDF - 创建客户列表



我正试图用Prawn生成一个PDF报告,通过传递单个ID,我可以很容易地让它对表演动作进行报告,但我想为其中的每个记录生成一个。就像标准的rails scaffold索引页一样。使用轨道,它看起来像这样:

<% @customer.each do |customer| %>
<%= customer.id %>
<%= customer.name %>
<%end%>

轻松!

但我不知道如何处理虾。。

类似于:

def index
 @customer = Customer.all
  respond_to do |format|
  format.html
   Prawn::Document.generate("customer_list.pdf") do |pdf|
   pdf.text "#{@customer.id} "
    pdf.text "#{@customer.name} "  
       end
    end
end

这显然是不对的。

有什么想法吗?非常感谢。

使用对虾Gemfile=>宝石"对虾"、bundle很容易

假设您有客户型号:

customer_controller.rb

def show
   @customer = Customer.find(params[:id])
   respond_to do |format|
     format.html
     format.pdf do
        pdf = CustomerPdf.new(@customer)
        send_data pdf.render, filename: "customer_#{id}.pdf",
                              type: "application/pdf",
                              disposition: "inline"
     end
   end
end

然后只需在apps目录下创建pdfs文件夹,并创建文件customer_pdf.rb

class CustomerPdf< Prawn::Document
  def initialize(customer)
    super()
    @customer = customer
    text "Id##{@customer.id}"
    text "Name##{@customer.name}"
  end
end

show.html.erb

  <div class="pdf_link">
    <%= link_to "E-version", customer_path(@customer, :format => "pdf") %>
  </div>

编辑:

并且不要忘记将pdf包含在config/initializers/mimit_types.rb

Mime::Type.register "application/pdf", :pdf

我认为自定义渲染器是解决问题的好方法。Jose Valim(!Rails核心开发人员)在他的书中描述了最好的方法。第一章的开头在这里是免费的。这一章正是你真正需要的。

我就是这样做的:

class CustomerPdf< Prawn::Document
 def initialize(customer)
  super(page_size: "A4", page_layout: :portrait)
  @customers = customer
  bullet_list
 end
 def bullet_list
  @customers.each do |customer|
      text "•#{customer.id}- #{customer.name} ", style: :bold
    move_down 5
  end
 end
end

最新更新