可変フォント ファイルからすべてのグリフを個別の SVG として特定の場所にエクスポート し 画像ファイルを作成

プログラム

from fontTools.ttLib import TTFont
from fontTools.varLib.instancer import instantiateVariableFont
from fontTools.pens.svgPathPen import SVGPathPen
from fontTools.pens.boundsPen import BoundsPen
from textwrap import dedent
import os

output_path = "y:/output_svg/"
os.makedirs(output_path, exist_ok=True)

def save_all_glyph_as_svg(font, suffix=""):
    glyph_set = font.getGlyphSet()
    cmap = font.getBestCmap()

    for c, glyph_name in cmap.items():
        glyph = glyph_set[glyph_name]

        # --- 1) BoundsPen で bbox を取得 ---
        bpen = BoundsPen(glyph_set)
        glyph.draw(bpen)
        if bpen.bounds is None:
            continue
        xMin, yMin, xMax, yMax = bpen.bounds

        width = glyph.width
        glyph_height = yMax - yMin
        if glyph_height == 0 or width == 0:
            continue

        # --- 2) 高さを width に合わせるスケール ---
        scale = width / glyph_height

        # --- 3) SVG path を取得 ---
        svg_pen = SVGPathPen(glyph_set)
        glyph.draw(svg_pen)
        path_data = svg_pen.getCommands()
        if not path_data.strip():
            continue

        # --- 4) 正方形 viewBox & 上下余白なし ---
        content = dedent(f'''\
            <svg xmlns="http://www.w3.org/2000/svg"
                 viewBox="0 0 {width} {width}">
                <g transform="translate(0,{width}) scale({scale}, {-scale}) translate({-xMin}, {-yMin})">
                    <path d="{path_data}"/>
                </g>
            </svg>
        ''')

        filename = f"0x{c:04x}{suffix}.svg"
        with open(os.path.join(output_path, filename), "w", encoding="utf-8") as f:
            f.write(content)

# -------------------------
# NotoSansTC Regular(wght=400)
# -------------------------
font = TTFont(r"C:\data\Ishihara\Gothic\NotoSansTC-VariableFont_wght.ttf")
font = instantiateVariableFont(font, {"wght": 400})
save_all_glyph_as_svg(font, suffix="_TC")

# -------------------------
# NotoSansJP Regular(wght=400)
# -------------------------
font = TTFont(r"C:\data\Ishihara\Gothic\NotoSansJP-VariableFont_wght.ttf")
font = instantiateVariableFont(font, {"wght": 400})
save_all_glyph_as_svg(font, suffix="_JP")

font,Python

Posted by eightban