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

pyFPDF自动分页异常:后续页面仅显示一行数据的问题排查及疑问

问题分析与解决方案

1. 分页后每页仅显示一行的问题原因及修复

问题根源

你手动维护了y变量控制内容垂直位置,但自动分页后y值未重置。第一页写完后y已超出页面底部,新页面中仍使用这个过大的y值设置位置,导致每次写入都会触发分页,最终每页仅显示一行。

修复代码

去掉手动维护的y变量,让pyFPDF自动跟踪当前位置,或在分页后重置初始位置:

class PDF(FPDF):
    # 保留header和footer方法不变
    def content(self, df):
        # 初始位置:页眉下方30mm处
        self.set_y(30)
        self.set_font("Arial","",12)
        for _, row in df.iterrows():
            self.cell(40,15,row['LG'],1,0,'C')
            self.cell(40,15,row['LGP'],1,0,'C')
            self.cell(40,15,row['ZEIT'],1,1,'C')
            # 可选:提前检查位置,避免内容被页脚覆盖
            if self.get_y() >= self.page_height - 25:  # 留5mm余量
                self.add_page()
                self.set_y(30)  # 新页面重置到页眉下方

2. 获取页面主体尺寸(去除页眉页脚)

可以通过pyFPDF的内置属性计算:

  • 页面总尺寸:self.page_width(横向A4为297mm)、self.page_height(横向A4为210mm)
  • 页眉高度:你在header中用ln(30),所以占30mm
  • 页脚高度:footer中set_y(-20),所以占20mm

添加一个方法来获取主体尺寸:

class PDF(FPDF):
    # 保留header、footer、content方法不变
    def get_main_area(self):
        header_h = 30
        footer_h = 20
        # 主体宽度减去左右边距,高度减去页眉页脚
        main_width = self.page_width - self.l_margin - self.r_margin
        main_height = self.page_height - header_h - footer_h
        return (main_width, main_height)

调用示例:

# 在content或其他方法中
main_w, main_h = self.get_main_area()

内容的提问来源于stack exchange,提问作者Lukas Fürst

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 00:25:21