安装依赖
pip install fonttools brotli
python源码
from fontTools import ttLib
from fontTools.subset import main as subset_main
import os
import math
import random
import string
# ===================== 配置 =====================
SOURCE_FONT = "你的字体.TTF" # 改成你的字体文件名
OUTPUT_DIR = "dist_woff" #字体切片存放的文件夹
FONT_FAMILY = "fzxbs" #font-famliy
OUTPUT_FORMAT = "woff" #需要的格式woff或者woff2
# =================================================
os.makedirs(OUTPUT_DIR, exist_ok=True)
# 加载字体
tt = ttLib.TTFont(SOURCE_FONT)
cmap = tt.getBestCmap()
all_chars = sorted(cmap.keys())
tt.close()
# 分片计算
total_glyphs = len(all_chars)
glyphs_per_chunk = 150
chunk_count = math.ceil(total_glyphs / glyphs_per_chunk)
chunks = []
for i in range(chunk_count):
start = i * glyphs_per_chunk
end = start + glyphs_per_chunk
chunk = all_chars[start:end]
if chunk:
chunks.append(chunk)
css_lines = []
# 生成 6位随机字母+数字
def random_str(length=6):
return ''.join(random.choices(string.ascii_lowercase + string.digits, k=length))
# 批量切片
for idx, chunk in enumerate(chunks):
# 生成随机串 + 序号
rand = random_str()
#chunk_name = f"chunk_{rand}_{idx+1:02d}"
chunk_name = f"{idx+1:02d}"
font_out = os.path.join(OUTPUT_DIR, f"{FONT_FAMILY}_{chunk_name}.{OUTPUT_FORMAT}")
unicodes = ",".join(f"U+{c:04X}" for c in chunk)
args = [
SOURCE_FONT,
f"--unicodes={unicodes}",
f"--output-file={font_out}",
f"--flavor={OUTPUT_FORMAT}",
"--layout-features=*",
"--no-hinting",
]
subset_main(args)
# 生成CSS
min_c = min(chunk)
max_c = max(chunk)
urange = f"U+{min_c:04X}-{max_c:04X}"
css = f'''
@font-face {{
font-family: '{FONT_FAMILY}';
src: url('{os.path.basename(font_out)}') format('{OUTPUT_FORMAT}');
unicode-range: {urange};
}}
'''
css_lines.append(css.strip())
print(f"✅ 生成:{font_out}")
# 保存CSS
with open(os.path.join(OUTPUT_DIR, "fonts.css"), "w", encoding="utf-8") as f:
f.write("\n\n".join(css_lines))
print("\n🎉 全部完成!")
print(f"📁 输出目录:{OUTPUT_DIR}")
当面目录cmd执行py 你的python文件名,享用~