问题
I'm generating some pdf files using reportlab. I have a certain section that is repeated. It contains of a header and a table:
Story.append(Paragraph(header_string, styleH))
Story.append(table)
How can I group the paragraph with the table (in latex I would put them into the same environment) so that in case of a page brake, the paragraph and table stay together? Currently the paragraph sometimes floats at the end of one page and the table starts on top of the next page.
回答1:
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.
回答2:
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)
回答3:
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)
来源:https://stackoverflow.com/questions/4797536/how-to-group-objects-in-reportlab-so-that-they-stay-together-across-new-pages