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

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)

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.


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)