【问题标题】:Set dynamically height for entire Prawn PDF Document为整个 Prawn PDF 文档动态设置高度
【发布时间】:2015-08-06 13:16:01
【问题描述】:

尝试使用 Rails 的 Prawn gem 生成文档时遇到问题

我要做的是为我的 pdf 设置可变高度,因此根据数据库中的一些查询,PDF 高度会改变。我这样做是因为我需要一个单页 PDF 文档。

目前,我的代码如下所示:

pdf = Prawn::Document.new(page_size: [297.64, 419.53], margin: 0)

....

data = [ ["Header1", "Header2", "Header3", "Header4", "Header5", "Header6"] ]

// here is the variable data
cart.cart_products.each do |cp|
  arr = [
    cp.product_code,
    cp.product_description,
    cp.amount,
    cp.product_metric,
    cp.product_unit_value,
    cp.total_value
  ]

  data.push(arr)
end

// populating the table with data
pdf.table(data, :cell_style => {:border_width => 0}, :column_widths => [45, 80, 30, 42.36, 50, 50]) do |table|
  table.row(0).border_width = 0.1.mm
  table.row(0).font_style = :bold
  table.row(0).borders = [:bottom]
end

....

pdf.render_file("path/to/dir/document.pdf")

谁能帮我解决这个问题?谢谢。

【问题讨论】:

    标签: ruby-on-rails pdf prawn


    【解决方案1】:

    在不知道你到底要调整什么的情况下,我不得不在这里做一些猜测。

    所以我会为您返回的数据和最小文档高度建立某种行高。

    line_height = 14
    min_height = 419.53
    

    然后我会运行查询并计算结果。然后我会弄清楚可变高度是什么并将其添加到最小高度。

    variable_height = results.length * line_height
    height = min_height + variable_height
    

    最后:

    pdf = Prawn::Document.new(page_size: [297.64, height], margin: 0)
    

    这样的东西应该可以根据您的特定需求进行调整。

    【讨论】:

    • 正是我想要的!谢谢!
    【解决方案2】:

    Thomas Leitner 在 GitHub 问题评论 (https://github.com/prawnpdf/prawn/issues/974#issuecomment-239751947) 中提出了更好的选择:

    正是我想要发布的内容? - 就这样吧:

    您可能会为您的文档使用一个非常大的高度,这样虾就不会自动创建一个新的高度。完成所有操作后,使用 Prawn::Document#y 确定您当前的垂直位置。

    然后你可以使用 Prawn::Document#page (一个 PDF::Core::Page 对象)来调整页面的 MediaBox,比如:

    require 'prawn'
    
    Prawn::Document.generate("test.pdf", page_size: [100, 2000], margin: 10) do |doc|
      rand(100).times do
        doc.text("some text")
      end
      doc.page.dictionary.data[:MediaBox] = [0, doc.y - 10, 100, 2000]
    end
    

    感谢 Thomas Leitner (https://github.com/gettalong)

    【讨论】:

    • 它对我有用 :) 我认为这比其他解决方案简单得多。谢谢
    猜你喜欢
    • 1970-01-01
    • 2015-07-01
    • 2013-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-12
    • 2011-06-04
    • 2018-06-30
    相关资源
    最近更新 更多