You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用pyfpdf生成位于PDF首页的目录?

解决pyfpdf首页生成目录的问题

你的代码核心问题是没有正确切换到首页并写入内容,直接修改self.page=1无法让pyfpdf切换到目标页面,必须使用set_page()方法。另外,你在最后一页的header里调用目录生成逻辑,此时操作的还是最后一页,而非首页。

修正方案

  1. 先完成所有页面的生成,同步收集目录项(页码+标题)
  2. 所有页面生成完毕后,切换到首页绘制目录内容
  3. 修正类方法中错误使用全局变量的问题,统一用self引用当前实例

修改后的完整代码

from fpdf import FPDF
from datetime import date

today = date.today().strftime("%Y/%m/%d")

hardwareModel = ["hardwareModel1", "hardwareModel2", "hardwareModel3"]
snapshotNumber = ["N13100","N13101","N13102"]
firmwareVersion = ["1.8.0","1.8.1","1.8.2"]
websiteVersion = ["2.4.0","2.4.0","2.4.0"]
unifiedPackage = ["#38-20220624","#39-20220701","#40-20220829"]
stageDatabaseVersion = ["4.3.12","4.3.13","4.3.13"]
dateArray = ["2022/06/24","2022/07/01",today]

class PDF(FPDF):
    def __init__(self):
        super().__init__()
        self.currentIndex = -1
        self.tableOfContents = []  # 用实例变量存储目录项,而非全局变量
        
    def titlePage(self, redScale, greenScale, blueScale, string):
        self.set_text_color(redScale, greenScale, blueScale)
        # 标题
        self.cell(0, 10, txt=string, align="L")
        self.drawLine(128, 196, 28, 1, 10, 50, 200, 50)

    def drawLine(self, redScale, greenScale, blueScale, lineWidth, x1, y1, x2, y2):
        self.set_draw_color(redScale, greenScale, blueScale)
        self.set_line_width(lineWidth)
        self.line(x1, y1, x2, y2)
    
    def generate_table_of_contents(self):
        # 切换到首页
        self.set_page(1)
        self.set_text_color(0, 0, 0)
        self.set_font("helvetica", size=16)
        # 写入目录标题
        self.cell(0, 10, "目录", align="C")
        self.ln(15)
        self.set_font("helvetica", size=12)
        # 遍历目录项生成带链接的内容
        for page_num, title in self.tableOfContents:
            link = self.add_link()
            self.set_link(link, y=0.0, page=page_num)
            # 左对齐标题,右对齐页码
            self.cell(180, 10, title, link=link)
            self.cell(0, 10, str(page_num), align="R")
            self.ln(8)
        
    def header(self):
        if self.currentIndex > -1 and self.currentIndex <= len(snapshotNumber)-1:
            # 收集目录项:当前页码和页面标题
            self.tableOfContents.append(
                (self.page_no(), 
                 f"{hardwareModel[self.currentIndex]}_{snapshotNumber[self.currentIndex]} ({dateArray[self.currentIndex]})")
            )
            self.image('image.jpg', 0, 0, 210)
            self.set_font("helvetica", size=20)
            self.ln(30)
            self.titlePage(0, 84, 136, 
                          f"{hardwareModel[self.currentIndex]}_{snapshotNumber[self.currentIndex]} ({today})")
        # 首页(currentIndex=-1)不做处理,留空后续填充目录
        self.currentIndex += 1

pdf = PDF()
pdf.set_title("titleTest")

# 添加首页(空白,后续填充目录)
pdf.add_page()
# 添加其他内容页面
for _ in snapshotNumber:
    pdf.add_page()

# 所有页面生成完毕后,生成目录到首页
pdf.generate_table_of_contents()

pdf.output("test.pdf")

关键修改点

  • 将目录项存储改为实例变量self.tableOfContents,避免全局变量的问题
  • 使用self.set_page(1)正确切换到首页
  • 把目录生成逻辑从header中移出,放到所有页面生成完成后单独调用
  • 优化目录排版,添加目录标题,标题和页码左右对齐

内容的提问来源于stack exchange,提问作者Rayon Magique

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 01:15:54