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

pyfpdf使用multi_cell输出文本时行间距过大,该如何调整解决?

pyfpdf multi_cell行间距过大解决办法

核心方案

  • 调整multi_cell的第二个参数h即可控制行间距:很多开发者误以为该参数是整个单元格的总高度,实际它定义的是单行文本书写的行高,直接缩小该值就能降低行间距。
    示例代码:
    # 原高行间距写法,h=10会导致行间距过大
    # pdf.multi_cell(w=100, h=10, txt="第一行文本\n第二行文本\n第三行文本", border=1)
    
    # 调整h为5,行间距明显缩小
    pdf.multi_cell(w=100, h=5, txt="第一行文本\n第二行文本\n第三行文本", border=1)
    

更灵活的自定义方案

如果使用的是后续维护的fpdf2库(原pyfpdf的官方迭代版本),可以用line_height参数单独设置行高比例,无需和单元格行高绑定:

# line_height设为1.2代表行高为当前字号的1.2倍,符合常规排版习惯
pdf.multi_cell(w=100, h=6, txt="第一行文本\n第二行文本\n第三行文本", border=1, line_height=1.2)

如果使用的是旧版pyfpdf没有line_height参数,可以手动拆分文本逐行绘制,完全自定义行间距:

txt_content = "第一行文本\n第二行文本\n第三行文本"
lines = txt_content.split("\n")
custom_line_height = 4.5  # 自定义每行的间距,可按需调整
cell_width = 100
x_origin = pdf.get_x()
y_origin = pdf.get_y()

# 逐行输出文本
for index, line in enumerate(lines):
    pdf.set_xy(x_origin, y_origin + index * custom_line_height)
    pdf.cell(w=cell_width, h=custom_line_height, txt=line)

# 如需保留单元格边框,手动绘制外框
pdf.rect(x_origin, y_origin, w=cell_width, h=len(lines)*custom_line_height)

问题现象参考

multi_cell行间距过大示例

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 00:18:03