- 安裝必要的函式庫
首先,你需要安裝 fonttools 和 svgwrite 這兩個函式庫。你可以使用 pip 來安裝它們:
Bash
pip install fonttools svgwrite - 匯入函式庫
在你的 Python 腳本中,匯入必要的函式庫:
from fontTools.ttLib import TTFont
import svgwrite - 開啟字型檔
使用 fontTools 開啟你的字型檔:
font = TTFont("path/to/your/font.ttf")
請將 "path/to/your/font.ttf" 替換為你字型檔的實際路徑。 - 提取字元
從字型檔中提取你想要的字元。你可以使用 font.getGlyphNames() 來獲取所有字元的名稱,然後根據你的需求選擇特定的字元。
glyph_names = font.getGlyphNames()
selected_glyphs = [name for name in glyph_names if name.startswith("uni")]
# 例如,選擇所有 Unicode 字元 - 建立 SVG 檔案
使用 svgwrite 建立一個新的 SVG 檔案:
dwg = svgwrite.Drawing("output.svg", profile='full') - 將文字轉換為 SVG 元素
對於每個選定的字元,將其轉換為 SVG 路徑元素,並添加到 SVG 檔案中。
for glyph_name in selected_glyphs:
glyph = font["glyf"][glyph_name]
path = glyph.getOutline()
dwg.add(dwg.path(d=path, fill="black")) - 儲存 SVG 檔案
最後,儲存你的 SVG 檔案:
dwg.save()
完整程式碼範例
from fontTools.ttLib import TTFont
import svgwrite
font = TTFont("path/to/your/font.ttf")
glyph_names = font.getGlyphNames()
selected_glyphs = [name for name in glyph_names if name.startswith("uni")]
dwg = svgwrite.Drawing("output.svg", profile='full')
for glyph_name in selected_glyphs:
glyph = font["glyf"][glyph_name]
path = glyph.getOutline()
dwg.add(dwg.path(d=path, fill="black"))
dwg.save()
- Copilot提供較簡要的範例



