如何在reportlab中对对象进行分组,以便它们在新页面中保持在一起

mem*_*elf 11 python reportlab

我正在使用reportlab生成一些pdf文件.我有一个重复的部分.它包含一个标题和一个表:

            Story.append(Paragraph(header_string, styleH))
            Story.append(table) 
Run Code Online (Sandbox Code Playgroud)

如何将段落与表格分组(在乳胶中我会将它们放入相同的环境中),以便在页面制动的情况下,段落和表格保持在一起?目前,段落有时会浮动在一页的末尾,表格从下一页开始.

G G*_*III 10

您可以尝试将它们组合在一个KeepTogether可流动的中,如下所示:

Story.append(KeepTogether([Paragraph(header_string, styleH), table])
Run Code Online (Sandbox Code Playgroud)

但请注意,最后我检查过,实施并不完美,仍然会过于频繁地拆分项目.我知道它可以很好地保持一个可流动的,否则会分裂,就像你说:

Story.append(KeepTogether(Paragraph(header_string, styleH))
Run Code Online (Sandbox Code Playgroud)

那段不会分裂,除非它不可能.

如果KeepTogether不适合你,我建议Flowable用你的段落和表格创建一个自定义,然后在布局期间确保你的自定义Flowable子类不允许自己拆分.


mem*_*elf 7

这是我通过reportlab源代码找到的解决方案:

paragraph = Paragraph(header_string, styleH)
paragraph.keepWithNext = True
Story.append(paragraph)
Story.append(table)
Run Code Online (Sandbox Code Playgroud)

  • 我喜欢使用`story [-1] .keepWithNext = True`,因为它使代码更短,更清晰,并且可以轻松添加和删除,而无需更改变量名称。这对于将项目保持在循环中非常有用,因为您可以在循环中设置`story [-1] .keepWithNext = True`,然后在循环后设置`story [-1] .keepWithNext = False`以断开循环中添加的内容从接下来添加的任何内容。 (2认同)

j_w*_*dev 5

使用 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. 
Run Code Online (Sandbox Code Playgroud)
  * `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. 
Run Code Online (Sandbox Code Playgroud)