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

使用FPDF生成标签时出现Errno2错误:旧路径引用问题求解

FPDF生成PDF时触发FileNotFoundError,引用旧路径而非当前路径

我用Tkinter开发了一个数据库表单,通过FPDF生成标签。保存生成的标签时出现Errno2错误,错误提示的路径是我实验室电脑的旧路径,并非当前运行脚本的电脑路径。为保证脚本可移植性,我已经用os.getcwd()结合子目录处理路径,但问题仍未解决。

报错的函数代码

skid_number = config.get('DEFAULT','skid_number')

pdf = FPDF('L', 'mm', (101.6,152.4))
pdf.add_page()

pdf.add_font('free3of9', '',f'{os.getcwd()}\\free3of9.ttf',uni=True)

pdf.set_font("Arial", size=45,style='B')
pdf.cell(131,10, txt='AUD-PLT',align='C')

pdf.ln(h=16.5)
pdf.set_font("free3of9", size=55,style='')
pdf.cell(131,10, txt='*AUD-PLT*',align='C')

pdf.ln(h=16.5)
pdf.set_font("Arial", size=45,style='B')
pdf.cell(131,10, txt=skid_number,align='C')

pdf.ln(h=16.5)
pdf.set_font("free3of9", size=55,style='')
pdf.cell(131,10, txt=f'*{skid_number}*',align='C')

pdf.ln(h=16.5)
pdf.set_font("Arial", size=45,style='B')
pdf.cell(131,5, txt=date.today().strftime('%b-%d-%y'),align='C')

pdf.output(name='skid_label.pdf', dest=os.getcwd())

报错回溯信息

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Program Files\Python311\Lib\tkinter\__init__.py", line 1948, in __call__
    return self.func(*args)
           ^^^^^^^^^^^^^^^^
  File "C:\Users\onlineuser\Desktop\gui.py", line 474, in new_pallet
    self.print_skid_label()
  File "C:\Users\onlineuser\Desktop\gui.py", line 398, in print_skid_label
    pdf.output(name='skid_label.pdf', dest=os.getcwd())
  File "C:\Program Files\Python311\Lib\site-packages\fpdf\fpdf.py", line 1065, in output
    self.close()
  File "C:\Program Files\Python311\Lib\site-packages\fpdf\fpdf.py", line 246, in close
    self._enddoc()
  File "C:\Program Files\Python311\Lib\site-packages\fpdf\fpdf.py", line 1637, in _enddoc
    self._putresources()
  File "C:\Program Files\Python311\Lib\site-packages\fpdf\fpdf.py", line 1584, in _putresources
    self._putfonts()
  File "C:\Program Files\Python311\Lib\site-packages\fpdf\fpdf.py", line 1288, in _putfonts
    ttfontstream = ttf.makeSubset(font['ttffile'], subset)
                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Program Files\Python311\Lib\site-packages\fpdf\ttfonts.py", line 459, in makeSubset
    self.fh = open(file ,'rb')
              ^^^^^^^^^^^^^^^^
FileNotFoundError: [Errno 2] No such file or directory:     'C:\\Users\\DavidSonnen\\Documents\\Projects\\Silver Inventory Python\\Lib\\site-packages\\fpdf\\fonts\\free3of9.ttf'

错误触发在pdf.output行,我怀疑问题出在add_font的free3of9字体上,试过硬编码ttf文件路径但未解决,查看回溯里的其他文件也未发现异常。


解决方案

1. 用脚本自身路径定位字体文件,避免依赖os.getcwd()

os.getcwd()返回的是当前工作目录,若脚本从其他目录启动会导致路径错误。应基于脚本所在目录拼接字体路径:

import os
# 获取脚本所在绝对目录
script_dir = os.path.dirname(os.path.abspath(__file__))
# 拼接字体文件完整路径
font_path = os.path.join(script_dir, 'free3of9.ttf')
pdf.add_font('free3of9', '', font_path, uni=True)

2. 清理FPDF缓存的旧字体文件

FPDF会将字体缓存到其安装目录的fonts文件夹中,换电脑后缓存的旧路径依然存在,导致读取失败:

  • 找到当前环境下FPDF的fonts目录(示例:C:\Program Files\Python311\Lib\site-packages\fpdf\fonts)
  • 删除其中所有free3of9.*相关文件
  • 重新运行脚本,FPDF会生成适配当前路径的新缓存文件

3. 修正pdf.output的参数用法

pdf.output的dest参数接受的是文件操作模式(如'F'表示保存到文件,'S'表示返回字符串),并非保存路径。正确写法是直接在name参数中传入完整路径:

output_path = os.path.join(script_dir, 'skid_label.pdf')
pdf.output(output_path)

4. 增加字体文件存在性检查

确保字体文件确实存在于指定路径,可提前添加检查逻辑:

if not os.path.exists(font_path):
    # 这里可添加Tkinter提示框等错误处理
    print(f"错误:字体文件不存在,路径为{font_path}")
    return

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 03:31:12