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

如何解决FPDF库报错“AttributeError: 'FPDF' object has no attribute 'unifontsubset'”?

解决FPDF库的AttributeError: 'FPDF' object has no attribute 'unifontsubset'错误

问题场景

使用FPDF库从文本文件列表生成PDF时触发以下错误:AttributeError: 'FPDF' object has no attribute 'unifontsubset'。

使用的代码:

from fpdf import FPDF
import glob
from pathlib import Path

pdf = FPDF(orientation="P", unit="mm", format="A4")
pdf.add_page()

# List of file paths
filepaths = glob.glob("Text+Files/*.txt")
# Extracting a single file path from the list
filepaths = filepaths[0]
# Extracting the filename
filename = Path(filepaths).stem
pdf.cell(w=0, h=10, txt=filename, align='L')

pdf.output("output.pdf")

已确认:

  • filepaths变量路径正确
  • filename提取正确(类型为str)
  • 尝试过用f字符串改写pdf.cell的txt参数,无效
  • 执行pip install --upgrade fpdf升级库后问题依旧
  • 环境:Python 3.10 + Windows 10

完整报错回溯

Traceback (most recent call last):
  File "C:\Users\shibb\PythonProjects\App4.1_excercise_cats_dogs\main.py", line 14, in <module>
    pdf.cell(w=0, h=10, txt=filename, align='L')
  File "C:\Users\shibb\PythonProjects\App4.1_excercise_cats_dogs\venv\lib\site-packages\fpdf\fpdf.py", line 150, in wrapper
    return fn(self, *args, **kwargs)
  File "C:\Users\shibb\PythonProjects\App4.1_excercise_cats_dogs\venv\lib\site-packages\fpdf\fpdf.py", line 685, in cell
    txt = self.normalize_text(txt)
  File "C:\Users\shibb\PythonProjects\App4.1_excercise_cats_dogs\venv\lib\site-packages\fpdf\fpdf.py", line 1099, in normalize_text
    if self.unifontsubset and isinstance(txt, str) and not PY3K:
AttributeError: 'FPDF' object has no attribute 'unifontsubset'

Process finished with exit code 1

解决方案

这个错误是因为安装的是旧版fpdf(1.x分支),该版本对Python 3.10及以上版本兼容性较差。解决步骤如下:

  1. 卸载旧版fpdf:
pip uninstall -y fpdf
  1. 安装官方维护的现代分支fpdf2:
pip install fpdf2
  1. 修改代码中的导入语句(部分版本兼容原导入,但推荐显式使用fpdf2的导入):
from fpdf2 import FPDF  # 替换原来的from fpdf import FPDF

完成以上步骤后重新运行代码,即可解决该错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 09:30:22