如何将字体文件拆分为多个部分?

How to split a font file to multiple parts?

如何自动将一个字体文件分割成多个部分?

为什么我需要这个?因为高达 Chrome 99,它将字体的最大未压缩文件大小限制为 30 MB。看 https://chromium.googlesource.com/external/ots/+/v6.1.1/src/ots.cc

此外,中文字体通常每个文件超过 30 MB。 例如 CNS11643 字体: https://data.gov.tw/dataset/5961

因此,我需要一个自动拆分字体文件的工具。

FontForge应用支持Python脚本,可用于实现字体自动拆分

这是一个示例脚本 2

import glob
import os
import fontforge

# Up to Chrome 99, the max uncompressed size (e.g. ttf) of a font file is 30 MB.
# Please tune this value to split a font file to multiple files with size <= 30 MB.
maxGlyphsPerFile = 15000
# The glob expression of all font files.
fontFilesPath = "../fonts/*.ttf"

def splitFontFile(originalFile):
    filename = os.path.basename(file)
    filename = filename.split('.')[0]
    font = fontforge.open(originalFile)
    font.selection.all()
    glyphs = font.selection.byGlyphs
    totalGlyphs = len(list(glyphs))
    totalFiles = int(totalGlyphs / maxGlyphsPerFile + 0.5)
    print(f'{file} totalFiles: {totalFiles}')

    for f in range(totalFiles):
        g = 0
        gMin = f * maxGlyphsPerFile
        gMax = (f + 1) * maxGlyphsPerFile
        for glyph in glyphs:
            # Clear glyph out of range.
            if not(gMin <= g and g < gMax):
                glyph.clear()
            g = g + 1
        # Use this to check uncompressed font file sizes.
        #font.generate(f'{filename}-{f+1}.ttf')
        # Use this for compressed outputs.
        font.generate(f'{filename}-{f+1}.woff2')
        font.close()
        font = fontforge.open(originalFile)
        font.selection.all()
        glyphs = font.selection.byGlyphs
    font.close()
    
for file in glob.glob(fontFilesPath):
    splitFontFile(file)
    print('Done!')