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

如何在Python的reportlab中注册.otf格式的Avenir字体?

在ReportLab中注册并使用OTF格式的Avenir字体

ReportLab提供了专门适配OTF字体的OTFont类(位于reportlab.pdfbase.ttfonts模块下),可以直接替代仅支持TTF的TTFont类来注册你的Avenir字体,以下是具体实现方法:

1. 导入核心模块

先导入处理字体和PDF生成的必要模块:

from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import OTFont
from reportlab.pdfgen import canvas

2. 注册OTF字体

用OTFont初始化字体对象,再通过pdfmetrics.registerFont完成注册:

# 替换为你的Avenir OTF字体实际路径
avenir_font_path = "/path/to/your/Avenir.otf"
# 第一个参数是自定义字体名,后续使用时需对应这个名称
pdfmetrics.registerFont(OTFont("Avenir", avenir_font_path))

如果你的Avenir字体包含不同字重(如Bold、Italic),可以分别注册不同版本:

pdfmetrics.registerFont(OTFont("Avenir-Bold", "/path/to/your/Avenir-Bold.otf"))
pdfmetrics.registerFont(OTFont("Avenir-Italic", "/path/to/your/Avenir-Italic.otf"))

3. 使用已注册的字体

在PDF生成代码中,通过setFont指定注册好的字体名称即可使用:

# 创建PDF画布
c = canvas.Canvas("avenir_otf_demo.pdf")

# 使用常规Avenir字体,字号12
c.setFont("Avenir", 12)
c.drawString(100, 750, "这是Avenir常规体的测试文本")

# 使用粗体Avenir字体,字号14
c.setFont("Avenir-Bold", 14)
c.drawString(100, 720, "这是Avenir粗体的测试文本")

# 保存PDF
c.save()

额外提示

  • 若使用的是较新版本的ReportLab,TTFont类已兼容OTF格式,你也可以尝试直接保留原代码结构,替换字体文件为OTF后测试,但OTFont是更针对性的方案,兼容性更稳定。
  • 确保字体文件路径正确且文件未损坏,否则会出现加载失败的报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 23:29:58