如何在 Python 中使用核心字体管理
Aspose.Font FOSS for Python 提供 FontLoader 作为加载字体(从文件路径、字节数组或流)的主要入口点。返回的 Font 对象公开元数据,例如名称、系列、样式、字形计数和编码映射。
分步指南
步骤 1:安装软件包
git clone https://github.com/aspose-font-foss/Aspose.Font-FOSS-for-Python.git
cd Aspose.Font-FOSS-for-Python
pip install -e .步骤 2:导入所需类
from aspose_font import FontLoader
from aspose_font import TtfFont步骤 3:从文件路径加载字体
使用 FontLoader.open() 并传入字体文件的路径。该方法会自动检测格式,并返回相应的 Font 子类(TtfFont、CffFont 等):
font = FontLoader.open("Roboto-Regular.ttf")
print(font.font_name)
print(font.num_glyphs)步骤 4:访问字体度量
属性 Font.metrics 返回一个 FontMetrics 对象,包含字体的上升线、下降线、行间距、字符高度以及其他排版度量:
from aspose_font import FontLoader
font = FontLoader.open("Roboto-Regular.ttf")
metrics = font.metrics
print(metrics)步骤 5:转换为其他格式
将已加载的字体传递给 FontConverter.convert(),并指定所需的 FontType 目标。该方法返回一个新的字体对象,采用请求的格式,而不修改原始对象:
from aspose_font import FontLoader
from aspose_font.converter import FontConverter # internal API — may change between releases
from aspose_font import FontType
font = FontLoader.open("Roboto-Regular.ttf")
woff2 = FontConverter.convert(font, FontType.WOFF2)常见问题及解决方案
FontType 未找到 — 导入 FontType 从顶层 aspose_font 包: from aspose_font import FontType.
Font has no attribute font_name — 确保您使用的是 Font 由…返回的实例 FontLoader.open(),而不是原始字节对象。
Windows 路径上的编码错误 — 将路径作为原始字符串传递: r"C:\Fonts\MyFont.ttf".
常见问题
FontLoader 支持哪些字体格式?
FontLoader.open() 支持 TTF、OTF、CFF、Type 1、WOFF、WOFF2 和 EOT。
我可以从字节加载字体吗?
是的。FontLoader.open() 接受文件路径字符串、字节或通过 source 参数传入的流对象,并需要显式的 font_type 参数。
Font.to_bytes() 可用吗?
No. Font.to_bytes(font_type) 在基类中未实现。使用 FontConverter.convert() 更改格式,然后使用子类的 save 方法。