如何在 Python 中使用 TTF 字体

如何在 Python 中使用 TTF 字体

本指南展示了如何加载 TTF 字体、检查 TtfFont 属性、读取表格、实例化可变字体,以及使用 Aspose.Font FOSS 为 Python 转换为其他格式。TrueType 字体(.ttf)是最常见的字体格式。Aspose.Font FOSS 将它们加载为 TtfFont 实例,提供对表格、可变字体轴、字形数据和转换工具的访问。

分步指南

步骤 1:安装软件包

使用以下命令安装 Aspose.Font FOSS 包:

git clone https://github.com/aspose-font-foss/Aspose.Font-FOSS-for-Python.git
cd Aspose.Font-FOSS-for-Python
pip install -e .

步骤 2:导入必需的类

导入 FontLoader 和 TtfFont 以加载 TTF 字体并访问其类型化属性:

from aspose_font import FontLoader
from aspose_font import TtfFont

步骤 3:加载并检查 TTF 字体

使用 FontLoader.open() 加载 TTF 文件,并读取诸如名称、字体族和字形计数等基本属性:

ttf_font: TtfFont = FontLoader.open("Roboto-Regular.ttf")
print(ttf_font.font_name)
print(ttf_font.font_family)
print(ttf_font.num_glyphs)

步骤 4:读取 kern 表

访问 ttf_tables 属性,并通过名称检查 kern 表是否存在:

ttf_font: TtfFont = FontLoader.open("Roboto-Regular.ttf")
kern = ttf_font.ttf_tables.kern
print("kern present:", kern is not None)

步骤 5:实例化可变字体

加载可变字体文件,检查 is_variable,并使用轴字典调用 instantiate() 以生成静态实例:

from aspose_font import FontLoader
from aspose_font import TtfFont

ttf_font: TtfFont = FontLoader.open("Roboto-VariableFont_wdth,wght.ttf")
if ttf_font.is_variable:
    static = ttf_font.instantiate({"wght": 700.0})
    print("Instantiated:", static.font_name)

步骤 6:转换为 WOFF2

通过将 FontType.WOFF2 传递给 FontConverter.convert() 将已加载的 TTF 字体转换为 WOFF2 格式:

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)

常见问题与解决方案

AttributeError: Font has no attribute ttf_tables — 使用 ttf_font: TtfFont = FontLoader.open(...)。该 ttf_tables 属性位于 TtfFont,而不是基础 Font.

is_variable 在可变字体上为 False — 某些可变字体使用非标准 fvar 表格格式。检查 ttf_font.fvar is not None 作为替代方案。

instantiate() raises KeyError — 轴标签必须是已注册的 4 字符标签(例如). "wght", "wdth"). 检查 ttf_font.axes 用于可用标签。

常见问题

TTF 与 OTF 有何区别?

OTF 和 TTF 共享相同的二进制容器(SFNT)。OTF 字体通常使用 CFF 轮廓,而 TTF 字体使用 TrueType 二次曲线。两者都由 FontLoader.open() 加载。

我可以从 TTF 字体获取字距对吗?

是的。使用 TtfFont.get_kern_pairs() 获取 KernPair 对象的列表。

该库支持字体集合(.ttc)吗?

是的。使用 FontLoader.open(source, collection_index=N) 从 TTC 集合文件中选择特定字体。

另请参阅

 中文