如何在Rails中创建表示一个数据表(包括每个新页面上的列标题)的多页PDF?

时间:2012-05-23 01:24:17

标签: pdf-generation ruby-on-rails-3.2 prawn pdfkit wicked-pdf

如何在Rails中创建表示一个数据表(包括每个新页面上的列标题)的多页PDF?我看过许多wicked-pdf,pdfkit和prawn的例子,但是没有看到任何专门解决后续页面溢出的问题以及需要重复每个新页面的标题。谢谢你的帮助。

3 个答案:

答案 0 :(得分:4)

我使用Prawn来生成我的pdf,并且可以得到你想要的效果:

def render_photo_table(pdf)
  ps = self.photos.map do |photo|
    [photo.filename, photo.image_height, photo.image_width]
  end
  ps.insert(0, ['Filename', 'Height', 'Width'])
  pdf.table(ps) do |table|
    table.header = true
  end
end

这会在每个页面的顶部产生一个标题(在数组位置0中设置)。

答案 1 :(得分:2)

这也有问题,但发现了一个相当简单的方法(经过多次头痛)才能做到这一点。

在项目上方放置一个浮动的地标div,这样您就可以获得起始坐标(我称之为ID item_top)。

然后使用顶级div数据渲染页面,类为“unbreakable”。

还包括一个强制分页的类:

.page-breaker {
  display: block;
  clear: both;
  page-break-after: always;
}

然后渲染

<script>
// Very top of items
var current_top = $('#item_top').offset().top;
// Check distance from top of page to bottom of item
// If greater than page size put page break and headers before
// Reset top of page to top of item.
$('.unbreakable_section').each(function(index) {
  var item_bottom = $(this).offset().top + $(this).outerHeight(true);
  if ((item_bottom - current_top) > 1250) {
    $(this).before("<div class='page-breaker'></div>");
    $(this).before("Headings Div here");
    current_top = $(this).offset().top - 48; // item - header height
  }
});

</script>

如果空间超出页面高度,这将测量自上次分页以来的垂直空间并开始新页面并在其上方放置标题。 (1250是近似值,对我来说足够接近 - 我在页面上也有一个页脚,因此高度可能因您的设置而异。)

在100页文档上测试按预期工作。

答案 2 :(得分:1)

我们为此编写了内部jquery代码。

如果您有以下网页:

<div class="mypage">
  <div class="mypage_footer"></div>
</div>

外面你有:

<div class="mybox">
  <table><tbody><tr><td>omg</td></tr></tbody></table>
</div>
<div class="mybox">
  <table><tbody><tr><td>lol</td></tr></tbody></table>
</div>

假设您有一个固定的页面高度(最好是A4大小),您可以使用jquery:

  • 通过从mypage的高度减去页面子项的$(元素).height()来计算mypage中的剩余空间
  • 虽然有剩余空间,但请从页面外部选择一个mybox并将其放在页面内
  • 如果没有更多空间,请创建第一页的副本并重复。
相关问题