在Prawn rails 4上的bounding_box中插入变量

时间:2015-09-02 09:08:35

标签: ruby-on-rails ruby pdf prawn

我想在我的bounding_box文本中插入变量。 当我生成PDF时,我的文字是空白的。

我的控制器动作"显示"按顺序:

def show
  respond_to do |format|
    format.html
    format.pdf do
      pdf = ReportPdf.new(@order, view_context)
      send_data pdf.render, filename: 'report.pdf', type: 'application/pdf'
    end
  end
end

我的报告文件(app / pdfs / report_pdf.rb)

class ReportPdf < Prawn::Document
require 'prawn/table'

  def initialize(order, view)
    super()
    @view = view
    @order = order
    image "#{Rails.root}/app/assets/images/pdf/header.jpg", width: 540, height: 60

    # The cursor for inserting content starts on the top left of the page. Here we move it down a little to create more space between the text and the image inserted above
    y_position = cursor - 50

    # The bounding_box takes the x and y coordinates for positioning its content and some options to style it
    bounding_box([0, y_position], :width => 270, :height => 300) do
        text "Lorem ipsum", size: 15, style: :bold
        text "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse interdum semper placerat. Aenean mattis fringilla risus ut fermentum. Fusce posuere dictum venenatis. Aliquam id tincidunt ante, eu pretium eros. Sed eget risus a nisl aliquet scelerisque sit amet id nisi. Praesent porta molestie ipsum, ac commodo erat hendrerit nec. Nullam interdum ipsum a quam euismod, at consequat libero bibendum. Nam at nulla fermentum, congue lectus ut, pulvinar nisl. Curabitur consectetur quis libero id laoreet. Fusce dictum metus et orci pretium, vel imperdiet est viverra. Morbi vitae libero in tortor mattis commodo. Ut sodales libero erat, at gravida enim rhoncus ut."
    end

    bounding_box([300, y_position], :width => 270, :height => 300) do
        text "#{@order.company_fact}", size: 15, style: :bold
        text "#{@order.civility_fact} #{@order.last_name_fact} #{@order.first_name_fact}"
        text "#{@order.address_fact} "
    end

    table product_rows do
        row(0).font_style = :bold
        self.header = true
        self.row_colors = ['DDDDDD', 'FFFFFF']
        self.column_widths = [40, 300, 200]
    end
  end

  def product_rows
    [['#', 'Pictogram code', 'Price']] +
        @order.pictograms.map do |p|
            [p.id, p.code, '/']
        end
  end  end

我创建了2个bounding_box,一个带有示例文本,另一个带有来自变量的文本。第一个工作完美,但我包含变量,文本是空白的。

我认为它是关于上下文的,在google很多人添加pdf.text来包含变量但在我的情况下我在初始化方法中不在控制器中。

1 个答案:

答案 0 :(得分:0)

由于您将@order对象作为参数传递给ReportPdf的构造函数,因此您应该通过本地参数访问它

    text "#{order.company_fact}", size: 15, style: :bold
    text "#{order.civility_fact} #{order.last_name_fact} #{order.first_name_fact}"
    text "#{order.address_fact} 

您应该将参数order添加到方法产品行

def product_rows(order)
    [['#', 'Pictogram code', 'Price']] +
    order.pictograms.map do |p|
        [p.id, p.code, '/']
    end
end

并像table product_rows(order) do

一样调用它