使用Python的fpdf2生成PDF时遇自定义字体未定义错误求助
解决fpdf2自定义字体报错:Undefined font: dejavusanscondensedB
问题场景
在Python应用中使用fpdf2生成PDF时,添加自定义字体后触发错误提示:
python pyfpdf Undefined font: dejavusanscondensedB - Use built-in fonts or FPDF.add_font() beforehand
对应代码示例:
from fpdf import FPDF pdf = FPDF() pdf.add_page() pdf.add_font(fname="DejaVuSansCondensed.ttf") pdf.set_font('DejaVuSansCondensed', size=14) # 业务逻辑代码 pdf.output(f"{instance.app_user.first_name} {instance.app_user.last_name} - {time}.pdf")
解决方案
- 显式指定字体家族ID:
add_font方法需明确传入family参数,避免fpdf2自动从文件名识别出错误的字体变体(如后缀B代表加粗)。修改后的调用方式:pdf.add_font(family="DejaVuSansCondensed", fname="DejaVuSansCondensed.ttf") - 确认字体文件路径:如果字体文件不在当前脚本运行目录,必须提供完整绝对路径,示例:
pdf.add_font(family="DejaVuSansCondensed", fname="/usr/local/fonts/DejaVuSansCondensed.ttf") - 匹配字体文件与样式:如果需要使用加粗字体,需单独添加对应加粗字体文件,并在
set_font时指定样式:# 添加加粗字体 pdf.add_font(family="DejaVuSansCondensed", fname="DejaVuSansCondensed-Bold.ttf", style='B') # 使用加粗样式 pdf.set_font('DejaVuSansCondensed', style='B', size=14)
内容的提问来源于stack exchange,提问作者Ahmed Wagdi
相关产品推荐
相关产品推荐

