[Python] Tiny numbers in ReportLab's table of contents

Discussão em 'Python' iniciado por Stack, Agosto 23, 2025.

  1. Stack

    Stack Membro Participativo

    I followed an example from the ReportLab documentation on how to add a table of contents, and it works fine in most situations. However, if a section title is very close to the full page width, then the page number gets shrunk to fit. Sometimes, it's shrunk to the point you can't see it at all.

    Has anyone found a way to work around this by forcing the section title to wrap earlier, leaving enough room for the page number?

    Here's a demonstration of the problem:

    [​IMG]

    You can see that with 3, 4, and 5 i's the page number shrinks and disappears.

    Here's my modified version of the example that generated the table of contents above:

    from reportlab.lib.styles import ParagraphStyle as PS
    from reportlab.platypus import PageBreak
    from reportlab.platypus.paragraph import Paragraph
    from reportlab.platypus.doctemplate import PageTemplate, BaseDocTemplate
    from reportlab.platypus.tableofcontents import TableOfContents
    from reportlab.platypus.frames import Frame
    from reportlab.lib.units import cm


    class MyDocTemplate(BaseDocTemplate):

    def __init__(self, filename, **kw):
    self.allowSplitting = 0
    BaseDocTemplate.__init__(self, filename, **kw)
    template = PageTemplate('normal', [Frame(2.5 * cm, 2.5 * cm, 15 * cm, 25 * cm, id='F1')])
    self.addPageTemplates(template)

    def afterFlowable(self, flowable):
    "Registers TOC entries."
    if flowable.__class__.__name__ == 'Paragraph':
    text = flowable.getPlainText()
    style = flowable.style.name
    if style == 'Heading1':
    self.notify('TOCEntry', (0, text, self.page))
    if style == 'Heading2':
    self.notify('TOCEntry', (1, text, self.page))


    h1 = PS(name='Heading1',
    fontSize=14,
    leading=16)

    h2 = PS(name='Heading2',
    fontSize=12,
    leading=14,
    leftIndent=10)

    # Build story.
    story = []
    toc = TableOfContents()
    # For conciseness we use the same styles for headings and TOC entries
    toc.levelStyles = [h1, h2]
    story.append(toc)
    story.append(PageBreak())
    story.append(Paragraph('Table of Contents Test', h1))
    for i in range(10):
    story.append(Paragraph('XXXXX ' * 9 + 'i' * i, h2))

    doc = MyDocTemplate('toc_test.pdf')
    doc.multiBuild(story)


    I looked in the ReportLab source code, and found that it really is just shrinking the page number until it fits or reaches a font size of 1 pixel.

    Continue reading...

Compartilhe esta Página