FontTools 是一个用于操作字体文件的 Python 库。它支持多种字体格式,包括 TrueType (TTF) 和 OpenType (OTF),并提供功能来编辑、合并、子集化和生成字体文件
前提:安装了 Python
1、安装 fonttools 库
pip3 install fonttools
2、编写脚本
from fontTools import subset
# 定义输入字体文件和输出字体文件的路径
input_font_path = "DIN-Bold.otf"
output_font_path = "DIN-Bold-subset.otf"
# 定义需要保留的字符
text = "1479"
# 创建一个 Subsetter 对象
options = subset.Options()
subsetter = subset.Subsetter(options=options)
# 加载字体
font = subset.load_font(input_font_path, options)
# 将字符加入到要保留的字符集中
subsetter.populate(text=text)
# 执行子集化
subsetter.subset(font)
# 保存子集化后的字体
subset.save_font(font, output_font_path, options)
print(f"Subset font saved to {output_font_path}")
3、执行脚本
python subset_font.py
4、文件大小对比,由29kb减少到4kb
5、验证代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Font Display</title>
<style>
@font-face {
font-family: 'DIN-Bold';
src: url('DIN-Bold.otf') format('opentype');
}
@font-face {
font-family: 'DIN-Bold-Subset';
src: url('DIN-Bold-subset.otf') format('opentype');
}
.din-bold {
font-family: 'DIN-Bold';
font-size: 50px;
}
.din-bold-subset {
font-family: 'DIN-Bold-Subset';
font-size: 50px;
}
.container {
display: flex;
gap: 20px;
}
</style>
</head>
<body>
<div class="container">
<div class="din-bold">5</div>
<div class="din-bold-subset">5</div>
<div class="din-bold">4</div>
<div class="din-bold-subset">4</div>
<div class="din-bold">9</div>
<div class="din-bold-subset">9</div>
<div class="din-bold">7</div>
<div class="din-bold-subset">7</div>
<div class="din-bold">1</div>
<div class="din-bold-subset">1</div>
</div>
</body>
</html>
6、验证效果