Table page breaks

19 views
Skip to first unread message

Jason Valenzuela

unread,
Jul 16, 2024, 10:38:07 AMJul 16
to reportlab-users
I have a simple application that outputs a few sections, each with a header and associated content. I've been using the keepWithNext style option for section headings to avoid page breaks between the section headers and content, which works well, except when the section content is a table. Below is a sample script to generate some test cases illustrating the problem:

from reportlab.lib.units import inch
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.platypus import Paragraph, SimpleDocTemplate, Spacer, Table

style = getSampleStyleSheet()

# Define an alternate Heading1 style to demonstrate the effect of the
# keepWithNext option.
style.add(ParagraphStyle(
    name='Heading1KeepWithNext',
    parent=style['Heading1'],
    keepWithNext=1
))

def make_pdf(filename, prev_section_height, header_style):
    doc = SimpleDocTemplate(filename)
    doc.build([
        Paragraph('Previous Section', style=style[header_style]),
        Spacer(0, prev_section_height), # Simulated content length.
        Paragraph('End of previous section.'),

        Paragraph('Table Section', style=style[header_style]),
        Table(
            [[Paragraph('A Table Row')] for i in range(50)]
        ),
    ])

# The keepWithNext style causes a problem where a large amount of space
# is left before the table section where the table could have been broken.
make_pdf('KeepWithNext.pdf', 3 * inch, 'Heading1KeepWithNext')

# Omitting the keepWithNext style option yields the desired result, with
# the table remaining attached to the header. However, it can lead to the
# problem illustrated in the next case.
make_pdf('good.pdf', 3 * inch, 'Heading1')

# Here the previous content is such that the table header gets orphaned
# at the bottom of the page because keepWithNext is not in effect; the
# desired output would be the page break before the Table Section header.
make_pdf('Orphaned Header.pdf', 8.5 * inch, 'Heading1')
Reply all
Reply to author
Forward
0 new messages