PDF.js 源码解读: fonts
2026年10月27日 · StreamPDF Team

前言
前面几篇分别讲完了对象模型、XRef、Catalog 等内容层的基础设施。到了内容流求值,任何一次 Tj、TJ、'、" 操作都离不开一个东西:字体。内容流里只写了字符码,真正决定「这个码画成什么形状、占多宽、在文本层里对应哪个 Unicode」的,是字体字典与它背后的字体程序。
src/core/fonts.js(3801 行)就是 Worker 侧字体处理的终点。它的上游是 encodings.js 提供的编码表、cmap.js 解析出的 CMap、glyphlist.js 的字形名到 Unicode 映射、standard_fonts.js 的标准字体替换表,以及 metrics.js 的基础度量;它的下游是 font_renderer.js 的字形轮廓编译、canvas.js 里的文本绘制,以及主线程 font_loader.js 中的 FontFaceObject。
一句话概括:它把「PDF 字体字典 + 可选的字体程序字节」翻译成一个统一的 Font 对象,向求值器提供字形、宽度、Unicode 与可嵌入的 OpenType 数据。
版本说明:本篇严格按当前仓库这一版
fonts.js讲解。这一版只有Font与ErrorFont两个类,没有TrueTypeFont、Type1Font、Type3Font、CFFFont这些子类:Type1Font来自type1_font.js,CFFFont来自cff_font.js,TrueType 修复逻辑收在Font.checkAndRepair里,Type3 则在构造函数里直接返回。FontFlags、ToUnicodeMap、IdentityToUnicodeMap都是 import 进来的,不在本文件定义;取字形的入口叫_charToGlyph,不是charToGlyph;空格宽度是私有 getter_spaceWidth,不是getSpaceWidth;基础度量走metrics.js的getFontBasicMetrics,本文件没有getBaseFontMetrics(它在evaluator.js的求值器上);也没有getType3Glyph与FontRenderType常量。读源码时不要套用记忆里的其它版本 API。
模块总览
fonts.js 可以切成九块。前七块围绕「把字体程序变成可渲染数据」,后两块负责度量和兜底:
| 区块 | 关键类或方法 | 职责 |
|---|---|---|
| 常量与工具 | PRIVATE_USE_AREAS、PDF_GLYPH_SPACE_UNITS、EXPORT_DATA_PROPERTIES、int16、signedInt16 | 私有区范围、字形空间换算、导出字段表、二进制读写小工具 |
| 格式探测 | isTrueTypeFile、isTrueTypeCollectionFile、isOpenTypeFile、isType1File、isCFFFile、getFontFileType | 不看字典声明,直接读文件头判断真实类型 |
| 映射构建 | adjustMapping、getRanges、createCmapTable、buildToFontChar、getSymbolGlyphIdEncoding | 把字符码搬到私有区,重建 cmap、OS/2、post、name 表 |
| 字形对象 | Glyph | 一次字符码翻译的完整结果,供求值器与文本层共用 |
| 字体主体 | Font 构造函数 | 读取属性、按类型分派、失败时回退 |
| TrueType 修复 | checkAndRepair | 校验并重建表、清理字形、修正度量 |
| Type1/CFF 包装 | convert | 把 CFF 数据包进 OTF 外壳,生成必要表 |
| 字形查询 | _charToGlyph、charsToGlyphs、_spaceWidth、encodeString、glyphCacheValues | 查询、缓存、反向编码 |
| 导出与兜底 | exportData、fallbackToSystemFont、ErrorFont | 把结果压缩成二进制、缺字体时用系统字体 |
它在整条链路里的位置可以画成这样:
// 字体字典 /FontFile2 /FontFile3 + 内容流中的字符码
// → PartialEvaluator.extractDataStructures / extractWidths (属性准备)
// → new Font(name, file, properties, options) (本篇)
// → getFontFileType → checkAndRepair / convert
// → toUnicode / toFontChar / widths / fontMatrix
// → Font._charToGlyph / charsToGlyphs (字符码 → Glyph)
// → Font.renderer(FontRendererFactory) (字形轮廓)
// → exportData → TranslatedFont.send → FontFaceObject (主线程装载)
// → canvas.js 的文本绘制与 text_layer 的文本选择Font 不解析内容流,也不负责把字形画到画布上。它的职责边界很清晰:给定字体字典与字体程序,产出一个「字符码进、字形与宽度出」的稳定查询接口,并准备好可被浏览器装载的字体数据。下面的章节按源码顺序展开,但会把相关的辅助函数归到同一主题,避免逐行翻译。
字体类型分派与构造流程
构造函数的输入与输出
Font 的构造函数签名很短,但参数来自求值器精心准备的结果:
constructor(name, file, properties, evaluatorOptions) {
this.name = name;
this.psName = null;
this.mimetype = null;
this.disableFontFace = evaluatorOptions.disableFontFace;
this.fontExtraProperties = evaluatorOptions.fontExtraProperties;
this.loadedName = properties.loadedName;
this.isType3Font = properties.isType3Font;
this.missingFile = false;
this.cssFontInfo = properties.cssFontInfo;name 是 PDF 里的基础字体名,可能带 ABCDEF+ 这样的子集前缀;file 是 /FontFile、/FontFile2、/FontFile3 取出的流,可能为空;properties 是 PartialEvaluator.extractDataStructures 与 extractWidths 组装出来的属性包;evaluatorOptions 只关心两个开关:是否禁用字体嵌入、是否导出额外属性。
loadedName 不是 PDF 里的名字,而是求值器生成的全局唯一名,形如 docId_fontId,后面会作为 CSS font-family 与 commonobj 消息的键。missingFile 一开始是 false,一旦走系统字体回退就被改成 true,上层据此判断「这份字体是不是拼出来的」。
构造函数的输出不是一个普通数据对象,而是一个方法集合:_charToGlyph、charsToGlyphs、getCharPositions、encodeString、exportData,再加一个惰性构建的 renderer getter。所有字段都是给这些方法用的中间状态。
从 Flags 推导 serif、monospace 与 fallbackName
字体描述符里的 /Flags 经常不可信,因此源码做了一次「先信 Flags,再信名字」的推导:
let isSerifFont = !!(properties.flags & FontFlags.Serif);
// Fallback to checking the font name, in order to improve text-selection,
// since the /Flags-entry is often wrong (fixes issue13845.pdf).
if (!isSerifFont && !properties.isSimulatedFlags) {
const stdFontMap = getStdFontMap(),
nonStdFontMap = getNonStdFontMap(),
serifFonts = getSerifFonts();
for (const namePart of name.split('+')) {
let fontName = normalizeFontName(namePart);
fontName = stdFontMap[fontName] || nonStdFontMap[fontName] || fontName;
fontName = fontName.split('-', 1)[0];
if (serifFonts[fontName]) {
isSerifFont = true;
break;
}
}
}
this.isSerifFont = isSerifFont;
this.isSymbolicFont = !!(properties.flags & FontFlags.Symbolic);
this.isMonospace = !!(properties.flags & FontFlags.FixedPitch);FontFlags 是位掩码:Serif 为 2、Symbolic 为 4、FixedPitch 为 1。位运算只能回答「有没有这个标志」,不能回答「这个标志是不是真的」。因此当 Serif 位没置上、且这批标志不是模拟出来的时候,源码把名字拆开逐个归一化:去掉子集前缀、用标准字体映射表替换别名、再剥掉字重后缀,最后在 getSerifFonts 里查一次。这样 ArialNarrow、TimesNewRomanPS-BoldMT 这类名字即使 Flags 写错也能落到正确的 serif 分组。
fallbackName 是给 CSS 用的最后一张牌,优先级是「无效字体名 → monospace → serif → sans-serif」:
const matches = name.match(/^InvalidPDFjsFont_(.*)_\d+$/);
this.isInvalidPDFjsFont = !!matches;
if (this.isInvalidPDFjsFont) {
this.fallbackName = matches[1];
} else if (this.isMonospace) {
this.fallbackName = 'monospace';
} else if (this.isSerifFont) {
this.fallbackName = 'serif';
} else {
this.fallbackName = 'sans-serif';
}
if (this.systemFontInfo?.guessFallback) {
// Once the fallback name is guessed, we don't want to guess it again.
this.systemFontInfo.guessFallback = false;
this.systemFontInfo.css += `,${this.fallbackName}`;
}InvalidPDFjsFont_ 前缀是求值器在字体名彻底无效时造的占位名。这类名字的正则捕获部分本身就是原始字体名的一部分,因此直接拿来当 fallback。systemFontInfo.css 是系统字体替换时生成的 CSS 字体族字符串,guessFallback 保证「补一次 fallback」只发生一次,避免同名字体被多个页面反复追加。
设计要点:
Font对/Flags采取的是「读取但不迷信」策略。位掩码是廉价的元数据,先用来做默认判断;一旦缺失或与名字矛盾,就用字体名与映射表交叉验证。这个设计让字体分组在损坏 PDF 上仍然稳定,因为字体名比 Flags 更难被随意篡改——它同时决定了系统字体替换与文本层显示。
度量字段的统一换算
构造函数的中间部分把 PDF 的「千分之一字号单位」统一换成本文后面一直使用的「一个字身」:
this.differences = properties.differences;
this.widths = properties.widths;
this.defaultWidth = properties.defaultWidth;
this.composite = properties.composite;
this.cMap = properties.cMap;
this.capHeight = properties.capHeight / PDF_GLYPH_SPACE_UNITS;
this.ascent = properties.ascent / PDF_GLYPH_SPACE_UNITS;
this.descent = properties.descent / PDF_GLYPH_SPACE_UNITS;
this.lineHeight = this.ascent - this.descent;
this.fontMatrix = properties.fontMatrix;
this.bbox = properties.bbox;
this.defaultEncoding = properties.defaultEncoding;
this.toUnicode = properties.toUnicode;
this.toFontChar = [];PDF_GLYPH_SPACE_UNITS 是 1000。PDF 的 /Ascent、/Descent、/CapHeight 都以「千分之一文本空间单位」书写,除以 1000 之后变成「相对字号的倍数」,这样上层乘以字号即可得到设备空间高度。lineHeight 是最朴素的 ascent - descent;如果后面解析到真实字体程序,会再用 hhea 表覆盖。
fontMatrix 原样保留,因为 Type3 字体的字形空间不是千分之一,而由 /FontMatrix 自己定义。bbox 同样保留原值,Type3 的 d1 与后面 createOS2Table 都依赖它。
这里有一个容易忽略的细节:toFontChar 初始化为空数组,而不是 null。它是一个按字符码索引的稀疏数组,索引是 PDF 内容流里的字符码,值是要交给浏览器字体的 font char code。Type3 分支会立刻填满它;其它分支由修复或转换过程填。
Type3 的提前返回
Type3 字体没有字体程序,字形是内容流:
if (properties.type === 'Type3') {
for (let charCode = 0; charCode < 256; charCode++) {
this.toFontChar[charCode] = this.differences[charCode] || properties.defaultEncoding[charCode];
}
return;
}这十几行是整个构造函数里最早的分叉。Type3 的「字体程序」是 /CharProcs 里的一段段内容流,由求值器后续用 TranslatedFont.loadType3Data 编译成 operatorList,因此 Font 在这里只需要建立字符码到字形名的映射就够。
注意映射的值是字形名,不是 glyph id:
if (this.isType3Font) {
// Font char code in this case is actually a glyph name.
operatorListId = fontCharCode;
}这段在 _charToGlyph 里。对 Type3 来说,fontCharCode 来自 toFontChar,值可能是像 "square" 这样的名字;operatorListId 因此也是这个名字,画布层用它在 charProcOperatorList 里查对应的 operatorList。普通字体的 operatorListId 是 undefined,画布层走的是浏览器字体或 renderer.getPath。
有无字体程序的两条路
构造函数的后半段只有两条主路:没有文件,回退;有文件,按真实类型处理。
if (!file || file.isEmpty) {
if (file) {
// Some bad PDF generators will include empty font files,
// attempting to recover by assuming that no file exists.
warn('Font file is empty in "' + name + '" (' + this.loadedName + ')');
}
this.fallbackToSystemFont(properties);
return;
}
// Parse the font file to determine the correct type/subtype, rather than
// relying on the (often incorrect) data in the font dictionary; (see e.g.
// issue6782.pdf, issue7598.pdf, and issue9949.pdf).
[type, subtype] = getFontFileType(file, properties);file.isEmpty 是「流长度为 0」的快捷判断。空字体文件不报错,只警告,然后当作没嵌入处理——这一步很关键,因为大量生成器会写一个长度为 0 的 /FontFile2,如果直接抛错,整页都会变成错误字体。
getFontFileType 不看 /Subtype,而是读文件头:
function getFontFileType(file, { type, subtype, composite }) {
let fileType, fileSubtype;
if (isTrueTypeFile(file) || isTrueTypeCollectionFile(file)) {
fileType = composite ? 'CIDFontType2' : 'TrueType';
} else if (isOpenTypeFile(file)) {
fileType = composite ? 'CIDFontType2' : 'OpenType';
} else if (isType1File(file)) {
if (composite) {
fileType = 'CIDFontType0';
} else {
fileType = type === 'MMType1' ? 'MMType1' : 'Type1';
}
} else if (isCFFFile(file)) {
if (composite) {
fileType = 'CIDFontType0';
fileSubtype = 'CIDFontType0C';
} else {
fileType = type === 'MMType1' ? 'MMType1' : 'Type1';
fileSubtype = 'Type1C';
}
} else {
warn('getFontFileType: Unable to detect correct font file Type/Subtype.');
fileType = type;
fileSubtype = subtype;
}
return [fileType, fileSubtype];
}判断顺序是 TrueType、TrueType Collection、OpenType、Type1、CFF。CFF 放在最后,是因为 CFF 文件头不是固定魔数,而是版本号加头长度,与其它格式相比更容易误判。composite 决定「简单字体」还是「CID 字体」:同样一段 CFF 数据,在简单字体里叫 Type1C,在 CID 字体里叫 CIDFontType0C。
isTrueTypeFile 检查前四字节是否为 \x00\x01\x00\x00 或 "true",isTrueTypeCollectionFile 检查 "ttcf",isOpenTypeFile 检查 "OTTO",isType1File 检查 %! 或 PFB 的 \x80\x01,isCFFFile 检查首字节版本范围与第四字节(offset size)是否在 1 到 4 之间。这些函数都只 peekBytes,不会推进流位置。
用真实文件头覆盖字典声明的收益很直接:字典写 Type1、文件其实是 CFF 的情况非常常见;反过来写 CIDFontType2、文件其实是 Type1 的也有。如果按声明分派,Type1Font 会在 CFF 数据上直接失败,最后只能回退系统字体,字形精度大幅下降。
三种处理路径
确定真实类型之后,构造函数用一次 switch 分成三条路:
let data;
try {
switch (type) {
case 'MMType1':
info('MMType1 font (' + name + '), falling back to Type1.');
/* falls through */
case 'Type1':
case 'CIDFontType0':
this.mimetype = 'font/opentype';
const cff =
subtype === 'Type1C' || subtype === 'CIDFontType0C'
? new CFFFont(file, properties)
: new Type1Font(name, file, properties);
adjustWidths(properties);
// Wrap the CFF data inside an OTF font file
data = this.convert(name, cff, properties);
break;
case 'OpenType':
case 'TrueType':
case 'CIDFontType2':
this.mimetype = 'font/opentype';
// Repair the TrueType file. It is can be damaged in the point of
// view of the sanitizer
data = this.checkAndRepair(name, file, properties);
adjustWidths(properties);
if (this.isOpenType) {
type = 'OpenType';
}
break;
default:
throw new FormatError(`Font ${type} is not supported`);
}
} catch (e) {
warn(e);
this.fallbackToSystemFont(properties);
return;
}三条路的共同点是「最终都要产出 data,即一段可交给浏览器的 OpenType 字节」。差别在于数据来源与加工方式:
| 真实类型 | 解析器 | 产出方式 | 最终 mimetype |
|---|---|---|---|
TrueType / OpenType / CIDFontType2 | Font.checkAndRepair | 就地修复表并重新组装 OTF | font/opentype |
Type1 / CIDFontType0(Type1 程序) | Type1Font | Font.convert 包上 OTF 外壳 | font/opentype |
Type1C / CIDFontType0C | CFFFont | Font.convert 包上 OTF 外壳 | font/opentype |
MMType1 | 降级为 Type1 | 同上 | font/opentype |
Type3 | 无字体程序 | 构造函数提前返回,字符过程后续编译 | 不设置 |
MMType1 是 Multiple Master Type1,PDF.js 不实现可变轴,直接按普通 Type1 读。adjustWidths 在两条主路里都被调用,它负责把 /Widths 从字体矩阵空间换算回千分之一空间:
function adjustWidths(properties) {
if (!properties.fontMatrix) {
return;
}
if (properties.fontMatrix[0] === FONT_IDENTITY_MATRIX[0]) {
return;
}
// adjusting width to fontMatrix scale
const scale = 0.001 / properties.fontMatrix[0];
const glyphsWidths = properties.widths;
for (const glyph in glyphsWidths) {
glyphsWidths[glyph] *= scale;
}
properties.defaultWidth *= scale;
}默认字体矩阵的 [0] 是 0.001,因此正常字体直接跳过。非标准矩阵(Type3 常见,某些 Type1 也会写)才需要缩放:宽度定义在字形空间,而后续 _charToGlyph 期望的是「相对字身」的千分之一单位。
异常、回退与属性回写
整个 switch 包在一个 try/catch 里。任何解析异常都只 warn,然后走系统字体回退,不向上抛:
amendFallbackToUnicode(properties);
this.data = data;
// Transfer some properties again that could change during font conversion
this.type = type;
this.subtype = subtype;
this.fontMatrix = properties.fontMatrix;
this.widths = properties.widths;
this.defaultWidth = properties.defaultWidth;
this.toUnicode = properties.toUnicode;
this.seacMap = properties.seacMap;这段在 try 之后、构造函数末尾。它把 properties 里的几个字段再读一遍,原因是修复或转换过程会原地修改 properties:adjustWidths 改宽度、adjustMapping 写入新的 toFontChar、convert 写 seacMap、checkAndRepair 可能改 fontMatrix。如果不回写,Font 上的字段仍是构造开始时的旧值。
amendFallbackToUnicode 必须在所有 toUnicode 调整之后调用。它的注释写得很明确:只能在字体解析的最后调用,否则会与 adjustType1ToUnicode 之类的补丁互相覆盖。函数本身只把 fallbackToUnicode 里还没被 toUnicode 覆盖的项合并进去:
function amendFallbackToUnicode(properties) {
if (!properties.fallbackToUnicode) {
return;
}
if (properties.toUnicode instanceof IdentityToUnicodeMap) {
return;
}
const toUnicode = [];
for (const charCode in properties.fallbackToUnicode) {
if (properties.toUnicode.has(charCode)) {
continue; // The font dictionary has a `ToUnicode` entry.
}
toUnicode[charCode] = properties.fallbackToUnicode[charCode];
}
if (toUnicode.length > 0) {
properties.toUnicode.amend(toUnicode);
}
}fallbackToUnicode 是求值器从字体程序内嵌编码推导出来的兜底映射,优先级低于字典里的 /ToUnicode,因此只在「字典没给这个码」时补位。IdentityToUnicodeMap 会直接拒绝,因为它的 amend 本身就是 unreachable。
设计要点:构造函数把「失败」处理成一条正常分支,而不是异常出口。字体坏掉时,最差的结果是字形不精确、文本层可能错位,但页面仍然能画、能选、能复制。这个取舍决定了后面所有子流程的风格:每个校验失败点都优先尝试修复,修不好就降级,只有在「连降级都没有意义」时才抛错。
字形对象与两级缓存
Glyph 的九个字段
求值器每遇到一次文本操作,最终都会拿到一组 Glyph。它是整条字体链路的「结果值」:
class Glyph {
constructor(
originalCharCode,
fontChar,
unicode,
accent,
width,
vmetric,
operatorListId,
isSpace,
isInFont,
) {
this.originalCharCode = originalCharCode;
this.fontChar = fontChar;
this.unicode = unicode;
this.accent = accent;
this.width = width;
this.vmetric = vmetric;
this.operatorListId = operatorListId;
this.isSpace = isSpace;
this.isInFont = isInFont;
}
/**
* This property, which is only used by `PartialEvaluator.getTextContent`,
* is purposely made non-serializable.
* @type {Object}
*/
get category() {
return shadow(
this,
'category',
getCharUnicodeCategory(this.unicode),
/* nonSerializable = */ true,
);
}
}九个字段对应九种消费方式:
| 字段 | 含义 | 主要消费方 |
|---|---|---|
originalCharCode | 内容流里的原始字符码 | 调试、文本层定位 |
fontChar | 实际用于绘制的字符串(多数是单个码点) | canvas.js 的 fillText |
unicode | 文本层显示的 Unicode 字符 | text_layer、复制粘贴、查找 |
accent | seac 复合字形的重音部分与偏移 | canvas.js 的路径渲染 |
width | 字符前进宽度(相对字身) | 文本定位、文本层宽度 |
vmetric | 竖排字体的垂直度量 | 竖排文本定位 |
operatorListId | Type3 字形在 charProcOperatorList 里的键 | 画布层查字形过程 |
isSpace | 这个字符在内容流里是否按空格处理 | 文本层空格合并 |
isInFont | 字符码是否真的在字体映射里 | 文本选择与缺失字形判断 |
category 是一个惰性 getter,用 shadow 把结果固化成不可序列化的数据属性。它只服务 getTextContent,因为 Glyph 本身会通过 commonobj 消息跨线程传输,而 Unicode 分类对象不是结构化克隆友好类型。
_charToGlyph 的完整流程
真正的翻译入口是 _charToGlyph。它的第一件事不是查表,而是查缓存:
_charToGlyph(charcode, isSpace = false) {
let glyph = this.#glyphCache.get(charcode);
// All `Glyph`-properties, except `isSpace` in multi-byte strings,
// depend indirectly on the `charcode`.
if (glyph?.isSpace === isSpace) {
return glyph;
}
let fontCharCode, width, operatorListId;缓存键只有 charcode,但 isSpace 也影响结果,所以命中之后还要比一次 isSpace。注释解释了原因:在多字节字符串里,同一个字符码可能出现在「按空格处理」与「不按空格处理」两种上下文,Glyph 的其它字段都由字符码唯一决定,只有 isSpace 会随上下文变化。
接下来是宽度码的解析:
let widthCode = charcode;
if (this.cMap?.contains(charcode)) {
widthCode = this.cMap.lookup(charcode);
if (typeof widthCode === 'string') {
widthCode = convertCidString(charcode, widthCode);
}
}
width = this.widths[widthCode];
if (typeof width !== 'number') {
width = this.defaultWidth;
}
const vmetric = this.vmetrics?.[widthCode] || this.defaultVMetrics;复合字体的宽度表不是按字符码索引,而是按 CID 索引。cMap.lookup 把字符码查成 CID;某些 CMap 的映射结果是多字节字符串,convertCidString 负责把它折成一个 16 位整数。宽度表里查不到时用 defaultWidth,而不是 0,因为 0 会让整行文本重叠在一起。
convertCidString 只接受长度为 1 或 2 的字符串:
function convertCidString(charCode, cid, shouldThrow = false) {
switch (cid.length) {
case 1:
return cid.charCodeAt(0);
case 2:
return (cid.charCodeAt(0) << 8) | cid.charCodeAt(1);
}
const msg = `Unsupported CID string (charCode ${charCode}): "${cid}".`;
if (shouldThrow) {
throw new FormatError(msg);
}
warn(msg);
return cid;
}长度为 2 时按大端序拼成 16 位整数;长度超过 2 时没有合法解释,shouldThrow 控制是抛错还是返回原字符串。checkAndRepair 里的 CID 映射用 shouldThrow = true,因为 CID 超过 16 位一定是字体数据坏了;_charToGlyph 用默认值 false,宁可返回原字符串也不让整页文本失败。
然后是 Unicode 与 toFontChar:
let unicode = this.toUnicode.get(charcode) || charcode;
if (typeof unicode === 'number') {
unicode = String.fromCharCode(unicode);
}
let isInFont = this.toFontChar[charcode] !== undefined;
// First try the toFontChar map, if it's not there then try falling
// back to the char code.
fontCharCode = this.toFontChar[charcode] || charcode;toUnicode.get 可能返回字符串,也可能返回数字(IdentityToUnicodeMap 返回 String.fromCharCode,而 ToUnicodeMap 直接返回数组元素,可能是数字也可能是字符串)。统一转成字符串之后,文本层就不用再判断类型。
isInFont 只看 toFontChar 里有没有这个索引。它是「这个字符码有没有对应的字形」的近似判断:toFontChar 由 adjustMapping 与 buildToFontChar 填充,未填充的索引代表「字体里没有这个字形」。文本层用它区分「真的有这个字」与「只是编码里有这个码」。
fontCharCode 的取值顺序是 toFontChar 优先,字符码兜底。前者是「映射到浏览器字体里的码位」,后者是「假定字符码本身就是码位」。对标准字体与简单字体,这两者经常相同;对复合字体与私有区搬移过的字体,它们完全不同。
缺失字体上的 .notdef 处理
当字体没有嵌入、走系统字体回退时,.notdef 不能真的画出来:
if (this.missingFile) {
const glyphName = this.differences[charcode] || this.defaultEncoding[charcode];
if ((glyphName === '.notdef' || glyphName === '') && this.type === 'Type1') {
// .notdef glyphs should be invisible in non-embedded Type1 fonts, so
// replace them with spaces.
fontCharCode = 0x20;
if (glyphName === '') {
// Ensure that other relevant glyph properties are also updated
// (fixes issue18059.pdf).
width ||= this._spaceWidth;
unicode = String.fromCharCode(fontCharCode);
}
}
fontCharCode = mapSpecialUnicodeValues(fontCharCode);
}这里只处理 Type1。原因是标准字体替换后的 Type1 如果缺少某个字形,fontChar 会落到 .notdef,而 .notdef 在系统字体里通常显示成一个空心方块或一个奇怪的符号。把它换成空格,视觉上至少不会破坏版面。宽度也要跟着换成 _spaceWidth,否则会出现「看不见但有宽度」的空洞。
mapSpecialUnicodeValues 负责把 PDF 字体里常见的一批特殊码位映射回正确的 Unicode。例如某些符号字体把 0xF0 段当作私有码位使用,映射之后浏览器字体才能找到正确字形。
seac 复合字形
Type1 有一种「两个字形拼一个字符」的机制,叫 seac(Standard Encoding Accented Character):
let accent = null;
if (this.seacMap?.[charcode]) {
isInFont = true;
const seac = this.seacMap[charcode];
fontCharCode = seac.baseFontCharCode;
accent = {
fontChar: String.fromCodePoint(seac.accentFontCharCode),
offset: seac.accentOffset,
};
}seacMap 是 convert 阶段构建的:每个键是原始字符码,值里存「基字形的 font char code」「重音字形的 font char code」「重音偏移」。_charToGlyph 把 fontCharCode 换成基字形,把重音信息单独放进 accent,因为重音不是顺序绘制的——它要在基字形绘制完之后,按偏移叠上去。
isInFont 在这里被强制设为 true:即使 toFontChar 里没有这个索引,seac 也说明字体确实能画出这个字符。
fontChar 的生成
最后一步是把数值码位变成一个可绘制的字符串:
let fontChar = "";
if (typeof fontCharCode === "number") {
if (fontCharCode <= 0x10ffff) {
fontChar = String.fromCodePoint(fontCharCode);
} else {
warn(`charToGlyph - invalid fontCharCode: ${fontCharCode}`);
}
}
if (this.missingFile && this.vertical && fontChar.length === 1) {
const vertical = getVerticalPresentationForm()[fontChar.charCodeAt(0)];
if (vertical) {
fontChar = unicode = String.fromCharCode(vertical);
}
}
glyph = new Glyph(
charcode,
fontChar,
unicode,
accent,
width,
vmetric,
operatorListId,
isSpace,
isInFont
);
this.#glyphCache.set(charcode, glyph);
return glyph;
}String.fromCodePoint 而不是 String.fromCharCode,是因为私有区之外还可能用到增补平面的码位。超过 0x10FFFF 的码位不是合法 Unicode,只警告并保留空字符串——空字符串在画布上是「画了但没宽度」,比抛错安全。
竖排的处理只在缺字体时做:getVerticalPresentationForm 把横排字符换成竖排表现形式(例如把横排的括号换成竖排括号)。嵌入字体自己就带竖排字形,不需要这层替换。
charsToGlyphs 的多字节切分
单个字符码的翻译之上,还有一层「整串翻译」。它是内容流 Tj 的直接入口:
charsToGlyphs(chars) {
// If we translated this string before, just grab it from the cache.
let glyphs = this.#charsCache.get(chars);
if (glyphs) {
return glyphs;
}
glyphs = [];
if (this.cMap) {
// Composite fonts have multi-byte strings, convert the string from
// single-byte to multi-byte.
const c = Object.create(null),
ii = chars.length;
let i = 0;
while (i < ii) {
this.cMap.readCharCode(chars, i, c);
const { charcode, length } = c;
i += length;
// Space is char with code 0x20 and length 1 in multiple-byte codes.
const glyph = this._charToGlyph(
charcode,
length === 1 && chars.charCodeAt(i - 1) === 0x20
);
glyphs.push(glyph);
}
} else {
for (let i = 0, ii = chars.length; i < ii; ++i) {
const charcode = chars.charCodeAt(i);
const glyph = this._charToGlyph(charcode, charcode === 0x20);
glyphs.push(glyph);
}
}
// Enter the translated string into the cache.
this.#charsCache.set(chars, glyphs);
return glyphs;
}简单字体逐字符取 charCodeAt;复合字体必须通过 cMap.readCharCode 才知道「这个码占几个字节」。readCharCode 把结果写进复用的对象 c,避免每次迭代都分配新对象,这是典型的热路径优化。
空格判断在多字节路径里多了一个条件:length === 1。原因是多字节 CMap 里,字节 0x20 也可能只是某个双字节码的一部分,只有「一个字节长、且值就是 0x20」才是真正的空格。简单字体不需要这个条件,因为每个字符本来就只占一个字节。
两级缓存的分工
Font 内部有两个 Map:
class Font {
#charsCache = new Map();
#glyphCache = new Map();它们的键与值完全不同:
| 维度 | #glyphCache | #charsCache |
|---|---|---|
| 键 | 单个字符码(数字) | 整段字符串(chars) |
| 值 | Glyph 实例 | Glyph 数组 |
| 命中场景 | 同一字符在多处出现 | 同一段文本被重复绘制 |
| 失效条件 | 无,字体对象生命周期内一直有效 | 无,字体对象生命周期内一直有效 |
| 典型调用方 | _charToGlyph 自身、文本层逐字查询 | Tj、TJ 的整串翻译 |
两级缓存是包含关系:字符串缓存命中时不会再走字符缓存;字符串缓存未命中时,逐字翻译仍然会复用字符缓存。这样「同一段文本重复出现」省掉切分与查表,「同一字符分散出现」省掉查表与对象分配。
缓存没有主动失效机制。字体对象在 Catalog.fontCache 里以引用为键,页面切换不会重建;文档 cleanup 时整个字体缓存被清空,字体对象随之释放。因此 Font 内部不需要 LRU,也不需要容量上限——它的生命周期天然与文档一致。
glyphCacheValues 的用途
glyphCacheValues 暴露的是值迭代器,不是整个 Map:
get glyphCacheValues() {
return this.#glyphCache.values();
}它只有一个调用方:TranslatedFont.fallback。当主线程报告「字体装载失败」时,Worker 需要把所有已经解析过的字形路径重新发一遍,因为主线程可能只收到了「字体元数据」,没收到后续按需发送的字形路径:
PartialEvaluator.buildFontPaths(
this.font,
/* glyphs = */ this.font.glyphCacheValues,
handler,
evaluatorOptions,
);只暴露迭代器而不是 Map,是一种封装选择:调用方只能遍历,不能写入或删除,避免外部代码破坏缓存一致性。
getCharPositions 与按字节定位
文本层需要知道「每个字形对应原字符串的哪一段」,getCharPositions 就是为此而生:
getCharPositions(chars) {
// This function doesn't use a cache because
// it's called only when saving or printing.
const positions = [];
if (this.cMap) {
const c = Object.create(null);
let i = 0;
while (i < chars.length) {
this.cMap.readCharCode(chars, i, c);
const length = c.length;
positions.push([i, i + length]);
i += length;
}
} else {
for (let i = 0, ii = chars.length; i < ii; ++i) {
positions.push([i, i + 1]);
}
}
return positions;
}返回值是「起始下标、结束下标」的数组。简单字体每个字符占一位,复合字体按 CMap 的实际字节长度切分。它不复用 charsToGlyphs,因为两者关注的不是同一件事:前者要字节区间,后者要字形对象。注释明确说它不加缓存,因为只在保存或打印时调用,调用频率远低于渲染。
设计要点:
Glyph把「绘制用什么、显示用什么、占多宽、从哪来」压进一个对象,#glyphCache再把这个对象按字符码驻留。这样画布层、文本层、打印路径拿到的是同一份结果,不会出现「画布用 A 码位、文本层用 B Unicode」的漂移。代价是Glyph对象必须保持不可变;缓存没有失效机制,任何字段被外部改写都会污染后续所有使用。
ToUnicode 与 toFontChar
两张映射表的分工
字体层有两条方向相反的映射:
toUnicode:字符码 → Unicode,供文本层使用;toFontChar:字符码 → 字体里的码位,供绘制使用。
这两条映射在多数简单字体里恰好重合,但在复合字体、符号字体、私有区搬移之后会完全分开。_charToGlyph 同时查两张表,正是为了让「画出来的形状」与「复制出来的文字」各自正确。
ToUnicodeMap 与 IdentityToUnicodeMap
这两个类不在 fonts.js 里,但在字体构造函数里被反复判断类型,因此必须先弄清它们的语义:
class ToUnicodeMap {
constructor(cmap = []) {
// The elements of this._map can be integers or strings, depending on how
// `cmap` was created.
this._map = cmap;
}
get length() {
return this._map.length;
}
forEach(callback) {
for (const charCode in this._map) {
callback(charCode, this._map[charCode].codePointAt(0));
}
}
has(i) {
return this._map[i] !== undefined;
}
get(i) {
return this._map[i];
}ToUnicodeMap 是对稀疏数组的薄包装。forEach 只遍历实际存在的索引,回调的第二个参数是码点整数;get 返回原始元素,可能是字符串也可能是数字。这个「类型不确定」正是 _charToGlyph 里要判断 typeof unicode === "number" 的原因。
IdentityToUnicodeMap 完全不存数组,只用首尾范围表示恒等映射:
class IdentityToUnicodeMap {
constructor(firstChar, lastChar) {
this.firstChar = firstChar;
this.lastChar = lastChar;
}
get length() {
return this.lastChar + 1 - this.firstChar;
}
forEach(callback) {
for (let i = this.firstChar, ii = this.lastChar; i <= ii; i++) {
callback(i, i);
}
}
has(i) {
return this.firstChar <= i && i <= this.lastChar;
}恒等映射意味着「字符码本身就是 Unicode」。CID 字体最常见这种情况:字符码是 CID,CID 在 Identity CMap 下就是字符码,而字体程序里的字形也按同样顺序排列。用范围表示而不是数组,可以避免为几万个 CID 分配一个巨大的稀疏数组。
IdentityToUnicodeMap.amend 是 unreachable。这解释了为什么 amendFallbackToUnicode、adjustTrueTypeToUnicode、adjustType1ToUnicode 开头都要判断 instanceof IdentityToUnicodeMap:不是「没必要补」,而是「补了会直接崩」。
toFontChar 的构建:buildToFontChar
标准字体回退、符号字体、Dingbats 都走 buildToFontChar:
function buildToFontChar(encoding, glyphsUnicodeMap, differences) {
const toFontChar = [];
let unicode;
for (let i = 0, ii = encoding.length; i < ii; i++) {
unicode = getUnicodeForGlyph(encoding[i], glyphsUnicodeMap);
if (unicode !== -1) {
toFontChar[i] = unicode;
}
}
for (const charCode in differences) {
unicode = getUnicodeForGlyph(differences[charCode], glyphsUnicodeMap);
if (unicode !== -1) {
toFontChar[+charCode] = unicode;
}
}
return toFontChar;
}两轮遍历的顺序很重要:先按编码表整体填,再用 /Differences 覆盖。/Differences 的语义就是「在某个字符码上偏离基础编码」,因此必须后写。getUnicodeForGlyph 返回 -1 表示这个字形名没有对应的 Unicode,此时不写入,而不是写 0——写入 0 会让 toFontChar 看起来「有这个字形」,isInFont 判断就会失真。
adjustMapping:把字符码搬进私有区
嵌入字体最常见的一道加工是 adjustMapping。它把「字符码 → glyph id」的映射整体搬到 Unicode 私有区:
function adjustMapping(charCodeToGlyphId, hasGlyph, newGlyphZeroId, toUnicode) {
const newMap = Object.create(null);
const toUnicodeExtraMap = new Map();
const toFontChar = [];
const usedGlyphIds = new Set();
let privateUseAreaIndex = 0;
const privateUseOffetStart = PRIVATE_USE_AREAS[privateUseAreaIndex][0];
let nextAvailableFontCharCode = privateUseOffetStart;
let privateUseOffetEnd = PRIVATE_USE_AREAS[privateUseAreaIndex][1];
const isInPrivateArea = code =>
(PRIVATE_USE_AREAS[0][0] <= code && code <= PRIVATE_USE_AREAS[0][1]) ||
(PRIVATE_USE_AREAS[1][0] <= code && code <= PRIVATE_USE_AREAS[1][1]);
let LIGATURE_TO_UNICODE = null;私有区有两段:BMP 的 0xE000 到 0xF8FF,以及 16 号平面的 0x100000 到 0x10FFFD。搬移的目的写在 adjustMapping 的文档注释里:避开「某些 Unicode 区域里的字形不会被绘制,或者会被 shaper 变形」的问题。
遍历原始映射时,先跳过空字形:
for (const originalCharCode in charCodeToGlyphId) {
let glyphId = charCodeToGlyphId[originalCharCode];
// For missing glyphs don't create the mappings so the glyph isn't
// drawn.
if (!hasGlyph(glyphId)) {
continue;
}
if (nextAvailableFontCharCode > privateUseOffetEnd) {
privateUseAreaIndex++;
if (privateUseAreaIndex >= PRIVATE_USE_AREAS.length) {
warn("Ran out of space in font private use area.");
break;
}
nextAvailableFontCharCode = PRIVATE_USE_AREAS[privateUseAreaIndex][0];
privateUseOffetEnd = PRIVATE_USE_AREAS[privateUseAreaIndex][1];
}
const fontCharCode = nextAvailableFontCharCode++;
if (glyphId === 0) {
glyphId = newGlyphZeroId;
}hasGlyph 是外部传入的回调:TrueType 路径传 hasGlyph(glyphId)(判断 missingGlyphs),convert 路径传 font.hasGlyphId.bind(font)。跳过空字形是为了「不创建映射,这样字形不会被画出来」——如果给一个空字形也分配私用码位,浏览器会尝试绘制它,结果是一个空白但占位的位置。
glyphId === 0 要换成 newGlyphZeroId,因为 .notdef 在重建后的字体里被复制到了最后。这是「glyph 0 在浏览器里常常不显示」的补丁:字体程序把有效字形放在 glyph 0 位置时,源码复制一份追到末尾,再把所有指向 0 的映射改到新位置。
接着是 Unicode 修复与去重:
let unicode = toUnicode.get(originalCharCode);
if (typeof unicode === "string") {
if (unicode.length === 1) {
unicode = unicode.codePointAt(0);
} else {
if (!LIGATURE_TO_UNICODE) {
LIGATURE_TO_UNICODE = new Map();
// The code range [0xfb00, 0xfb4f] contains some ligature characters
// but not all.
for (let i = 0xfb00; i <= 0xfb4f; i++) {
const normalized = String.fromCharCode(i).normalize("NFKD");
if (normalized.length > 1) {
LIGATURE_TO_UNICODE.set(normalized, i);
}
}
}
unicode = LIGATURE_TO_UNICODE.get(unicode) || unicode.codePointAt(0);
}
}
if (unicode && !isInPrivateArea(unicode) && !usedGlyphIds.has(glyphId)) {
toUnicodeExtraMap.set(unicode, glyphId);
usedGlyphIds.add(glyphId);
}
newMap[fontCharCode] = glyphId;
toFontChar[originalCharCode] = fontCharCode;
}注释里引用的 bug 1778484 解释了 toUnicodeExtraMap 的存在:字符码被搬进私有区之后,打印成 PDF 时生成的字体会带上错误字符。解决办法是把原始 Unicode 也写进 cmap,打印后端就能按 Unicode 把 glyph id 映射回去。
toUnicodeExtraMap 只收录「不在私有区、且 glyph id 还没被用过」的项。usedGlyphIds 防止同一个 glyph 被多个 Unicode 重复登记,因为 cmap 里一个 glyph 对应多个码位会让某些后端行为不一致。
函数返回四个值:
return {
toFontChar,
charCodeToGlyphId: newMap,
toUnicodeExtraMap,
nextAvailableFontCharCode,
};nextAvailableFontCharCode 后续被 convert 用来给 seac 的基字形与重音字形「临时造」新的码位。
私有区搬移的代价
把字符码搬进私有区不是无损操作。它带来三个后果:
toFontChar与字符码彻底分离,isInFont只能靠toFontChar判断,不能靠字符码猜测;toUnicode必须同时维护原始码位,否则文本层拿到的是私有区字符;- 打印与复制路径需要额外的
toUnicodeExtraMap,把私有区码位反查回真实 Unicode。
但收益更大:浏览器字体栈对某些 Unicode 区域(组合符号、RTL 控制符、部分 CJK 兼容区)有特殊处理,直接使用原码位可能不绘制、错位或被字重排。搬到私有区等于告诉浏览器「这是一批普通字形,不要做任何语言相关处理」。
adjustTrueTypeToUnicode 与 adjustType1ToUnicode
两条回退路径还会尝试「从内嵌编码反推 ToUnicode」。TrueType 的版本在 checkAndRepair 末尾调用:
// Try to infer if the fallback encoding should really be `WinAnsiEncoding`.
if (properties.defaultEncoding === WinAnsiEncoding) {
return;
}
for (const r of nameRecords) {
if (!isWinNameRecord(r)) {
return; // Not Windows, hence `WinAnsiEncoding` wouldn't make sense.
}
}
const encoding = WinAnsiEncoding;
const toUnicode = [],
glyphsUnicodeMap = getGlyphsUnicode();
for (const charCode in encoding) {
const glyphName = encoding[charCode];
if (glyphName === "") {
continue;
}
const unicode = glyphsUnicodeMap[glyphName];
if (unicode === undefined) {
continue;
}
toUnicode[charCode] = String.fromCharCode(unicode);
}
if (toUnicode.length > 0) {
properties.toUnicode.amend(toUnicode);
}
}调用前有五道闸门:内部字体不补、已带 /ToUnicode 不补、已带 /Encoding 不补、恒等映射不补、非符号字体不补。只有「符号字体、没有编码信息、name 表全是 Windows 记录」时才推断为 WinAnsiEncoding。这是保守推断:符号字体通常没有有意义的字符语义,只有 Windows 平台名称记录时才暗示它其实是一个伪装成符号的文本字体。
Type1 的版本更直接,它用字体程序自带的内嵌编码:
function adjustType1ToUnicode(properties, builtInEncoding) {
if (properties.isInternalFont) {
return;
}
if (properties.hasIncludedToUnicodeMap) {
return; // The font dictionary has a `ToUnicode` entry.
}
if (builtInEncoding === properties.defaultEncoding) {
return; // No point in trying to adjust `toUnicode` if the encodings match.
}
if (properties.toUnicode instanceof IdentityToUnicodeMap) {
return;
}
const toUnicode = [],
glyphsUnicodeMap = getGlyphsUnicode();
for (const charCode in builtInEncoding) {
if (properties.hasEncoding) {
if (
properties.baseEncodingName ||
properties.differences[charCode] !== undefined
) {
continue; // The font dictionary has an `Encoding`/`Differences` entry.
}
}当字典已经给了 /BaseEncoding 或某个码的 /Differences,那个码就以字典为准,不再用内嵌编码覆盖。这与 buildToFontChar 的「先整体后差异」是同一套优先级:字典显式信息永远高于程序内隐式信息。
设计要点:
toUnicode的所有补丁都遵循「只补空缺,不覆盖显式值」。amendFallbackToUnicode查has,adjustType1ToUnicode查differences,adjustTrueTypeToUnicode先看hasIncludedToUnicodeMap。原因是/ToUnicode是 PDF 作者(或生成器)对「这段字节应该被读成什么」的明确声明,而编码表推断只是猜测。猜测只能填空,不能推翻声明。
TrueType 修复流水线
checkAndRepair 是本文件最长的方法,从 1423 行一直延伸到 3282 行,接近 1900 行。它不是一个「解析器」,而是一条修复流水线:把一份可能来自任意生成器、可能违反 OpenType 规范的字体,重整成浏览器与 OTS 都能接受的版本。
从头复制一份,绝不改原流
方法的第一条实际动作是复制:
// The following steps modify the original font data, making copy
font = new Stream(new Uint8Array(font.getBytes()));注释说得很直白:后续步骤会原地修改数据,因此必须先复制。font.getBytes() 把整个流读成一个 Uint8Array,再包成新的 Stream。这样即使修复失败回退,原始流仍然完好,properties 里的信息也不会被污染。
在复制之前,方法内部定义了一大组闭包函数:readTables、readTableEntry、readOpenTypeHeader、readTrueTypeCollectionHeader、readTrueTypeCollectionData、readCmapTable、sanitizeMetrics、sanitizeGlyph、sanitizeHead、sanitizeGlyphLocations、readPostScriptTable、readNameTable、sanitizeTTProgram、checkInvalidFunctions、foldTTTable、sanitizeTTPrograms。把它们放在方法内部,是为了共享 font 这个流对象与 properties,同时不把这些只服务 TrueType 的工具暴露到模块级。
表的读取与过滤
readTableEntry 读一条 16 字节的表目录项,但有一个细节:它按 offset 回到文件起点重新读表数据:
function readTableEntry(file) {
const tag = file.getString(4);
const checksum = file.getInt32() >>> 0;
const offset = file.getInt32() >>> 0;
const length = file.getInt32() >>> 0;
// Read the table associated data
const previousPosition = file.pos;
file.pos = file.start || 0;
file.skip(offset);
const data = file.getBytes(length);
file.pos = previousPosition;
if (tag === "head") {
// clearing checksum adjustment
data[8] = data[9] = data[10] = data[11] = 0;
data[17] |= 0x20; // Set font optimized for cleartype flag.
}
// The "CFF " table may be replaced completely, hence its data shouldn't
// need to be read and/or modified piecewise through a `DataView`.
const view =
tag === "CFF "
? null
: new DataView(data.buffer, data.byteOffset, data.byteLength);head 表一读进来就清掉 checksum adjustment,并置上 ClearType 优化位。checksum 是「整个文件的校验和补偿值」,修复之后必然变化,因此先清零。CFF 表不建 DataView,因为它后续会被整段替换,按字节视图修改没有意义。
readTables 只保留白名单里的表:
function readTables(file, numTables) {
const tables = Object.create(null);
tables['OS/2'] = null;
tables.cmap = null;
tables.head = null;
tables.hhea = null;
tables.hmtx = null;
tables.maxp = null;
tables.name = null;
tables.post = null;
for (let i = 0; i < numTables; i++) {
const table = readTableEntry(file);
if (!VALID_TABLES.includes(table.tag)) {
continue; // skipping table if it's not a required or optional table
}
if (table.length === 0) {
continue; // skipping empty tables
}
tables[table.tag] = table;
}
return tables;
}白名单是 OS/2、cmap、head、hhea、hmtx、maxp、name、post、loca、glyf、fpgm、prep、cvt 、CFF 。这些是「渲染与度量必需」或「TrueType 指令必需」的表。其它表(DSIG、GDEF、GPOS、GSUB、kern、hdmx 等)全部丢弃,因为 PDF.js 的用途是「显示固定内容」,不需要排版特性,也不需要数字签名。丢弃未知表还能规避大量解析器兼容问题。
Object.create(null) 与前面讲过的 CmdCache 同理:表标签来自文件内容,可能是 __proto__ 之类的字符串,无原型对象可以避免假命中。
TrueType Collection 与 OpenType 的提前分流
TrueType Collection 是「一个文件装多套字体」。源码先读 TTC 头,再按字体名挑一套:
let header, tables;
if (isTrueTypeCollectionFile(font)) {
const ttcData = readTrueTypeCollectionData(font, this.name);
header = ttcData.header;
tables = ttcData.tables;
} else {
header = readOpenTypeHeader(font);
tables = readTables(font, header.numTables);
}
const isTrueType = !tables['CFF '];readTrueTypeCollectionData 遍历 offsetTable 里的每套字体,读它的 name 表,把名称与 this.name 做去除空白后的精确比较;找不到就退而求其次,按 + 拆开的名字片段匹配。还找不到才抛 FormatError。匹配成功之后,后续所有读取都基于这一套字体的表目录,而不是整个 TTC 文件。
接着是 CFF 的特殊分支:
// OpenType font (skip composite fonts with non-default glyph mapping).
if (
(header.version === 'OTTO' &&
(!properties.composite || (properties.fontFileN === 'FontFile3' && parsedCff?.isCIDFont))) ||
!tables.head ||
!tables.hhea ||
!tables.maxp ||
!tables.post
) {
// No major tables: throwing everything at `CFFFont`.
return this.convert(name, new CFFFont(new Stream(tables['CFF '].data), properties), properties);
}这段的意思是:如果文件是 OTTO(OpenType 外壳)、且「不是复合字体,或者复合字体但 CFF 是 CID 字体」,就直接走 convert;如果缺少 head、hhea、maxp、post 任一必需表,也走 convert。convert 会把 CFF 数据重新包一层 OTF,不需要修复 TrueType 的轮廓与指令。
this.isOpenType 标记决定后续 checkAndRepair 是否处理 glyf。纯 CFF 的 OpenType 会删掉 glyf、loca、fpgm、prep、cvt ,只保留字形度量与 CFF 数据。
必需表与 maxp 版本修正
进入 TrueType 主路之后,源码先做几项硬性校验:
if (!tables.loca) {
throw new FormatError('Required "loca" table is not found');
}
if (!tables.glyf) {
warn('Required "glyf" table is not found -- trying to recover.');
// Note: We use `sanitizeGlyphLocations` to add dummy glyf data below.
tables.glyf = {
tag: 'glyf',
data: new Uint8Array(0),
};
}loca 缺失直接抛错,因为没有它就无法定位任何字形;glyf 缺失只警告并补一个空表,sanitizeGlyphLocations 会在最后造一个「只有一个点」的占位字形,让字体至少合法。这两者的区别体现了「没有替代方案才失败」的原则。
maxp 表的版本号也经常写错:
font.pos = (font.start || 0) + tables.maxp.offset;
let version = font.getInt32();
const numGlyphs = numGlyphsFromCFF ?? font.getUint16();
if (version === 0x00005000 && tables.maxp.length !== 6) {
tables.maxp.data = tables.maxp.data.subarray(0, 6);
tables.maxp.length = 6;
}
if (version !== 0x00010000 && version !== 0x00005000) {
if (tables.maxp.length === 6) {
version = 0x0005000;
} else if (tables.maxp.length >= 32) {
version = 0x00010000;
} else {
throw new FormatError(`"maxp" table has a wrong version number`);
}
writeUint32(tables.maxp.data, 0, version);
}OpenType 的 maxp 有两个合法版本:0x00005000(只有 6 字节,CFF 字体用)与 0x00010000(32 字节,TrueType 用)。源码用表长度反推版本,而不是相信第一个 4 字节。长度是 6 就写 0.5,长度至少 32 就写 1.0,其它长度才抛错。这是典型的「结构自证」:表长度是物理事实,版本号是可写坏的字段。
字形位置的修复
loca 表存的是每个字形在 glyf 表里的偏移,长度必须严格等于 (numGlyphs + 1) 乘以每项字节数:
if (tables.loca) {
const locaLength = isGlyphLocationsLong ? (numGlyphs + 1) * 4 : (numGlyphs + 1) * 2;
if (tables.loca.length !== locaLength) {
warn("Incorrect 'loca' table length -- attempting to fix it.");
// The length of the loca table is wrong (see #13425), so we check if we
// have enough space to fix it.
const sortedTables = Object.values(tables)
.filter(Boolean)
.sort((a, b) => a.offset - b.offset);
const locaIndex = sortedTables.indexOf(tables.loca);
const nextTable = sortedTables[locaIndex + 1] || null;
if (nextTable && tables.loca.offset + locaLength < nextTable.offset) {
const previousPos = font.pos;
font.pos = font.start || 0;
font.skip(tables.loca.offset);
tables.loca.data = font.getBytes(locaLength);
tables.loca.length = locaLength;
font.pos = previousPos;
}
}
}修复手法是「按正确长度重新截取」:只要 loca 起点加上正确长度还没有越过下一张表的起点,就说明文件里确实有这么多字节,只是目录项写错了长度,直接重读一段即可。如果空间不够,则保持原样,后续 sanitizeGlyphLocations 会按可用长度尽量处理。
isGlyphLocationsLong 来自 head 表的 indexToLocFormat 字段。sanitizeHead 会在它超出 0 到 1 的范围时,用 loca 表长度反推:
const numGlyphsPlusOne = numGlyphs + 1;
if (locaLength === numGlyphsPlusOne << 1) {
// 0x0000 indicates the loca table consists of short offsets
data[50] = 0;
data[51] = 0;
} else if (locaLength === numGlyphsPlusOne << 2) {
// 0x0001 indicates the loca table consists of long offsets
data[50] = 0;
data[51] = 1;
} else {
throw new FormatError('Could not fix indexToLocFormat: ' + indexToLocFormat);
}短偏移每项 2 字节,长偏移每项 4 字节。用 << 1 与 << 2 分别表示「乘以 2」与「乘以 4」,与长度公式一一对应。两个都对不上时才抛错,因为此时无法确定字形边界,任何猜测都会画出错位的形状。
sanitizeGlyph 与字形轮廓清理
sanitizeGlyph 是单个字形的守门员。它先检查偏移范围,再修正包围盒:
const glyf = source.subarray(sourceStart, sourceEnd);
// Sanitize the glyph bounding box.
const xMin = signedInt16(glyf[2], glyf[3]);
const yMin = signedInt16(glyf[4], glyf[5]);
const xMax = signedInt16(glyf[6], glyf[7]);
const yMax = signedInt16(glyf[8], glyf[9]);
if (xMin > xMax) {
writeSignedInt16(glyf, 2, xMax);
writeSignedInt16(glyf, 6, xMin);
}
if (yMin > yMax) {
writeSignedInt16(glyf, 4, yMax);
writeSignedInt16(glyf, 8, yMin);
}
const contoursCount = signedInt16(glyf[0], glyf[1]);
if (contoursCount < 0) {
if (contoursCount < -1) {
// OTS doesn't like contour count to be less than -1.
// The glyph data offsets are very likely wrong and
// having something lower than -1, very likely, implies
// to have some garbage data.
return glyphProfile;
}
// complex glyph, writing as is
dest.set(glyf, destStart);
glyphProfile.length = glyf.length;
return glyphProfile;
}轮廓数小于 0 表示这是复合字形(由其它字形组合而成),直接原样保留。小于 -1 的值不是合法复合字形,说明偏移完全错了,返回长度为 0 的 profile,等于把这个字形丢掉。
对简单字形,清理逻辑更细:
// validating flags
let coordinatesLength = 0;
for (i = 0; i < flagsCount; i++) {
const flag = glyf[j++];
if (flag & 0xc0) {
// reserved flags must be zero, cleaning up
glyf[j - 1] = flag & 0x3f;
}
let xLength = 2;
if (flag & 2) {
xLength = 1;
} else if (flag & 16) {
xLength = 0;
}
let yLength = 2;
if (flag & 4) {
yLength = 1;
} else if (flag & 32) {
yLength = 0;
}
const xyLength = xLength + yLength;
coordinatesLength += xyLength;
if (flag & 8) {
const repeat = glyf[j++];
if (repeat === 0) {
// The repeat count should be non-zero when the repeat flag is set.
glyf[j - 1] ^= 8;
}
i += repeat;
coordinatesLength += repeat * xyLength;
}
}
// glyph without coordinates will be rejected
if (coordinatesLength === 0) {
return glyphProfile;
}标志位的高两位是保留位,规范要求为 0,这里直接清零;xLength 与 yLength 按标志位决定每个坐标占 0、1、2 字节;repeat 标志表示「后续若干点复用同一个标志」,但重复次数不能为 0,遇到 0 就把重复标志本身清掉。这些修正的目标是让坐标数据的总长度可计算,从而判断数据是否完整。
hintsValid 为 false 时,字形里的 TrueType 指令会被整段删掉:
if (!hintsValid && instructionsLength > 0) {
dest.set(glyf.subarray(0, instructionsStart), destStart);
dest.set([0, 0], destStart + instructionsStart);
dest.set(glyf.subarray(instructionsEnd, glyphDataLength), destStart + instructionsStart + 2);
glyphDataLength -= instructionsLength;
if (glyf.length - glyphDataLength > 3) {
glyphDataLength = (glyphDataLength + 3) & ~3;
}
glyphProfile.length = glyphDataLength;
return glyphProfile;
}指令长度字段被写成 0,指令字节被跳过,后面的坐标数据整体前移。这是「不信任 hinting」时的降级:不做网格对齐,但仍然画出轮廓。& ~3 是四字节对齐,OpenType 要求字形数据按 4 字节对齐。
sanitizeGlyphLocations 的三次重排
sanitizeGlyphLocations 修的是「loca 表本身」。规范要求偏移非降序,且不能为 0 表示缺失;现实中大量字体违反这两条,因此源码做了三次排序:
const locaEntries = [];
// There are numGlyphs + 1 loca table entries.
for (i = 0, j = 0; i < numGlyphs + 1; i++, j += itemSize) {
let offset = itemDecode(locaData, j);
if (offset > oldGlyfDataLength) {
offset = oldGlyfDataLength;
}
locaEntries.push({
index: i,
offset,
endOffset: 0,
});
}
locaEntries.sort((a, b) => a.offset - b.offset);
// Now the offsets are sorted, calculate the end offset of each glyph.
// The last loca entry's endOffset is not calculated since it's the end
// of the data and will be stored on the previous entry's endOffset.
for (i = 0; i < numGlyphs; i++) {
locaEntries[i].endOffset = locaEntries[i + 1].offset;
}
// Re-sort so glyphs aren't out of order.
locaEntries.sort((a, b) => a.index - b.index);第一次排序按偏移,让「前一项偏移小于后一项」成立;排序后相邻两项的偏移差就是该字形的字节长度。第二次排序按原始索引恢复顺序,保证 glyph id 与字形数据的对应关系不变。
第三次修正针对「开头多个空字形」:
// Calculate the endOffset of the "first" glyph correctly when there are
// *multiple* empty ones at the start of the data (fixes issue14618.pdf).
for (i = 0; i < numGlyphs; i++) {
const { offset, endOffset } = locaEntries[i];
if (offset !== 0 || endOffset !== 0) {
break;
}
const nextOffset = locaEntries[i + 1].offset;
if (nextOffset === 0) {
continue;
}
locaEntries[i].endOffset = nextOffset;
break;
}当 glyph 0 与 glyph 1 的偏移都是 0 时,按相邻差算出的 glyph 0 长度也是 0,但实际数据可能从后面某个非零偏移开始。这段循环把「第一个非零偏移」之前的最后一个空字形补上长度,避免整段字形数据被当成空。
复合字形的环检测
sanitizeGlyphLocations 在逐个清理之前先调用 pruneCompositeGlyphCycles:
const droppedGlyphs = pruneCompositeGlyphCycles(oldGlyfData, locaEntries, numGlyphs);复合字形可以引用其它字形,而引用关系可能成环。环在渲染时会无限递归,因此必须提前找出来并丢弃。这个函数在 glyf.js 里,返回一个「被丢弃的 glyph id 集合」;后续循环遇到集合里的 id 就直接给一个空 profile,不再尝试解析。
这正是 glyf.js 与 fonts.js 分工的体现:fonts.js 负责「表结构与度量」,glyf.js 负责「字形轮廓的图结构」。
字形的最终写入
清理完每个字形后,源码重写 loca 与 glyf:
const missingGlyphs = Object.create(null);
let writeOffset = 0;
itemEncode(locaData, 0, writeOffset);
for (i = 0, j = itemSize; i < numGlyphs; i++, j += itemSize) {
const glyphProfile = droppedGlyphs.has(i)
? { length: 0, sizeOfInstructions: 0 }
: sanitizeGlyph(
oldGlyfData,
locaEntries[i].offset,
locaEntries[i].endOffset,
newGlyfData,
writeOffset,
hintsValid,
);
const newLength = glyphProfile.length;
if (newLength === 0) {
missingGlyphs[i] = true;
}
if (glyphProfile.sizeOfInstructions > maxSizeOfInstructions) {
maxSizeOfInstructions = glyphProfile.sizeOfInstructions;
}
writeOffset += newLength;
itemEncode(locaData, j, writeOffset);
}missingGlyphs 是后续 hasGlyph 的数据来源:长度被清零的字形记为缺失,adjustMapping 遇到它就不分配映射。maxSizeOfInstructions 被顺手统计出来,后面写回 maxp,因为很多字体的这个字段也是错的。
如果所有字形都被清理成空,源码造一个最小合法字形:
if (writeOffset === 0) {
// glyf table cannot be empty -- redoing the glyf and loca tables
// to have single glyph with one point
const simpleGlyph = new Uint8Array([0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 49, 0]);
for (i = 0, j = itemSize; i < numGlyphsOut; i++, j += itemSize) {
itemEncode(locaData, j, simpleGlyph.length);
}
glyf.data = simpleGlyph;
}glyf 表不能为空,否则 OTS 会拒绝整个字体。造一个「一个轮廓、一个点」的字形,至少让表结构合法。这个字体最终画出来什么都没有,但页面不会因此变成错误字体。
复制 glyph 0
浏览器普遍不显示 glyph 0,而不少字体把有效字形放在这里。源码的通用对策是复制一份追到末尾:
} else if (dupFirstEntry) {
// Browsers will not display a glyph at position 0. Typically glyph 0
// is notdef, but a number of fonts put a valid glyph there so it must
// be duplicated and appended.
const firstEntryLength = itemDecode(locaData, itemSize);
if (newGlyfData.length > firstEntryLength + writeOffset) {
glyf.data = newGlyfData.subarray(0, firstEntryLength + writeOffset);
} else {
glyf.data = new Uint8Array(firstEntryLength + writeOffset);
glyf.data.set(newGlyfData.subarray(0, writeOffset));
}
glyf.data.set(newGlyfData.subarray(0, firstEntryLength), writeOffset);
itemEncode(
loca.data,
locaData.length - itemSize,
writeOffset + firstEntryLength
);
}复制之后,numGlyphsOut 变成 numGlyphs + 1,glyphZeroId 变成 numGlyphsOut - 1。adjustMapping 里所有指向 glyph 0 的映射都被改到新位置。如果 glyph 总数已经达到 0xFFFF,没有空间再复制,dupFirstEntry 置 false,glyphZeroId 退回 0——源码注释说「这比整个字体失败要好」。
sanitizeMetrics 与 hmtx 补齐
hmtx 需要为每个字形提供「前进宽度 + 左侧方位」。有些字体只写了前面若干个字形的完整度量,后面的只写宽度:
const numOfSidebearings = numGlyphs - numOfMetrics;
const numMissing = numOfSidebearings - ((metrics.length - numOfMetrics * 4) >> 1);
if (numMissing > 0) {
// For each missing glyph, we set both the width and lsb to 0 (zero).
// Since we need to add two properties for each glyph, this explains
// the use of |numMissing * 2| when initializing the typed array.
const entries = new Uint8Array(metrics.length + numMissing * 2);
entries.set(metrics.data);
if (dupFirstEntry) {
// Set the sidebearing value of the duplicated glyph.
entries[metrics.length] = metrics.data[2];
entries[metrics.length + 1] = metrics.data[3];
}
metrics.data = entries;
}numOfMetrics 是 hhea 里声明的「完整度量数量」。超出的字形只需要 2 字节的左侧方位,所以缺失字节数按 numMissing * 2 补零。复制 glyph 0 时,新字形的左侧方位沿用原 glyph 0 的字节,保证复制前后的度量一致。
同一函数还修 caretOffset 与 numOfMetrics 越界:
if (numOfMetrics > numGlyphs) {
info(
`The numOfMetrics (${numOfMetrics}) should not be ` +
`greater than the numGlyphs (${numGlyphs}).`,
);
// Reduce numOfMetrics if it is greater than numGlyphs
numOfMetrics = numGlyphs;
header.data[34] = (numOfMetrics & 0xff00) >> 8;
header.data[35] = numOfMetrics & 0x00ff;
}numOfMetrics 大于字形总数时,多出来的度量没有任何意义,直接截到字形总数并回写 hhea。
TrueType 指令的静态分析
sanitizeTTProgram 是一个简化的 TrueType 解释器,目的不是执行指令,而是遍历控制流、统计函数定义与栈变化:
function sanitizeTTPrograms(fpgm, prep, cvt, maxFunctionDefs) {
const ttContext = {
functionsDefined: [],
functionsUsed: [],
functionsStackDeltas: [],
tooComplexToFollowFunctions: false,
hintsValid: true,
};
if (fpgm) {
sanitizeTTProgram(fpgm, ttContext);
}
if (prep) {
sanitizeTTProgram(prep, ttContext);
}
if (fpgm) {
checkInvalidFunctions(ttContext, maxFunctionDefs);
}
if (cvt && cvt.length & 1) {
const cvtData = new Uint8Array(cvt.length + 1);
cvtData.set(cvt.data);
cvt.data = cvtData;
}
return ttContext.hintsValid;
}fpgm 定义函数,prep 执行一次准备代码,cvt 是控制值表。cvt 长度必须是偶数,奇数时补一个字节。遍历过程中如果发现「调用了未定义函数」「函数定义数量超限」「栈深变成负数」,hintsValid 被置 false,后续所有字形的指令都会被删掉。
sanitizeTTProgram 里维护了一个栈模型,但它不精确执行:
// Adjusting stack not exactly, but just enough to get function id
if (!inFDEF && !inELSE) {
let stackDelta = 0;
if (op <= 0x8e) {
stackDelta = TTOpsStackDeltas[op];
} else if (op >= 0xc0 && op <= 0xdf) {
stackDelta = -1;
} else if (op >= 0xe0) {
stackDelta = -2;
}
if (op >= 0x71 && op <= 0x75) {
n = stack.pop();
if (!isNaN(n)) {
stackDelta = -n * 2;
}
}
while (stackDelta < 0 && stack.length > 0) {
stack.pop();
stackDelta++;
}
while (stackDelta > 0) {
stack.push(NaN); // pushing any number into stack
stackDelta--;
}
}TTOpsStackDeltas 是一张「每条指令对栈深的净影响」表。真正的数值不重要,源码只需要知道「执行到 CALL 时栈顶是不是一个合法的函数编号」。因此缺失的值用 NaN 填充,遇到 NaN 就记为无效。这个设计让静态分析在常数空间内完成,不需要模拟字体里的实际数值。
度量的真实来源
清理完表结构之后,源码用 head 与 hhea 覆盖 PDF 字典里的度量:
// Extract some more font properties from the OpenType head and
// hhea tables; yMin and descent value are always negative.
const metricsOverride = {
unitsPerEm: int16(tables.head.data[18], tables.head.data[19]),
yMax: signedInt16(tables.head.data[42], tables.head.data[43]),
yMin: signedInt16(tables.head.data[38], tables.head.data[39]),
ascent: signedInt16(tables.hhea.data[4], tables.hhea.data[5]),
descent: signedInt16(tables.hhea.data[6], tables.hhea.data[7]),
lineGap: signedInt16(tables.hhea.data[8], tables.hhea.data[9]),
};
// PDF FontDescriptor metrics lie -- using data from actual font.
this.ascent = metricsOverride.ascent / metricsOverride.unitsPerEm;
this.descent = metricsOverride.descent / metricsOverride.unitsPerEm;
this.lineGap = metricsOverride.lineGap / metricsOverride.unitsPerEm;注释里的「PDF FontDescriptor metrics lie」是这份代码里最直白的一句话。/Ascent、/Descent 是作者写在字典里的声明,而 hhea 是字体程序自带的实测值。渲染时用后者,文本选择与布局才与真实字形一致。
除以 unitsPerEm 而不是 1000,是因为 head 里的 unitsPerEm 可以是 1024、2048 或 1000。这一步把「设计单位」换成「相对字身」,与前面 properties.ascent / 1000 的目标一致,但精度更高。
lineHeight 也随之更新:
if (this.cssFontInfo?.lineHeight) {
this.lineHeight = this.cssFontInfo.metrics.lineHeight;
this.lineGap = this.cssFontInfo.metrics.lineGap;
} else {
this.lineHeight = this.ascent - this.descent + this.lineGap;
}有 CSS 字体信息时,行高与行距完全由 cssFontInfo.metrics 决定,字体自己的 hhea 只提供 ascent 与 descent。普通路径则把 lineGap 加进行高,这是 OpenType 推荐的排版公式。
复合字体:CMap 与 CIDToGIDMap
字符码到 glyph id 的映射分两条完全不同的路径。复合字体直接用 CMap:
if (properties.composite) {
const cidToGidMap = properties.cidToGidMap || [];
const isCidToGidMapEmpty = cidToGidMap.length === 0;
properties.cMap.forEach(function (charCode, cid) {
if (typeof cid === 'string') {
cid = convertCidString(charCode, cid /* shouldThrow = true */);
}
if (cid > 0xffff) {
throw new FormatError('Max size of CID is 65,535');
}
let glyphId = -1;
if (isCidToGidMapEmpty) {
glyphId = cid;
} else if (cidToGidMap[cid] !== undefined) {
glyphId = cidToGidMap[cid];
}
if (glyphId >= 0 && glyphId < numGlyphs && hasGlyph(glyphId)) {
charCodeToGlyphId[charCode] = glyphId;
}
});
}没有 /CIDToGIDMap 时,CID 就是 glyph id;有映射表时查表。查不到或越界或字形缺失,就不建立映射。这样 _charToGlyph 里的 toFontChar 就不会包含「指向不存在的字形」的项。
简单字体:cmap 子表的优先级
简单字体的映射需要处理「字体的内嵌 cmap」与「PDF 字典的 Encoding」两套信息。readCmapTable 先按规范选子表:
if (
platformId === 0 &&
(encodingId === /* Unicode Default */ 0 ||
encodingId === /* Unicode 1.1 */ 1 ||
encodingId === /* Unicode BMP */ 3)
) {
useTable = true;
// Continue the loop since there still may be a higher priority
// table.
} else if (platformId === 1 && encodingId === 0) {
useTable = true;
// Continue the loop since there still may be a higher priority
// table.
} else if (
platformId === 3 &&
encodingId === 1 &&
(hasEncoding || !potentialTable)
) {
useTable = true;
if (!isSymbolicFont) {
canBreak = true;
}
} else if (isSymbolicFont && platformId === 3 && encodingId === 0) {
useTable = true;优先级是:非符号字体优先 (3, 1),其次 (1, 0) 与平台 0;符号字体优先 (3, 0)。源码注释说明它利用了「子表按 platformId 排序」这一事实,因此可以在遇到更高优先级时继续扫描,遇到确定最优时提前 break。
子表格式支持 0、2、4、6、12:
| 格式 | 结构 | 典型用途 |
|---|---|---|
| 0 | 256 字节直接索引 | 早期 Mac 字体 |
| 2 | 高低字节分段 + 子头 | CJK 双字节字体 |
| 4 | 分段映射 + idDelta | Windows BMP 最常用 |
| 6 | 连续区间直接映射 | 小型子集字体 |
| 12 | 分组映射,支持增补平面 | 大字符集、emoji |
格式 4 的读取有一段容易看错的偏移换算:offsetIndex 由 (rangeOffset >> 1) - (segCount - segIndex) 得到,再与 offsetIndex + segment.end - segment.start + 1 取最大值,作为 glyphIdArray 需要读取的项数。
rangeOffset 是「从当前 idRangeOffset 字段位置到 glyphIdArray 的字节距离」,右移一位得到「多少个 16 位项」。减去「当前段到数组末尾的段数」,就得到该段在 glyphIdArray 里的起始索引。这段公式来自规范,源码只是照做。
简单字体的三条映射规则
选好 cmap 子表之后,源码按规范 9.6.6.4 处理三种情况。最常见的是「有 Encoding 且非符号字体、子表是 (3, 1) 或 (1, 0)」:
for (const mapping of cmapMappings) {
if (mapping.charCode !== unicodeOrCharCode) {
continue;
}
charCodeToGlyphId[charCode] = mapping.glyphId;
break;
}它先用字符码在 /Differences、/BaseEncoding、StandardEncoding 三级里查出字形名,再用 recoverGlyphName 修正非标准名,最后把字形名换成 Unicode 或 MacRoman 索引,去 cmap 里找对应项。这个顺序的关键在于:cmap 的键是 Unicode,而 PDF 的键是字符码,两者之间必须通过字形名搭桥。
平台 0 的子表直接按 Unicode 语义使用:
} else if (cmapPlatformId === 0) {
// Default Unicode semantics, use the charcodes as is.
for (const mapping of cmapMappings) {
charCodeToGlyphId[mapping.charCode] = mapping.glyphId;
}
// Always prefer the BaseEncoding/Differences arrays, when they exist
// (fixes issue13433.pdf).
forcePostTable = true;
} else if (cmapPlatformId === 3 && cmapEncodingId === 0) {
// When a (3, 0) cmap table is present, it is used instead but the
// spec has special rules for char codes in the range of 0xF000 to
// 0xF0FF and it says the (3, 0) table should map the values from
// the (1, 0) table by prepending 0xF0 to the char codes. To reverse
// this, the upper bits of the char code are cleared, but only for the
// special range since some PDFs have char codes outside of this range
// (e.g. 0x2013) which when masked would overwrite other values in the
// cmap.
for (const mapping of cmapMappings) {
let charCode = mapping.charCode;
if (charCode >= 0xf000 && charCode <= 0xf0ff) {
charCode &= 0xff;
}
charCodeToGlyphId[charCode] = mapping.glyphId;
}
} else {(3, 0) 的 0xF000 到 0xF0FF 段是「把单字节码加上 0xF0 前缀」的产物,因此反向映射时要把高位清掉。限制在这个区间内是必要的:有些 PDF 直接用 0x2013 这样的 Unicode 作字符码,如果无条件 & 0xFF 会把它们错误地折叠到低字节。
最后一步是用 post 表补缺:
// Last, try to map any missing charcodes using the post table.
if (properties.glyphNames && (baseEncoding.length || this.differences.length)) {
for (let i = 0; i < 256; ++i) {
if (!forcePostTable && charCodeToGlyphId[i] !== undefined) {
continue;
}
const glyphName = this.differences[i] || baseEncoding[i];
if (!glyphName) {
continue;
}
const glyphId = properties.glyphNames.indexOf(glyphName);
if (glyphId > 0 && hasGlyph(glyphId)) {
charCodeToGlyphId[i] = glyphId;
}
}
}post 表里的 glyphNames 是「按 glyph id 排列的字形名数组」,indexOf 得到的就是 glyph id。forcePostTable 为 true 时连已有映射也要覆盖,因为平台 0 的 cmap 已经给出了 Unicode 语义,而 PDF 字典里的 Encoding 才是作者对字符码的最终声明。
私有区重建与 OS/2
映射建好之后,源码统一调用 adjustMapping 并重建 cmap 与 OS/2:
// When `cssFontInfo` is set, the font is used to render text in the HTML
// view (e.g. with Xfa) so nothing must be moved in the private use area.
if (!properties.cssFontInfo) {
// Converting glyphs and ids into font's cmap table
const newMapping = adjustMapping(charCodeToGlyphId, hasGlyph, glyphZeroId, this.toUnicode);
this.toFontChar = newMapping.toFontChar;
tables.cmap = {
tag: 'cmap',
data: createCmapTable(newMapping.charCodeToGlyphId, newMapping.toUnicodeExtraMap, numGlyphsOut),
};
if (!tables['OS/2'] || !validateOS2Table(tables['OS/2'], font)) {
tables['OS/2'] = {
tag: 'OS/2',
data: createOS2Table(properties, newMapping.charCodeToGlyphId, metricsOverride),
};
}
}cssFontInfo 存在时跳过搬移,因为这类字体要在 HTML 视图里按真实 Unicode 渲染,搬进私有区反而会让浏览器找不到对应字符。这是 XFA 支持带来的例外分支。
validateOS2Table 只校验几个「会让字体完全不可用」的字段:
function validateOS2Table(os2, file) {
file.pos = (file.start || 0) + os2.offset;
const version = file.getUint16();
const minLength = [78, 86, 96, 96, 96, 100][version];
if (minLength === undefined || os2.length < minLength) {
return false;
}
// TODO verify all OS/2 tables fields, but currently we validate only those
// that give us issues
file.skip(60); // skipping type, misc sizes, panose, unicode ranges
const selection = file.getUint16();
if (version < 4 && selection & 0x0300) {
return false;
}
const firstChar = file.getUint16();
const lastChar = file.getUint16();
if (firstChar > lastChar) {
return false;
}
file.skip(6); // skipping sTypoAscender/Descender/LineGap
const usWinAscent = file.getUint16();
if (usWinAscent === 0) {
// makes font unreadable by windows
return false;
}
// OS/2 appears to be valid, resetting some fields
os2.data[8] = os2.data[9] = 0; // IE rejects fonts if fsType != 0
return true;
}校验项包括:版本对应的最小长度、旧版本不允许的样式位、首尾字符顺序、usWinAscent 非零。最后还把 fsType 清零,因为 IE 会因为嵌入权限位拒绝装载字体。校验通过就保留原表,失败就整张重建。
createOS2Table 与 createCmapTable 都是纯字节拼装,用 DataBuilder 写大端整数。它们不在本篇展开,只需要知道:重建后的表与映射完全一致,而原表可能与修复后的映射脱节。
name 表与 ToUnicode 推断
// Re-creating 'name' table
if (!tables.name) {
tables.name = {
tag: 'name',
data: createNameTable(this.name),
};
} else {
// ... using existing 'name' table as prototype
const [namePrototype, nameRecords] = readNameTable(tables.name);
tables.name.data = createNameTable(name, namePrototype);
this.psName = namePrototype[0][6] || null;
if (!properties.composite) {
// For TrueType fonts that do not include `ToUnicode` or `Encoding`
// data, attempt to use the name-table to improve text selection.
adjustTrueTypeToUnicode(properties, this.isSymbolicFont, nameRecords);
}
}createNameTable 需要同时生成 Mac 与 Windows 两套字符串:Mac 每字符 1 字节,Windows 每字符 2 字节。namePrototype 是原表里的字符串,作为模板保留版权、家族名等信息。psName 取 name ID 6(PostScript 名),后面用于 CSS 或调试。
最后把保留的表交给 OpenTypeFileBuilder 重新组装:
const builder = new OpenTypeFileBuilder(header.version);
for (const tableTag in tables) {
builder.addTable(tableTag, tables[tableTag].data);
}
return builder.toArray();header.version 是原文件的版本标记(\x00\x01\x00\x00 或 OTTO),保持原样,避免改变字体类型。
设计要点:
checkAndRepair的每一步都在回答同一个问题——「这个字段坏了,我还能不能继续画字?」。表目录坏了就按真实长度重读,loca 坏了就排序重建,字形坏了就清零并记为缺失,指令坏了就整段删除,连 glyf 全空都还能造一个占位字形。整个流水线只有两类地方抛错:无法确定字形边界(indexToLocFormat两个长度都对不上)、必需表缺失且无法重建(loca、maxp、head、hhea)。这是「修复优先」思路的极致版本。
Type1 与 CFF 的 OTF 包装
为什么不能直接交出去
Type1 与 CFF 都不是浏览器能直接装载的格式。浏览器需要的是 sfnt 容器(扩展名通常是 otf 或 ttf),里面有 head、hhea、hmtx、maxp、cmap、name、post、OS/2 这些表。Type1 是 PostScript 源码加加密段,CFF 是紧凑的字形程序容器,两者单独拿出来都不能被 FontFace 接受。
convert 的职责就是「造一个外壳」:把原始字形程序放进 CFF 表,其余表按字体属性手工拼出来。它不解析轮廓,因为浏览器拿到 CFF 之后会自己解析。
glyphZeroId:两个格式对 glyph 0 的处理不同
// Type 1 fonts have a notdef inserted at the beginning, so glyph 0
// becomes glyph 1. In a CFF font glyph 0 is appended to the end of the
// char strings.
const glyphZeroId = font instanceof CFFFont ? font.numGlyphs - 1 : 1;
const mapping = font.getGlyphMapping(properties);
let newMapping = null;
let newCharCodeToGlyphId = mapping;
let toUnicodeExtraMap = null;Type1 的 Type1Font 在解析时会先插入一个 .notdef,因此原始字形整体后移一位,glyph 0 对应的「真实字形」是 1。CFF 则相反,CFFFont 把 glyph 0 复制到字符程序数组末尾,真实 glyph 0 在最后一位。
这两个值都会传给 adjustMapping 作为 newGlyphZeroId,让所有原本指向 glyph 0 的字符码改指向「真正能画出来的那份」。
adjustMapping 与 seac 的码位分配
if (!properties.cssFontInfo) {
newMapping = adjustMapping(mapping, font.hasGlyphId.bind(font), glyphZeroId, this.toUnicode);
this.toFontChar = newMapping.toFontChar;
newCharCodeToGlyphId = newMapping.charCodeToGlyphId;
toUnicodeExtraMap = newMapping.toUnicodeExtraMap;
}
const numGlyphs = font.numGlyphs;Type1/CFF 路径的 hasGlyph 是 font.hasGlyphId。Type1 的实现长这样:
hasGlyphId(id) {
if (id < 0 || id >= this.numGlyphs) {
return false;
}
if (id === 0) {
// notdef is always defined.
return true;
}
const glyph = this.charstrings[id - 1];
return glyph.charstring.length > 0;
}CFFFont 则把这个调用直接转给底层的 CFF 解析器:return this.cff.hasGlyphId(id);。两者语义相同——「这个 glyph id 对应的字符程序存在且非空」,只是数据来源从 glyf 换成了字符程序。
seac 的处理需要一个「临时码位」分配器 createCharCode:它先在 charCodeToGlyphId 里找「已经指向目标 glyph id」的字符码,找不到就从 newMapping.nextAvailableFontCharCode 里领一个新的并写回映射。charCode | 0 是必要的:for in 遍历出的键是字符串,| 0 把它转回 32 位整数。
seac 的核心循环:
const seacs = font.seacs;
if (newMapping && SEAC_ANALYSIS_ENABLED && seacs?.length) {
const matrix = properties.fontMatrix || FONT_IDENTITY_MATRIX;
const charset = font.getCharset();
const seacMap = Object.create(null);
for (let glyphId in seacs) {
glyphId |= 0;
const seac = seacs[glyphId];
const baseGlyphName = StandardEncoding[seac[2]];
const accentGlyphName = StandardEncoding[seac[3]];
const baseGlyphId = charset.indexOf(baseGlyphName);
const accentGlyphId = charset.indexOf(accentGlyphName);
if (baseGlyphId < 0 || accentGlyphId < 0) {
continue;
}
const accentOffset = {
x: seac[0] * matrix[0] + seac[1] * matrix[2] + matrix[4],
y: seac[0] * matrix[1] + seac[1] * matrix[3] + matrix[5],
};seacs 的四元组来自 Type1 的 seac 指令:[asb, adx, bchar, achar],即重音的水平位移、基字形编码、重音字形编码。基字形与重音字形都用 StandardEncoding 查名,再在 charset 里查 glyph id。
偏移计算是一次完整的仿射变换:x 取矩阵第 0、2、4 项,y 取第 1、3、5 项。这样即使字体矩阵带旋转或倾斜,重音也能贴到正确位置。
只有「这个 glyph 原本就有字符码」时才建立 seac 映射:
const charCodes = getCharCodes(mapping, glyphId);
if (!charCodes) {
// There's no point in mapping it if the char code was never mapped
// to begin with.
continue;
}如果没有字符码,说明内容流里根本不会用到这个复合字形,为它建映射只是浪费码位。
hmtx 里的假 .notdef
(function fontTableHmtx() {
const charstrings = font.charstrings;
const cffWidths = font.cff?.widths ?? null;
const hmtx = new DataBuilder({ exactLength: numGlyphs * 4 });
// Fake .notdef (width=0 and lsb=0) first, skip redundant assignment.
hmtx.skip(4);
for (let i = 1, ii = numGlyphs; i < ii; i++) {
let width = 0;
if (charstrings) {
width = charstrings[i - 1].width || 0;
} else if (cffWidths) {
width = Math.ceil(cffWidths[i] || 0);
}
hmtx.setInt16(width);
hmtx.skip(2); // Use lsb=0, skip redundant assignment.
}
return hmtx.data;
})();第一项 4 字节保持为 0,代表 .notdef。循环从 1 开始,charstrings[i - 1] 是因为 Type1 的字符程序数组比 glyph id 少一位(.notdef 是插入的)。宽度用 Math.ceil 取整,因为 hmtx 只接受整数,而 CFF 的宽度可能是带小数的设计单位。
固定表头与度量来源
head、hhea、maxp 这三张表全部由 DataBuilder 手写:
const builder = new OpenTypeFileBuilder('\x4F\x54\x54\x4F');
// PostScript Font Program
builder.addTable('CFF ', font.data);
// OS/2 and Windows Specific metrics
builder.addTable('OS/2', createOS2Table(properties, newCharCodeToGlyphId));
// Character to glyphs mapping
builder.addTable('cmap', createCmapTable(newCharCodeToGlyphId, toUnicodeExtraMap, numGlyphs));版本标记 "\x4F\x54\x54\x4F" 就是 ASCII 的 OTTO,表示「这是一个带 CFF 轮廓的 OpenType 字体」。顺序上先放 CFF ,再放 OS/2 与 cmap,其余表随后追加。
hhea 里有一个容易看错的细节:
hhea.setSafeInt16(properties.capHeight); // caretSlopeRise
hhea.setSafeInt16(Math.tan(properties.italicAngle) * properties.xHeight); // caretSlopeRun仓库这一版把 capHeight 写到了 caretSlopeRise 的位置,把 tan(italicAngle) * xHeight 写到 caretSlopeRun。规范里这两个字段描述的是插入符斜率,与 capHeight 无关;这里更像是一个历史遗留的字段错位,而不是有意设计。注释仍然标着 caretSlopeRise,说明作者知道字段名,但赋值来源是字体度量。
hhea 的最后一个字段被写成字形总数:
hhea.setInt16(numGlyphs); // Number of HMetrics这等于宣称「每个字形都有完整度量」,与上面 hmtx 为每个字形都写 4 字节一致。
包装后的 ToUnicode 修正
if (properties.builtInEncoding) {
// For Type1 fonts that do not include either `ToUnicode` or `Encoding`
// data, attempt to use the `builtInEncoding` to improve text selection.
adjustType1ToUnicode(properties, properties.builtInEncoding);
}这一步必须在 convert 开头、adjustMapping 之前完成。原因很直接:adjustMapping 读 this.toUnicode 决定 toUnicodeExtraMap 的内容,如果此时 toUnicode 还没补全,补出来的 Unicode 就不会进入新的 cmap。
同样地,properties.fixedPitch = false 在开头被强制设置:
// TODO: Check the charstring widths to determine this.
properties.fixedPitch = false;Type1/CFF 的等宽属性没有被可靠解析,源码选择「一律当作非等宽」,让上层靠宽度表判断。这个 TODO 说明作者知道这里不精确。
CFFFont 与 Type1Font 的分界
两个类都不在 fonts.js 里,但构造函数的选择逻辑在本文件:
const cff =
subtype === 'Type1C' || subtype === 'CIDFontType0C'
? new CFFFont(file, properties)
: new Type1Font(name, file, properties);Type1Font 负责解密 eexec 段、解析 PostScript 字典、提取字符程序、把 Type1 轮廓转成 CFF。CFFFont 直接读 CFF 的 INDEX 结构、charset、encoding、私用字典。两者的共同输出是「字符程序 + seacs + charset + 宽度」,convert 只依赖这些公共接口,不关心具体实现。
CFFFont 还有一个额外能力:duplicateFirstGlyph。在 checkAndRepair 遇到「OTTO 外壳里其实是 CFF」的情况时,会先调用它把 glyph 0 复制到末尾,再用 CFFCompiler 重新编译:
if (parsedCff) {
try {
parsedCff.duplicateFirstGlyph();
tables['CFF '].data = new CFFCompiler(parsedCff).compile();
numGlyphsFromCFF = parsedCff.charStringCount;
} catch {
warn('Failed to compile font ' + properties.loadedName);
}
}这也是唯一一处「修复后会改变字形总数」的地方:numGlyphs 因此优先取 numGlyphsFromCFF,而不是 maxp 里的旧值。编译失败只警告,继续用原始 CFF 数据,后面仍按旧表结构处理。
设计要点:包装路线的核心假设是「浏览器能正确解析 CFF,但不认识 Type1 与裸 CFF 容器」。因此
convert只做容器转换与表补齐,绝不重写轮廓。这让 Type1/CFF 的渲染精度完全依赖浏览器自己的 CFF 解析器,也避免了在 Worker 里实现一套完整的轮廓解释器。
Type3 与字符过程
构造函数里的提前返回
Type3 在构造函数中只有十几行:
if (properties.type === 'Type3') {
for (let charCode = 0; charCode < 256; charCode++) {
this.toFontChar[charCode] = this.differences[charCode] || properties.defaultEncoding[charCode];
}
return;
}toFontChar 的值是字形名而不是码位。这是 Type3 与其它字体最本质的区别:其它字体的字形由字体程序定义,Type3 的字形由 /CharProcs 里同名的一段内容流定义。
循环固定到 256,因为 Type3 只支持单字节编码。/Differences 优先于 /Encoding,与简单字体的规则一致。
operatorListId 的来源
_charToGlyph 里有一段 Type3 专用分支:
if (this.isType3Font) {
// Font char code in this case is actually a glyph name.
operatorListId = fontCharCode;
}fontCharCode 来自 toFontChar,对 Type3 来说就是字形名。画布层拿到 operatorListId 之后,会在 charProcOperatorList 里查对应的 operatorList 并执行它,而不是调用 fillText。
这段赋值在 fontChar 生成之前,因此 Type3 的 fontCharCode 仍是字符串,不会被 String.fromCodePoint 处理。源码在生成 fontChar 时判断 typeof fontCharCode === "number",字符串直接跳过,fontChar 保持为空串。Type3 的绘制完全靠 operatorListId,fontChar 为空是正确的。
字符过程的编译
charProcOperatorList 不在 fonts.js 里构建,而在 evaluator.js 的 TranslatedFont.loadType3Data 里:
const charProcs = dict.get("CharProcs");
const fontResources = dict.get("Resources") || resources;
const charProcOperatorList = new Map();
const [x0, y0, x1, y1] = font.bbox;
const fontBBoxSize = Math.hypot(x1 - x0, y1 - y0);
for (const key of charProcs.getKeys()) {每个字符过程都被当作一段普通内容流求值,得到一个 OperatorList,再取它的 IR(中间表示)存进 Map。这段代码与普通页面的求值共用同一条路径,因此 Type3 字形里可以出现任何绘图操作,包括嵌套的文本、图像、颜色。
fontBBoxSize 是包围盒对角线长度,用来决定是否需要「猜」缺失的 d1 参数。相关逻辑在 #guessType3FontBBox,本节不展开。
d0 与 d1 的差别
规范要求字符过程以 d0 或 d1 开头,两者都声明字形宽度,d1 还额外声明包围盒:
switch (operatorList.fnArray[0]) {
case OPS.setCharWidthAndBounds:
this.#removeType3ColorOperators(operatorList, fontBBoxSize);
break;
case OPS.setCharWidth:
if (!fontBBoxSize) {
this.#guessType3FontBBox(operatorList);
}
break;
}OPS.setCharWidth 对应 d0,OPS.setCharWidthAndBounds 对应 d1。d1 的包围盒会被写回 font.bbox 并置 isCharBBox = true,画布层据此裁剪。
规范还规定:以 d1 开头的字符过程不应该执行任何设置颜色的操作,这些操作必须被忽略。#removeType3ColorOperators 就是执行这条规则,把颜色相关的算子从 IR 里剔除。
单个字符过程失败时的降级
} catch {
warn(`Type3 font resource "${key}" is not available.`);
charProcOperatorList.set(key, new OperatorList().getIR());
}某个字符过程解析失败时,不抛错,而是放入一个空 operatorList。这样这个字形画不出来,但其它字形正常。对比普通页面的求值,Type3 使用 evaluator.clone({ ignoreErrors: false })——单个字形内部错误不容忍,因为「半个字形」没有意义;但字形与字形之间彼此隔离。
fontMatrix 与 bbox 的角色
Type3 的 /FontMatrix 是必填项,而且通常不是默认的 [0.001, 0, 0, 0.001, 0, 0]。它定义了「字形空间」到「文本空间」的变换。构造函数原样保留它,并且在 Type3 分支提前返回,因此 adjustWidths 根本不会执行——Type3 的宽度本来就定义在自己的字形空间里。
bbox 对 Type3 尤其重要:它是默认包围盒,当字符过程用 d0 而不给包围盒时,画布层需要一个范围来裁剪。源码在 loadType3Data 结束时会用实际求值得到的 _bbox 覆盖它。
设计要点:Type3 把「字形」从数据变成了程序。
Font对此的处理是只保留身份信息(字形名、编码、宽度、矩阵、包围盒),把执行交给求值器与画布层。这条分界线让 Type3 可以复用普通内容流的全部能力,也让fonts.js不必理解任何绘图算子。
宽度、度量与空格
widths 与 defaultWidth 的来源
properties.widths 由求值器的 extractWidths 组装,Font 只是接收者。简单字体按字符码索引,复合字体按 CID 索引;没有 /Widths 时,求值器会尝试用标准字体度量或 BaseFont 的度量填充:
const missingWidth = descriptor.get("MissingWidth");
defaultWidth = typeof missingWidth === "number" ? missingWidth : 0;
} else {
// Trying get the BaseFont metrics (see comment above).
const baseFontName = dict.get("BaseFont");
if (baseFontName instanceof Name) {
const metrics = this.getBaseFontMetrics(baseFontName.name);
glyphsWidths = this.buildCharCodeToWidth(metrics.widths, properties);
defaultWidth = metrics.defaultWidth;
}
}这段在 evaluator.js 里,但它解释了为什么 Font 拿到宽度时可以直接信任:优先级已经是「字体字典 /Widths → /MissingWidth → 标准字体度量」。Font 再往下只有一步——查不到就退回 defaultWidth。
adjustWidths 只在非标准字体矩阵时生效:
function adjustWidths(properties) {
if (!properties.fontMatrix) {
return;
}
if (properties.fontMatrix[0] === FONT_IDENTITY_MATRIX[0]) {
return;
}
// adjusting width to fontMatrix scale
const scale = 0.001 / properties.fontMatrix[0];
const glyphsWidths = properties.widths;
for (const glyph in glyphsWidths) {
glyphsWidths[glyph] *= scale;
}
properties.defaultWidth *= scale;
}它同时修改 defaultWidth,因此构造函数末尾必须重新读取 properties.defaultWidth。如果只缩放 widths 而漏掉默认值,缺宽度的字符就会突然变宽或变窄。
宽度码与字符码不是一回事
_charToGlyph 里这三行是宽度计算的全部:
width = this.widths[widthCode];
if (typeof width !== 'number') {
width = this.defaultWidth;
}
const vmetric = this.vmetrics?.[widthCode] || this.defaultVMetrics;注意 typeof width !== "number",而不是 if (!width)。宽度为 0 是合法值(不可见字符、零宽连接符),用真假判断会把它替换成默认宽度,导致文本错位。
vmetrics 与 defaultVMetrics 是竖排字体的垂直度量。defaultVMetrics 由求值器在 /W2、/DW2 缺失时构造:
defaultVMetrics = [vmetrics[1], defaultWidth * 0.5, vmetrics[0]];这三个值分别是 w1y、vx、wy。vx 取默认宽度的一半,是「竖排字形大致居中」的近似。
_spaceWidth 的三级猜测
空格宽度在很多字体里缺失,因为它通常没有独立字形。私有 getter 做了一次逐级尝试:
get _spaceWidth() {
// trying to estimate space character width
const possibleSpaceReplacements = ["space", "minus", "one", "i", "I"];
let width;
for (const glyphName of possibleSpaceReplacements) {
// if possible, getting width by glyph name
if (glyphName in this.widths) {
width = this.widths[glyphName];
break;
}
const glyphsUnicodeMap = getGlyphsUnicode();
const glyphUnicode = glyphsUnicodeMap[glyphName];
// finding the charcode via unicodeToCID map
let charcode = 0;
if (this.composite && this.cMap.contains(glyphUnicode)) {
charcode = this.cMap.lookup(glyphUnicode);
if (typeof charcode === "string") {
charcode = convertCidString(glyphUnicode, charcode);
}
}
// ... via toUnicode map
if (!charcode && this.toUnicode) {
charcode = this.toUnicode.charCodeOf(glyphUnicode);
}
// setting it to unicode if negative or undefined
if (charcode <= 0) {
charcode = glyphUnicode;
}
// trying to get width via charcode
width = this.widths[charcode];
if (width) {
break; // the non-zero width found
}
}
return shadow(this, "_spaceWidth", width || this.defaultWidth);
}候选列表 space、minus、one、i、I 是按「宽度接近空格的常见字形」排序的。真正的 space 在复合字体里未必有独立 CID,因此退到 minus、one、i、I。
每一轮都做三次解析:先看 widths 里有没有以字形名为键的项(少见,但某些内部字体会这样),再用 CMap 把 Unicode 查成 CID,再用 toUnicode.charCodeOf 反查字符码,最后用字符码查宽度。三条路都失败才换下一个候选。
shadow 把结果固化到实例上。这个 getter 会被 _charToGlyph 在缺失字体路径里调用,而 _charToGlyph 本身是热路径,因此只算一次。
度量字段的三种来源
同一个 ascent 可能来自三个地方,优先级如下:
| 来源 | 字段 | 何时使用 |
|---|---|---|
| CSS 字体信息 | cssFontInfo.metrics | XFA 等按 CSS 排版的场景 |
字体程序的 head/hhea | unitsPerEm、ascent、descent | 有嵌入字体且表可读时 |
| PDF 字体描述符 | /Ascent、/Descent、/CapHeight | 无嵌入字体,或字体程序表缺失时 |
构造函数一开始用第三种(除以 1000),checkAndRepair 成功后用第二种(除以 unitsPerEm)覆盖。fallbackToSystemFont 只在字段是 NaN 时才用标准字体度量填充,避免覆盖已经有效的描述符值:
if (metrics) {
if (isNaN(this.ascent)) {
this.ascent = metrics.ascent / PDF_GLYPH_SPACE_UNITS;
}
if (isNaN(this.descent)) {
this.descent = metrics.descent / PDF_GLYPH_SPACE_UNITS;
}
if (isNaN(this.capHeight)) {
this.capHeight = metrics.capHeight / PDF_GLYPH_SPACE_UNITS;
}
}isNaN 判断而不是 undefined 判断,是因为描述符里可能出现 NaN:求值器在字段缺失或非数字时会留下 NaN 作为「未知」标记。
encodeString:把 Unicode 反编回字符码
文本层与表单需要「给定一段 JS 字符串,产回 PDF 字符码」。encodeString 就是反向映射:
encodeString(str) {
const buffers = [];
const currentBuf = [];
// buffers will contain: encoded, non-encoded, encoded, ...
// currentBuf is pushed in buffers each time there is a change.
// So when buffers.length is odd then the last string is an encoded one
// and currentBuf contains non-encoded chars.
const hasCurrentBufErrors = () => buffers.length % 2 === 1;
const getCharCode =
this.toUnicode instanceof IdentityToUnicodeMap
? unicode => this.toUnicode.charCodeOf(unicode)
: unicode => this.toUnicode.charCodeOf(String.fromCodePoint(unicode));返回的数组是交错的:偶数下标是「已编码段」,奇数下标是「无法编码的原文段」。调用方(画布层的 measureText、表单的默认值写入)可以分别处理两段。
for (let i = 0, ii = str.length; i < ii; i++) {
const unicode = str.codePointAt(i);
if (unicode > 0xffff) {
// unicode is represented by two uint16
i++;
}增补平面字符占两个 UTF-16 码元,i++ 跳过后半个。真正能编码时,字符码按 this.cMap.getCharCodeLength(charCode) 决定字节数,并从高字节到低字节写入 currentBuf,保证多字节 CMap 的字节序正确;charCodeOf 返回 -1 表示这个 Unicode 在字体里不存在,此时原文进入「无法编码」段。
度量的一致性如何保证
宽度、度量、行高三者必须互相自洽,否则文本层会出现「选中范围与字形不对齐」。源码用两条规则保证:
- 宽度与度量都以「相对字身」为单位,千分之一或
unitsPerEm归一化,绝不混用设计单位; lineHeight在最后一次覆盖之后才计算,且lineGap与lineHeight要么都来自 CSS,要么都来自hhea。
这也是为什么构造函数要在 checkAndRepair 之后重新读取 properties.fontMatrix、widths、defaultWidth:修复过程可能同时改了这三者,只更新一部分就会破坏一致性。
设计要点:宽度查询里「查不到」与「宽度为 0」被严格区分。
typeof width !== "number"保留零宽字符的真实宽度,width || this.defaultWidth则只用于「完全没找到」。这类判断看似琐碎,却决定了复杂排版(零宽连接、组合重音、竖排标点)能不能正确对齐。
系统字体回退与导出
什么时候回退
四条路会走到 fallbackToSystemFont:文件为空、类型不支持、修复抛错、/FontFile 压根不存在。回退不是「画出差不多的字」,而是「用浏览器已有的字体 + 正确的字符映射」尽量还原。
名字归一化与标准字体替换
fallbackToSystemFont(properties) {
this.missingFile = true;
// The file data is not specified. Trying to fix the font name
// to be used with the canvas.font.
const { name, type } = this;
let fontName = normalizeFontName(name);
const stdFontMap = getStdFontMap(),
nonStdFontMap = getNonStdFontMap();
const isStandardFont = !!stdFontMap[fontName];
const isMappedToStandardFont = !!(
nonStdFontMap[fontName] && stdFontMap[nonStdFontMap[fontName]]
);
fontName = stdFontMap[fontName] || nonStdFontMap[fontName] || fontName;normalizeFontName 去掉子集前缀与空白,把名字折成大写无空格的规范形式。stdFontMap 是「PDF 标准字体名 → 标准 14 字体」的映射,例如 Arial 映射到 Helvetica;nonStdFontMap 处理更多别名。isMappedToStandardFont 要求「别名先映射到某个名字,那个名字本身又在标准表里」,用来识别「伪装成非标准字体的标准字体」。
bold、italic、black、narrow 四个样式位直接用正则从名字推断:
this.bold = /bold/i.test(fontName);
this.italic = /oblique|italic/i.test(fontName);
// Use 'name' instead of 'fontName' here because the original
// name ArialBlack for example will be replaced by Helvetica.
this.black = /Black/.test(name);
// Use 'name' instead of 'fontName' here because the original
// name ArialNarrow for example will be replaced by Helvetica.
const isNarrow = /Narrow/.test(name);bold 与 italic 用替换后的 fontName,因为标准字体名本身就带 Bold、Italic 后缀;black 与 narrow 必须用原始 name,因为 ArialBlack 会被替换成 Helvetica,替换后就丢失了「黑体」信息。这两行注释把原因写得很清楚。
remeasure:什么时候需要重新量宽
// if at least one width is present, remeasure all chars when exists
this.remeasure = (!isStandardFont || isNarrow) && Object.keys(this.widths).length > 0;remeasure 表示「画布层必须用 measureText 重新量每个字符,不能相信 PDF 里的宽度」。触发条件是「非标准字体或窄体」且「至少有一个宽度」。标准字体且非窄体时,PDF 宽度与浏览器字体的度量高度一致,可以直接使用;一旦换了字体族或压缩了字宽,PDF 宽度就会与浏览器不一致。
复合字体的标准字形映射
标准字体有时被嵌入成 CID 字体,且没有 /CIDToGIDMap。这时需要用「标准字体的 glyph 顺序表」重建映射:
if (
(isStandardFont || isMappedToStandardFont) &&
type === "CIDFontType2" &&
this.cidEncoding.startsWith("Identity-")
) {
const cidToGidMap = properties.cidToGidMap;
// Standard fonts might be embedded as CID font without glyph mapping.
// Building one based on GlyphMapForStandardFonts.
const map = [];
if (/Trebuchet/i.test(name)) {
// TrebuchetMS doesn't share the glyph ordering of the standard fonts,
// hence using the latter would map e.g. "š" to "ž" (issue 21713).
applyStandardFontGlyphMap(map, getGlyphMapForMacOrderedFonts());
applyStandardFontGlyphMap(map, getSupplementalGlyphMapForTrebuchetMS());
} else {
applyStandardFontGlyphMap(map, getGlyphMapForStandardFonts());
if (/Arial-?Black/i.test(name)) {
applyStandardFontGlyphMap(
map,
getSupplementalGlyphMapForArialBlack()
);
} else if (/Calibri/i.test(name)) {
applyStandardFontGlyphMap(map, getSupplementalGlyphMapForCalibri());
}
}getGlyphMapForStandardFonts 是「标准 14 字体的字符码 → 字形序号」表。applyStandardFontGlyphMap 把这张表叠加到 map 上,遇到重复键时后写覆盖。Trebuchet、ArialBlack、Calibri 各有补充表,因为它们的字形顺序与标准字体不同。
这段还处理了「/CIDToGIDMap 不完整」的情况:
// When the /CIDToGIDMap is "incomplete", fallback to the included
// /ToUnicode-map regardless of its encoding (fixes issue11915.pdf).
if (
cidToGidMap.length !== this.toUnicode.length &&
properties.hasIncludedToUnicodeMap &&
this.toUnicode instanceof IdentityToUnicodeMap
) {
this.toUnicode.forEach(function (charCode, unicodeCharCode) {
const cid = map[charCode];
if (cidToGidMap[cid] === undefined) {
map[+charCode] = unicodeCharCode;
}
});
}长度不一致说明映射不完整;此时用 /ToUnicode 补上没有映射的项。条件里要求 IdentityToUnicodeMap,是因为只有恒等映射的 forEach 才能安全遍历全部 CID 而不依赖稀疏数组。
符号字体与 Dingbats
} else if (/Symbol/i.test(fontName)) {
// The non-embedded SymbolMT font in issue 21523 uses Identity encoding
// and an Identity CIDToGIDMap, hence its CIDs are glyph ids.
const isCidKeyed =
this.composite && this.cidEncoding.startsWith("Identity-");
this.toFontChar = buildToFontChar(
isCidKeyed ? getSymbolGlyphIdEncoding() : SymbolSetEncoding,
getGlyphsUnicode(),
this.differences
);
} else if (/Dingbats/i.test(fontName)) {
this.toFontChar = buildToFontChar(
ZapfDingbatsEncoding,
getDingbatsGlyphsUnicode(),
this.differences
);符号字体的字符码不是 Unicode,而是一套私有编码。SymbolSetEncoding 把 256 个码位映射到字形名,再由 getGlyphsUnicode 换成 Unicode。isCidKeyed 分支是给「Identity 编码 + Identity CIDToGIDMap」的 SymbolMT 用的,此时 CID 本身就是 glyph id,需要用另一张编码表。
Dingbats 用 ZapfDingbatsEncoding 与 getDingbatsGlyphsUnicode,因为它的字形名(如 a20)与普通字形名空间不同。
通用分支与 Tahoma/Verdana 补丁
} else {
const glyphsUnicodeMap = getGlyphsUnicode();
const map = [];
this.toUnicode.forEach((charCode, unicodeCharCode) => {
if (!this.composite) {
const glyphName =
this.differences[charCode] || this.defaultEncoding[charCode];
const unicode = getUnicodeForGlyph(glyphName, glyphsUnicodeMap);
if (unicode !== -1) {
unicodeCharCode = unicode;
}
}
map[+charCode] = unicodeCharCode;
});
// Attempt to improve the glyph mapping for (some) composite fonts that
// appear to lack meaningful ToUnicode data.
if (this.composite && this.toUnicode instanceof IdentityToUnicodeMap) {
if (/Tahoma|Verdana/i.test(name)) {
// Fixes issue15719.pdf and issue11242_reduced.pdf.
applyStandardFontGlyphMap(map, getGlyphMapForStandardFonts());
}
}
this.toFontChar = map;
}通用分支直接把 toUnicode 复制成 toFontChar;简单字体额外用「字形名 → Unicode」修正一次,因为 toUnicode 可能来自不精确的内嵌编码。
Tahoma 与 Verdana 的补丁针对一个具体现象:这两款字体的复合字体版本常常只有恒等映射,导致 glyph 顺序被当作 Unicode,文本层显示成乱码。用标准字形表覆盖之后,至少能恢复到正确的字形。
loadedName 的重写
amendFallbackToUnicode(properties);
this.loadedName = fontName.split('-', 1)[0];回退结束后,loadedName 被改成「归一化字体名的第一段」。原来是 docId_fontId,现在变成 Helvetica、TimesNewRoman 这样的真实字体名。原因是回退字体没有嵌入数据,主线程不需要按 loadedName 去 commonobj 里取字体字节,而是直接用 CSS 字体族;同时 loadedName 也是调试与 font-substitution 的键。
loadedName 仍可能重复:同名字体在同一文档里出现多次时,它们的 loadedName 会相同。这在回退路径里可以接受,因为没有字体数据需要区分。
exportData:把字段压成二进制
主线程不能直接接收 Font 实例,因此 exportData 把字段分成三份:
exportData() {
return {
buffer: compileFontInfo(this.#getExportData(EXPORT_DATA_PROPERTIES)),
charProcOperatorList: this.charProcOperatorList,
extra: this.fontExtraProperties
? this.#getExportData(EXPORT_DATA_EXTRA_PROPERTIES)
: undefined,
};
}compileFontInfo 来自 obj_bin_transform_core.js,把普通字段按固定顺序写成字节;charProcOperatorList 是 Map,不适合塞进这条二进制流,因此单独传输;extra 只在 fontExtraProperties 开启时携带调试字段。#getExportData 遍历字段表时跳过值为 undefined 的项,因此同一份导出格式能服务多种字体:Type3 没有 data 与 mimetype,回退字体没有 charProcOperatorList,但它们仍然能被主线程正确还原。
EXPORT_DATA_PROPERTIES 里有一项值得注意:data 是完整的 OpenType 字节。它被放在「基础字段」而不是 extra 里,因为它不是调试信息,而是 FontFace 的来源。toUnicode、widths、vmetrics 反而在 extra 里,因为只有文本层与竖排布局需要它们。
ErrorFont:最后的兜底
class ErrorFont {
constructor(error) {
this.error = error;
this.loadedName = 'g_font_error';
this.missingFile = true;
}
charsToGlyphs() {
return [];
}
encodeString(chars) {
return [chars];
}
exportData() {
return { error: this.error };
}
}ErrorFont 实现了与 Font 相同的最低接口,因此求值器不需要为「字体彻底失败」写分支。charsToGlyphs 返回空数组,文本层什么也画不出来;encodeString 原样返回,表单写入不会崩;exportData 只带错误信息,主线程据此在控制台报错。
loadedName 固定为 g_font_error,所有错误字体共享同一个 CSS 类。missingFile 为 true,让画布层知道不需要等待字体装载。
设计要点:回退路径的目标不是「还原原始字体」,而是「让文本仍然可读、可选中、可复制」。因此它优先保证三件事:字符码到 Unicode 的映射正确、宽度可被重新测量、
loadedName能被 CSS 直接使用。字形外观的差异被接受,因为原字体数据已经不存在了。
总结
fonts.js 在整条链路里承担「字体数据 → 可查询接口 + 可装载字节」的转换:
| 阶段 | 入口 | 产出 |
|---|---|---|
| 类型判定 | getFontFileType | 真实 type 与 subtype |
| 字体程序修复 | checkAndRepair | 重建后的 OpenType 字节、missingGlyphs |
| 字体程序包装 | convert | 带 CFF 表的 OpenType 字节、seacMap |
| 映射构建 | adjustMapping、buildToFontChar | toFontChar、新的 cmap |
| 字符查询 | _charToGlyph、charsToGlyphs | Glyph 与两级缓存 |
| 导出 | exportData | compileFontInfo 字节、charProcOperatorList |
| 兜底 | fallbackToSystemFont、ErrorFont | 系统字体元数据或错误标记 |
一次完整的调用链可以写成:
// PartialEvaluator: 读取字体字典与 /FontFile*
// → getFontFileType 判定真实类型
// → checkAndRepair / convert 修复或包装
// → adjustMapping 码位搬进私有区
// → createCmapTable / createOS2Table / createNameTable
// → Font.charsToGlyphs 内容流字符串 → Glyph 数组
// → _charToGlyph Glyph 缓存
// → Font.renderer FontRendererFactory 编译轮廓
// → exportData compileFontInfo + charProcOperatorList
// → TranslatedFont.send → FontFaceObject → canvas.js 绘制六条可以带走的原则:
- 文件头优先于字典声明。
getFontFileType读魔数,不迷信/Subtype;maxp版本用表长度反推,indexToLocFormat用loca长度反推。结构自证比字段自述可靠。 - 码位必须搬进私有区。
adjustMapping让浏览器把字形当作普通图形处理,避开 Unicode 区域的语言相关行为;代价是同时维护toFontChar、toUnicode与toUnicodeExtraMap三份信息。 - 修复优先,降级兜底。表坏了重读、字形坏了清零、指令坏了删除、连
glyf全空都造占位字形;修不好就回退系统字体,回退也失败才用ErrorFont。 - 度量以字体程序为准。
hhea的 ascent、descent、lineGap 覆盖 PDF 描述符;只有无嵌入字体时才退回描述符与标准字体度量,且只在字段为NaN时填充。 - 查询结果只读并驻留。
Glyph一旦进入#glyphCache就不再变化,#charsCache直接复用整串结果;glyphCacheValues只暴露迭代器,防止外部破坏缓存。 - 分层边界清晰。
fonts.js不解析轮廓(交给glyf.js、CFFFont、浏览器),不执行 Type3 字符过程(交给求值器与画布层),只负责「身份、映射、度量、容器」。
StreamPDF 的设计原则: 能前置处理的绝对不放到解析的时候才做, 由服务端一次解决所有性能问题. 浏览器只获取&渲染必须数据.
相关文章
- PDF.js 从 demo 深入浅出 10: CanvasGraphics 与 operatorList 绘制2026年10月27日
- PDF.js 从 demo 深入浅出 9: 网络流与 Range 请求2026年10月27日
- PDF.js 从 demo 深入浅出 8: PDFWorker.create 与真假 Worker 握手2026年10月27日
- PDF.js 从 demo 深入浅出 7: WorkerTransport 初始化2026年10月27日
- PDF.js 从 demo 深入浅出 6: MessageHandler 跨线程通讯2026年10月27日
- PDF.js 从 demo 深入浅出 5: render 方法全貌2026年10月27日
- PDF.js 从 demo 深入浅出 4: getViewport 方法全貌2026年10月27日
- PDF.js 从 demo 深入浅出 3: getPage 方法全貌2026年10月27日
- PDF.js 从 demo 深入浅出 2: getDocument 方法全貌2026年10月27日
- PDF.js 源码解读: TextLayer2026年10月27日
- PDF.js 源码解读: font_loader2026年10月27日
- PDF.js 源码解读: obj_bin_transform_display2026年10月27日
- PDF.js 源码解读: PDFObjects2026年10月27日
- PDF.js 源码解读: 网络流2026年10月27日
- PDF.js 源码解读: internal_evt.js2026年10月27日
- PDF.js 源码解读: math_clamp.js2026年10月27日
- PDF.js 源码解读: css_utils.js2026年10月27日
- PDF.js 源码解读: scripting_utils2026年10月27日
- PDF.js 源码解读: MurmurHash3_642026年10月27日
- PDF.js 源码解读: obj_bin_transform_utils2026年10月27日
- PDF.js 源码解读: image_utils.js2026年10月27日
- PDF.js 源码解读: BasePDFStream2026年10月27日
- PDF.js 源码解读: 共享工具层2026年10月27日
- PDF.js 源码解读: MessageHandler2026年10月27日
- PDF.js 源码解读: api2026年10月27日
- PDF.js 源码解读: glyphlist2026年10月27日
- PDF.js 源码解读: binary_cmap2026年10月27日
- PDF.js 源码解读: cmap2026年10月27日
- PDF.js 源码解读: encodings2026年10月27日
- PDF.js 源码解读: metrics2026年10月27日
- PDF.js 源码解读: standard_fonts2026年10月27日
- PDF.js 源码解读: fonts_utils2026年10月27日
- PDF.js 源码解读: default_appearance2026年10月27日
- PDF.js 源码解读: metadata_parser2026年10月27日
- PDF.js 源码解读: name_number_tree2026年10月27日
- PDF.js 源码解读: struct_tree2026年10月27日
- PDF.js 源码解读: catalog2026年10月27日
- PDF.js 源码解读: pdf_manager2026年10月27日
- PDF.js 源码解读: object_loader2026年10月27日
- PDF.js 源码解读: obj_bin_transform_core2026年10月27日
- PDF.js 源码解读: crypto2026年10月27日
- PDF.js 源码解读: core_utils2026年10月27日
- PDF.js 源码解读: primitives2026年10月27日
- PDF.js 源码解读: worker_stream2026年10月27日
- PDF.js 源码解读: ccitt_stream2026年10月27日
- PDF.js 源码解读: jpx_stream2026年10月27日
- PDF.js 源码解读: jbig2_stream2026年10月27日
- PDF.js 源码解读: jpeg_stream2026年10月27日
- PDF.js 源码解读: decrypt_stream2026年10月27日
- PDF.js 源码解读: brotli_stream2026年10月27日
- PDF.js 源码解读: run_length_stream2026年10月27日
- PDF.js 源码解读: ascii_hex_stream2026年10月27日
- PDF.js 源码解读: ascii_85_stream2026年10月27日
- PDF.js 源码解读: lzw_stream2026年10月27日
- PDF.js 源码解读: predictor_stream2026年10月27日
- PDF.js 源码解读: flate_stream2026年10月27日
- PDF.js 源码解读: decode_stream2026年10月27日
- PDF.js 源码解读: chunked_stream2026年10月27日
- PDF.js 源码解读: stream2026年10月27日
- PDF.js 源码解读: base_stream2026年10月27日
- PDF.js 深入浅出 11: Parser2026年10月26日
- PDF.js 深入浅出 10: XRef2026年10月26日
- PDF.js 深入浅出 9: CanvasGraphics2026年10月26日
- PDF.js 深入浅出 8: Document 与 Page2026年10月26日
- AI 时代, 我们到底应该做什么才能活下去(StreamPDF 创立有感)2026年10月26日
- PDF.js 深入浅出 7: PartialEvaluator2026年10月25日
- PDF.js 深入浅出 6: PDFManager.initDocument2026年10月25日
- PDF.js 深入浅出 5: PDFFetchStream 和 PDFWorkerStream2026年10月25日
- PDF.js 深入浅出 4: MessageHandler2026年10月22日
- PDF.js 深入浅出 3: getViewport & render2026年10月22日
- PDF.js 从 demo 深入浅出 1: 自定义 viewer 渲染 PDF2026年10月19日
- PDF.js 深入浅出 2: getDocument & getPage2026年10月19日
- PDF.js 深入浅出 1: PDF.js 的架构设计2026年10月16日