在 Overleaf 中引用 Matplotlib 生成的 PDF 避免字体冲突?
解读
国内科研与工程报告普遍采用 Overleaf 在线 LaTeX 编译,而 Matplotlib 默认回退到 DejaVu Sans 与 Bitstream Vera 系列字体,这些字体在 TeX Live 2023 镜像中并未随包分发。Overleaf 的 XeLaTeX/LuaLaTeX 引擎一旦遇到子集化后 CID 不一致 的嵌入字体,会抛出 font-not-found 或 CIDSystemInfo mismatch 错误,导致 PDF 无法通过线上编译。面试官通过此题考察候选人是否熟悉 Matplotlib 字体层、PDF 子集化规则、LaTeX 字体映射、Overleaf 容器环境 四重约束下的闭环解决方案,以及能否给出 CI 友好、可复现、跨平台 的工程级脚本。
知识点
- Matplotlib 字体回退顺序:rcParams['font.family'] → font_manager.ttfFontProperty.score → fc-list 缓存
- PDF 子集化机制:pdf.use14corefonts、pdf.fonttype、PDF 对象流 /FontFile → /FontDescriptor → /Widths 的 CID 映射
- Overleaf 字体白名单:XeLaTeX 仅挂载 texlive-fonts-recommended 与 texlive-lang-chinese,缺失 Nimbus、DejaVu、Liberation 系列
- LaTeX 字体映射链:.fontspec → .map → .enc → .tfm → .pfb,任何 CID 偏移不匹配都会触发 xdvipdfmx:fatal
- CI 可复现性:Docker 镜像 python:3.11-slim + texlive-full 体积 4.8 GB,需用 multi-stage 构建 在 GitHub Actions 缓存字体索引
答案
分三步闭环解决:
- 本地预编译阶段
a) 强制 Matplotlib 使用 LaTeX 自带字体:
b) 关闭 PDF 子集化,避免 CID 重写:import matplotlib.pyplot as plt plt.rcParams.update({ "text.usetex": True, "font.family": "serif", "font.serif": ["Times"], "pgf.rcfonts": False, "pgf.preamble": r"\usepackage{times}" })plt.savefig("fig.pdf", metadata={"Creator": None, "Producer": None}, pdf.fonttype=42, pdf.use14corefonts=True) - Overleaf 集成阶段
在 repo 根目录放置 matplotlibrc 与 latexmkrc,确保 Overleaf 的 XeLaTeX 编译链优先搜索 Times-Roman 与 NimbusRomNo9L-Regu 的 pfb 文件;通过 fontspec 显式禁用伪粗体:\setmainfont{Times New Roman}[ BoldFont = TimesNewRomanPS-BoldMT, ItalicFont = TimesNewRomanPS-ItalicMT, BoldItalicFont = TimesNewRomanPS-BoldItalicMT, Renderer = HarfBuzz, RawFeature = {+liga}] - CI 校验阶段
在 GitHub Actions 使用 qpdf --check fig.pdf 验证 所有字体完全嵌入且 CIDSystemInfo 与 Overleaf 容器一致;若出现 “font has inconsistent embedded subset” 警告,则回退到 pgf 后端 生成 fig.pgf 并由 \input{fig.pgf} 动态编译,彻底规避 PDF 字体对象冲突。
拓展思考
若面试官追问 “10 张图以上如何批量保证字体一致性?”,可继续阐述:
- 编写 matplotlib.pyplot.style.library 的 overleaf.times 样式包,固化 text.usetex、pdf.fonttype、axes.labelsize 等 17 项参数,通过 importlib.resources 在 init.py 注入;
- 利用 pytest-mpl 生成 hash-based baseline,在 CI 中对比 font checksum 而非像素,防止因 Overleaf 年度升级 TeX Live 导致字形漂移;
- 对 中文场景,改用 Fandol 字体族,并在 mpl.use('pgf') 下设置 pgf.preamble=r"\usepackage{xeCJK}\setCJKmainfont{FandolSong-Regular}",通过 Overleaf 的 font-cache warm-up 脚本提前上传 .otf 到项目根,避免在线编译时 fontspec 超时拉取失败。