使用 ReportLab 生成 PDF 索引

Generating a PDF Index with ReportLab

我正在通过 ReportLab 生成 PDF 文件,但找不到任何关于如何生成链接到文件页面的索引的文档。 ReportLab 是否支持此类功能,或者是否有其他解决方案?

经过大量时间的搜索,我想出了一个 anchor 解决方案。虽然我觉得这对我来说不是完美的解决方案,但我希望它能帮助有需要的人。

from reportlab.lib.styles import ParagraphStyle
from reportlab.pdfbase.pdfmetrics import registerFont
from reportlab.platypus import Paragraph, PageBreak, SimpleDocTemplate, Spacer

registerFont(TTFont('Calibri', 'Calibri.ttf')) # Just some font imports
registerFont(TTFont('Calibri-Bold', 'calibrib.ttf'))

pH = ParagraphStyle(name = 'Header', fontName = 'Calibri-Bold', fontSize = 13, leftIndent = 20, firstLineIndent = -20, spaceBefore = 10, leading = 16)
sH = ParagraphStyle(name = 'SubHeader', fontName = 'Calibri', fontSize = 12, leftIndent = 40, firstLineIndent = -20, spaceBefore = 5, leading = 16)

doc = SimpleDocTemplate('Reports\PDFname.pdf')
story = [Spacer(1, 2 * inch)]

story.append(Paragraph('<a href = page3.html#0>1. First Title</a>', pH)) # Linking the anchor to reference 0
story.append(Paragraph('<a href = page3.html#1>1.1. First Subtitle</a>', sH)) # Linking the anchor to reference 1
story.append(PageBreak())

story.append(Paragraph('<a name = page3.html#0></a> 1. First Title', pH)) # Creating anchor with reference 0
story.append(Paragraph('<a name = page3.html#1></a><br/> 1.1. First Subtitle', style)) # Creating anchor with reference 1

doc.build(story)