我正在尝试使用 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")
# Eracting a sigle file path from the list
filepaths = filepaths[0]
# Eracting the filename
filename = Path(filepaths).stem
pdf.cell(w=0, h=10, txt=filename, align='L')
pdf.output("output.pdf")
我已经检查过 filepaths 变量是否包含正确的文件路径,并且 filename 变量是否已正确提取(这是一个 str 类型)。
该问题可能与 pdf.cell(w=0, h=10, txt=filename,align='L') 中的 txt=filename 有关
我尝试在代码的以下部分中使用 f 字符串:txt=f"{filename}",但是问题仍然存在。
我已运行以下代码来升级 fpdf: 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
尝试在 pdf.add_page() 之后添加这一行 例如字体名称 Arial 和粗体,大小为 8 pdf.set_font("Arial", "B",8)
您必须设置上面的 pdf.cell 行,如下所示:
pdf.set_font(family='时代',style='B',size=12)