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

运行fpdf2 Unicode示例代码遇AttributeError:'table__n_a_m_e'无getBestFullName属性

解决fpdf2 Unicode示例运行时的AttributeError错误

问题描述

运行fpdf2官方文档中的Unicode示例代码时,触发以下错误:

Traceback (most recent call last):
File "fpdf2.py", line 12, in
pdf.add_font('DejaVu', fname='DejaVuSansCondensed.ttf')
File "C:\Program Files\Python36\lib\site-packages\fpdf\fpdf.py", line 1916, in add_font
"name": re.sub("[ ()]", "", font["name"].getBestFullName()),
AttributeError: 'table__n_a_m_e' object has no attribute 'getBestFullName'

已在系统中安装DejaVuSansCondensed字体,使用的完整代码如下:

from fpdf import FPDF

pdf = FPDF()
pdf.add_page()

# Add a DejaVu Unicode font (uses UTF-8)
# Supports more than 200 languages. For a coverage status see:
# http://dejavu.svn.sourceforge.net/viewvc/dejavu/trunk/dejavu-fonts/langcover.txt
pdf.add_font('DejaVu', fname='DejaVuSansCondensed.ttf')
pdf.set_font('DejaVu', size=14)

text = u"""
English: Hello World
Greek: Γειά σου κόσμος
Polish: Witaj świecie
Portuguese: Olá mundo
Russian: Здравствуй, Мир
Vietnamese: Xin chào thế giới
Arabic: مرحبا العالم
Hebrew: שלום עולם
"""

for txt in text.split('\n'):
    pdf.write(8, txt)
    pdf.ln(8)

# Add a Indic Unicode font (uses UTF-8)
# Supports: Bengali, Devanagari, Gujarati, 
#           Gurmukhi (including the variants for Punjabi) 
#           Kannada, Malayalam, Oriya, Tamil, Telugu, Tibetan
pdf.add_font('gargi', fname='gargi.ttf')
pdf.set_font('gargi', size=14)
pdf.write(8, u'Hindi: नमस्ते दुनिया')
pdf.ln(20)

# Add a AR PL New Sung Unicode font (uses UTF-8)
# The Open Source Chinese Font (also supports other east Asian languages)
pdf.add_font('fireflysung', fname='fireflysung.ttf')
pdf.set_font('fireflysung', size=14)
pdf.write(8, u'Chinese: 你好世界\n')
pdf.write(8, u'Japanese: こんにちは世界\n')
pdf.ln(10)

# Add a Alee Unicode font (uses UTF-8)
# General purpose Hangul truetype fonts that contain Korean syllable 
# and Latin9 (iso8859-15) characters.
pdf.add_font('eunjin', fname='Eunjin.ttf')
pdf.set_font('eunjin', size=14)
pdf.write(8, u'Korean: 안녕하세요')
pdf.ln(20)

# Add a Fonts-TLWG (formerly ThaiFonts-Scalable) (uses UTF-8)
pdf.add_font('waree', fname='Waree.ttf')
pdf.set_font('waree', size=14)
pdf.write(8, u'Thai: สวัสดีชาวโลก')
pdf.ln(20)

# Select a standard font (uses windows-1252)
pdf.set_font('helvetica', size=14)
pdf.ln(10)
pdf.write(5, 'This is standard built-in font')

pdf.output("unicode.pdf")

解决方法

1. 切换到正确的fpdf2库

错误路径显示调用的是旧版fpdf库的代码,而非目标库fpdf2,执行以下命令修复:

  • 卸载旧版fpdf:
    pip uninstall -y fpdf
    
  • 安装最新版fpdf2:
    pip install --upgrade fpdf2
    

2. 修改代码导入语句

将代码开头的导入行改为:

from fpdf2 import FPDF

3. 确保字体路径正确

如果字体文件不在脚本的当前工作目录,需提供完整绝对路径,例如:

pdf.add_font('DejaVu', fname='C:/Windows/Fonts/DejaVuSansCondensed.ttf')

也可直接将字体文件复制到脚本所在文件夹。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 02:31:09