【问题标题】:Prawn PDF and muliplte records对虾 PDF 和多条记录
【发布时间】:2017-04-12 20:26:40
【问题描述】:

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

目前我让它们通过 id 为单个 pdf 生成并且效果很好。

显示

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 %>

【问题讨论】:

    标签: ruby-on-rails prawn


    【解决方案1】:

    首先,你必须添加一个带有新方法路径的路由:

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

    然后调用视图中的方法:

    &lt;td&gt;&lt;%= link_to 'Download All Records', agreement_all_records_path(), :target =&gt; "_blank" %&gt;&lt;/td&gt;

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

    def all_records
    
      @agreements = Agreement.all
    
      pdf = AgreementsPdf.new(@agreements)
      send_data pdf.render,filename:'agreements.pdf',type:'application/pdf', disposition: 'inline'
    end

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

    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

    希望这会给你一个想法

    【讨论】:

    • 如何在视图中调用变量?
    • 我编辑答案并添加视图和路线。我没有测试过,只是代码来展示如何做到这一点
    • 成功了。感谢您的帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多