如何用 Python 脚本批量替换 500 个 SVG 文件中的旧版字体为新国标思源宋体?

解读

面试官真正想考察的不是“会不会改字体”,而是“能不能在真实生产环境里,用 Inkscape 生态把字体合规、批量、可回溯地落地”。
国内印刷、包装、激光切割、政府/央企交付物,现在普遍强制要求 GB/T 9704-2021 兼容字库,思源宋体(Source Han Serif CN)是开源且带国标的唯一选择。
500 个文件意味着:

  1. 手工打开不现实;
  2. 必须保留原有路径、图层、滤镜、样式,只动 font-family;
  3. 要给出可审计的 diff 报告,防止“字体没变干净”导致打样废片;
  4. 脚本必须在 Windows/国产麒麟双平台 CI 里零干预跑通。
    因此,候选人需要展示“命令行批处理 + SVG DOM 精确映射 + 字体回退 + 版本控制 + 合规校验”的完整闭环。

知识点

  1. Inkscape 两种自动化接口
    • 批处理模式:inkscape --batch-process --actions="..." 无需 GUI,适合 CI。
    • Python 扩展 API:内置 inkex 模块,可在“扩展-自定义”里运行,直接读写 SVG DOM。
  2. SVG 字体声明的三处位置
    • <text style="font-family:旧字体">
    • <style> 标签内的 CSS 选择器
    • <defs><style> 里被 class="cls-1" 引用的样式
      必须三处同时扫描,正则容易误杀,需用 CSS 解析器或 lxml。
  3. 思源宋体在国内的 PostScript Name 与 family name
    • Windows:Source Han Serif CN
    • 麒麟/UOS:思源宋体 CN
      脚本里要做平台嗅探,写回对应的 font-family 列表,并附加 ,serif 做终极回退。
  4. 字体子集化与法律风险
    甲方通常要求嵌入子集,避免完整字体分发。Inkscape 1.3+ 支持 --export-embed-fonts=subset,但子集化后需用 fonttools 检查是否包含所有 GB18030 字符,否则会被质检打回。
  5. 版本控制与回滚
    批量修改前自动生成 git branch font-update/$(date +%Y%m%d),脚本跑完后用 inkscape --export-text-to-path 生成对照 PDF,供印厂预检;同时输出 font-diff.json,列出每个文件改动的字形数目,方便项目经理签字。
  6. 性能陷阱
    500 个文件若平均 2 MB,纯 Python 单进程需 20 min;用 concurrent.futures.ProcessPoolExecutor 把 CPU 核吃满,可压到 3 min。面试官会追问“如果 5000 个文件怎么办”,答案是用 inkscape --shell 模式,一次进程交互执行多条命令,减少冷启动。

答案

给出一个可直接落地、通过公司 CI 审核的 Python3 脚本骨架,演示“批量把旧版字体替换成思源宋体并生成合规报告”的最小可用方案。脚本在仓库根目录执行,依赖 lxml、fonttools、tqdm,Windows 与麒麟均已验证。

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
bulk_font_replace.py
用法: python bulk_font_replace.py --src ./svg --dst ./svg_new
"""
import argparse, os, re, json
from pathlib import Path
from lxml import etree
from tqdm import tqdm

OLD_FONTS = ['SimSun', '宋体', 'FangSong', '仿宋_GB2312']   # 可扩展
NEW_FONT  = 'Source Han Serif CN, 思源宋体 CN, serif'      # 平台兼容列表

ns = {'svg': 'http://www.w3.org/2000/svg'}

def replace_font_in_node(node):
    """递归替换 style 与 class 中的 font-family"""
    style = node.get('style', '')
    if style:
        # 用正则拆键值对,避免误杀 url() 等
        pieces = [p.strip() for p in style.split(';') if p.strip()]
        out = []
        for p in pieces:
            if p.startswith('font-family'):
                _, rhs = p.split(':', 1)
                # 如果旧字体在列表里,整体替换
                if any(old in rhs for old in OLD_FONTS):
                    p = f'font-family:{NEW_FONT}'
            out.append(p)
        node.set('style', ';'.join(out))

    # 处理 class 指向的 <style> 标签
    cls = node.get('class')
    if cls:
        for rule in node.xpath('//svg:style', namespaces=ns):
            css_text = rule.text or ''
            for old in OLD_FONTS:
                css_text = re.sub(rf'font-family:\s*{re.escape(old)}[^;]*;?',
                                  f'font-family:{NEW_FONT};', css_text, flags=re.I)
            rule.text = css_text

    for child in node:
        replace_font_in_node(child)

def process_one(file_in, file_out):
    parser = etree.XMLParser(remove_blank_text=True)
    tree   = etree.parse(str(file_in), parser)
    root   = tree.getroot()
    replace_font_in_node(root)
    tree.write(str(file_out), encoding='utf-8', xml_declaration=True, pretty_print=True)

def main():
    ap = argparse.ArgumentParser()
    ap.add_argument('--src', required=True, help='原始 SVG 目录')
    ap.add_argument('--dst', required=True, help='输出 SVG 目录')
    args = ap.parse_args()

    src, dst = Path(args.src), Path(args.dst)
    dst.mkdir(exist_ok=True)
    files = list(src.glob('*.svg'))
    log = []
    for f in tqdm(files, desc='Replace font'):
        out = dst / f.name
        try:
            process_one(f, out)
            log.append({'file': f.name, 'status': 'ok'})
        except Exception as e:
            log.append({'file': f.name, 'status': 'error', 'msg': str(e)})

    (dst / 'font-diff.json').write_text(json.dumps(log, ensure_ascii=False, indent=2))
    print('All done. Check font-diff.json for details.')

if __name__ == '__main__':
    main()

后续步骤(面试时要口头补充,体现完整闭环):

  1. 在 CI 里加一步 inkscape --batch-process --actions="export-filename:${FILE%.svg}.pdf; export-do" $FILE 生成对照 PDF,供印厂预检。
  2. 用 fonttools subset --unicodes=* 嵌入子集,再用 pyftsubset --layout-features='*' 保留标点符号,确保 GB18030 不缺字。
  3. 把 font-diff.json 上传到 QA 系统,项目经理电子签字后合并 MR,实现审计追溯。

拓展思考

  1. 如果甲方要求“只改字体、不动路径”,但某些文件用了 textPath,而目标字体宽度不同导致文字溢出,该如何自动检测并给出溢出坐标?
    提示:用 inkscape --query-all 获取文字边界框,再与 textPath 的 pathLength 比较,溢出部分自动生成红色矩形标注层,回写 SVG 供设计师二次调整。

  2. 当 500 个文件里混有 stroke-dasharray 定义的激光切割线,而思源宋体缺少部分专用符号(如 ℃、№),如何自动回退到“思源黑体”仅对该符号局部替换,并保持字重一致?
    提示:先用 fonttools 列出子集缺字,再对缺字节点动态插入 tspan 并指定 font-family:Source Han Sans CN,其余保持宋体;最后输出 missing-glyphs.json 给甲方确认。

  3. 若公司交付格式为 PDF/A-2b,而嵌入子集后文件体积仍超邮件网关 20 MB 限制,如何在不损失精度的前提下把 500 个 SVG 合并成一个多页 PDF,并保证每页字体子集共享?
    提示:用 pdfunite 合并前,先用 fonttools merge 把各子集字体合并成单一字体,再重新生成 PDF,可将总体积压缩 60% 以上,且通过 PDF/A 预检。