如何在reportlab中对对象进行分组,以便在新页面中保持在一起
我正在使用reportlab生成一些PDF文件。有一个部分是重复的,里面有一个标题和一个表格:
Story.append(Paragraph(header_string, styleH))
Story.append(table)
我该如何把段落和表格放在一起(在latex中我会把它们放在同一个环境里),这样在分页的时候,段落和表格就能保持在一起?现在有时候段落会在一页的末尾,而表格却在下一页的顶部开始。
3 个回答
5
使用段落样式可能会更好,所以我想把这个补充到这个超级老的回答里。
在看到@memyself的回答后,我在他们的更新日志中发现了这个。
* `KeepWithNext` improved:
Paragraph styles have long had an attribute keepWithNext, but this was
buggy when set to True. We believe this is fixed now. keepWithNext is important
for widows and orphans control; you typically set it to True on headings, to
ensure at least one paragraph appears after the heading and that you don't get
headings alone at the bottom of a column.
header = ParagraphStyle(name='Heading1', parent=normal, fontSize=14, leading=19,
spaceAfter=6, keepWithNext=1)
14
你可以尝试把它们放在一个 KeepTogether
的流式组件里,像这样:
Story.append(KeepTogether([Paragraph(header_string, styleH), table])
不过要注意,最后一次我检查的时候,这个功能的实现并不是很完美,还是会太频繁地把内容拆开。我知道它能很好地保持一个本来会被拆开的流式组件在一起,比如如果你说:
Story.append(KeepTogether(Paragraph(header_string, styleH))
那么这个段落就不会被拆开,除非实在没办法不拆开。
如果 KeepTogether
对你来说不管用,我建议你创建一个自定义的 Flowable
,把你的段落和表格放在里面,然后在布局的时候确保你的自定义 Flowable
子类不会被拆开。
12
这是我在查看reportlab源代码时找到的解决方案:
paragraph = Paragraph(header_string, styleH)
paragraph.keepWithNext = True
Story.append(paragraph)
Story.append(table)