Prawn PDF和muliplte记录

时间:2017-04-12 00:44:29

标签: ruby-on-rails prawn

我希望使用Prawn PDF和rails 4.2将所有记录提取到单个pdf。

目前我按照个人pdf的ID生成它们并且运行良好。

显示

def show
    @agreement = Agreement.find(params[:id])

    respond_to do |format|
      format.html
      format.pdf do
        pdf = AgreementPdf.new(@agreement)
        send_data pdf.render, filename: "Agreement - #{@agreement.entity}", type: "application/pdf", disposition: "inline"
      end
    end
  end

表格中的索引

<% @agreements.each do |agreement| %>
      <tr>
        <td><%= agreement.entity %></td>
        <td><%= link_to 'Download', agreement_path(agreement.id, format: 'pdf'), :target => "_blank" %></td>
            </tr>
    <% end %>

1 个答案:

答案 0 :(得分:1)

首先,您必须添加一个包含新方法路径的路径:

&#13;
&#13;
get '/agreements/all_records' => 'agreements#all_records', :as => :agreement_all_records
&#13;
&#13;
&#13;

然后在视图中调用方法:

&#13;
&#13;
<td><%= link_to 'Download All Records', agreement_all_records_path(), :target => "_blank" %></td>
&#13;
&#13;
&#13;

在控制器中看起来像这样:

&#13;
&#13;
def all_records

  @agreements = Agreement.all

  pdf = AgreementsPdf.new(@agreements)
  send_data pdf.render,filename:'agreements.pdf',type:'application/pdf', disposition: 'inline'
end
&#13;
&#13;
&#13;

报告可能看起来像这样(假设协议模型有id,name字段):

&#13;
&#13;
require 'prawn/table'

class AgreementsPdf < PdfReport
  TABLE_WIDTHS = [100, 100]
  PAGE_MARGIN = [40, 40, 40, 40]


  def initialize(agreements=[])
    super(:page_size => "LEGAL",  margin: PAGE_MARGIN, :page_layout => :landscape)
    @agreements = agreements
    display_table
  end

  private

  def display_table
    if table_data.empty?
      text "None data"
    else
      table(table_data,column_widths: TABLE_WIDTHS, :cell_style => { size: 10 } )       
    end
  end

  def table_data
    @table_data ||= @agreements.map { |e| [e.id, e.name] }
  end

end
&#13;
&#13;
&#13;

希望这会给你一个想法