how to group objects in reportlab, so that they stay together across new pages

两盒软妹~` 提交于 2019-12-03 12:13:49

You can try to put them together in a KeepTogether flowable, like so:

Story.append(KeepTogether([Paragraph(header_string, styleH), table])

However be aware that, last I checked, the implementation was not perfect and would still split up items too frequently. I know it does a good job of keeping a single flowable together that would otherwise split, like if you were to say:

Story.append(KeepTogether(Paragraph(header_string, styleH))

then that paragraph would not get split unless it was impossible for it not to be.

If KeepTogether doesn't work for you, I'd suggest creating a custom Flowable with your paragraph and table inside it and then during layout make sure your custom Flowable subclass does not allow itself to be split up.

this is the solution that I found going through the reportlab source code:

paragraph = Paragraph(header_string, styleH)
paragraph.keepWithNext = True
Story.append(paragraph)
Story.append(table)

Using a ParagraphStyle might actually be better so i figured i'd add it to this super old answer.

Found this in their changelog after seeing @memyself's answer.

  * `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)
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!