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

Python使用FPDF生成带表格PDF时多行单元格动态等高问题

实现动态统一行高的FPDF表格解决方案

实现思路

要解决同一行单元格高度不对齐的问题,只需在渲染每行前加一步预计算即可:

  • 先通过 dry run 模式计算当前行每个单元格渲染所需的实际高度,取最大值作为当前行的统一高度
  • 正式渲染时所有单元格都使用该统一高度,保证行内高度对齐

修改后可运行代码

from fpdf import FPDF

data = (
    ("First name", "Last name", "Age", "City"),
    ("Jules", "Smith", "34", "San Juan"),
    ("Mary", "Ramos", "45", "Orlando"),
    ("Carlson", "Banks", "19", "Los Angeles"),
    ("Lucas", "Cimon", "31", "Saint-Mahturin-sur-Loire udfhisudhf fughdiufhg fduihgsdiufg dfghsdifugh fdiguhdsfiug fdughdifugh dfhgsdiufhg"),
)

pdf = FPDF()
pdf.add_page()
pdf.set_font("Times", size=10)
base_line_height = pdf.font_size * 2.5
col_width = pdf.epw / 4 

for row in data:
    # 第一步:预计算当前行最大高度
    max_row_height = base_line_height
    for datum in row:
        # dry_run=True表示只计算尺寸,不实际绘制内容
        cell_height = pdf.multi_cell(col_width, base_line_height, datum, border=1, ln=3, dry_run=True).height
        if cell_height > max_row_height:
            max_row_height = cell_height
    # 第二步:用统一行高正式渲染当前行所有单元格
    for datum in row:
        pdf.multi_cell(col_width, max_row_height, datum, border=1, ln=3)
    pdf.ln(max_row_height)

pdf.output('table_with_cells.pdf')

代码说明

  • 新增的预计算环节利用了multi_cell的dry_run参数,不会产生实际绘制操作,也不会改变PDF的当前绘制坐标
  • 无需提前知道单元格内容长度,完全动态适配任意长度的文本内容
  • 兼容原来的所有配置参数,只需要调整行循环的逻辑即可

内容的提问来源于stack exchange,提问作者Carmen B.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 11:24:03