我正在使用reportlab 生成一些pdf 文件。我有一个重复的部分。它包含一个标题和一个表格:
Story.append(Paragraph(header_string, styleH))
Story.append(table)
如何将段落与表格分组(在乳胶中,我会将它们放入相同的环境中),以便在页面制动的情况下,段落和表格保持在一起?目前,该段落有时会浮动在一页的末尾,而表格从下一页的顶部开始。
您可以尝试将它们放在一起KeepTogether
流动,如下所示:
Story.append(KeepTogether([Paragraph(header_string, styleH), table])
但是请注意,上次我检查时,实现并不完美,并且仍然会过于频繁地拆分项目。我知道它可以很好地保持一个单一的流动在一起,否则会分裂,就像你说:
Story.append(KeepTogether(Paragraph(header_string, styleH))
那么该段就不会被拆分,除非它不可能不拆分。
如果KeepTogether
对您不起作用,我建议在其中创建一个Flowable
包含您的段落和表格的自定义,然后在布局期间确保您的自定义Flowable
子类不允许自己被拆分。
这是我通过reportlab源代码找到的解决方案:
paragraph = Paragraph(header_string, styleH)
paragraph.keepWithNext = True
Story.append(paragraph)
Story.append(table)
使用 ParagraphStyle 实际上可能会更好,所以我想我会将它添加到这个超级旧的答案中。
看到@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)