@yudaocode/univer-pdfs 1.6.214 → 1.6.215

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -80,20 +80,24 @@ export interface IPdfBrowserRenderOptions {
80
80
 
81
81
  ## 3. 中文字体加载、回退顺序、缺字诊断与粗斜体约定(F1–F6)
82
82
 
83
- 1. **宿主提供字体,上游零捆绑(F1、F2)**:
84
- - 包内不捆绑任何中文字体文件;宿主通过 `render.fonts` 传入 `bytes` 或 `url`(可选附带 `integrity` 摘要校验),仅支持标准轮廓 TrueType(`.ttf`,含 `glyf`/`loca`/`cmap` 表)。
83
+ 1. **宿主提供字体与可选字库包辅助函数(F1、F2)**:
84
+ - 运行时包内不捆绑任何中文字体文件,也不在 `dependencies` 中引入字库依赖;常规安装与非 PDF 功能零字库下载。
85
+ - 宿主可直接传入自托管 `render.fonts`,或调用纯辅助函数 `createPdfCjkFontSources({ version, baseUrl, weights, family, integrity })`(浏览器入口亦挂载为 `io.createCjkFontSources`)生成指向独立开放许可字库包 `@yudaocode/univer-pdf-fonts`(默认固定版本 `1.0.0`,`SIL Open Font License 1.1` 静态 TrueType `NotoSansSC-Regular.ttf` / `NotoSansSC-Bold.ttf`,自带 `sha384` SRI)或宿主自定义 `baseUrl` 的标准 `IPdfFontSource[]` 条目,并仅请求所需字重(默认 `weights: 'normal'`,仅请求常规体;同时传入常规与粗体时,仅当文档存在粗体文本才请求粗体文件)。
85
86
  - 启用 `subset-ttf` 时,按文档实际用到的 Unicode 码位提取子集并写入 `Type0` + `CIDFontType2` + 内嵌 `FontFile2` + `ToUnicode` 映射表;中文、西文、数字与全角标点统一走同一套矢量字形度量,文字可选中、可搜索、可复制,不产生文本 PNG 位图。
86
- 2. **明确回退顺序与失败错误码(F3、F4)**:
87
- - 常规字重候选字体(`weight !== 'bold'`)按 `fonts[0] -> fonts[1] -> ...` 顺序依次尝试加载与解析;任一候选成功即采用该字体。
88
- - 若所有候选字体均失败(网络异常、HTTP 非 2xx、`integrity` 校验不匹配、空字节、损坏文件或非 TrueType `glyf` 格式如 CFF `.otf` / `.ttc`):
89
- - 默认 `fallback: 'error'`:**立即抛出 `PdfRenderError`**,`err.code === 'FONT_UNAVAILABLE'`,`err.failedFonts` 列出每一个失败候选字体的索引、`family`、`url` 与具体原因,绝不静默改变输出模式。
90
- - 仅当宿主显式设置 `fallback: 'raster-hd'` 或 `fallback: 'cid-vector'` 时,才切换至指定后备模式,并通过 `onWarning` 发出 `code: 'FONT_FALLBACK_ACTIVATED'` 警告。
87
+ 2. **显式 `render.fonts` 严格隔离与失败错误码(F3、F4)**:
88
+ - 当宿主显式传入 `render.fonts` 时:
89
+ - 候选字体按数组顺序依次尝试加载与解析,任一候选成功即使用该字体;
90
+ - **绝不回退读取** `customFontBytes` 或快照内嵌的 `resourceBindings` 字体资源;
91
+ - 所需字重的候选全部失败(网络异常、HTTP 非 2xx、`integrity` 校验不匹配、空字节、损坏文件或非 TrueType `glyf` 格式)时,默认 `fallback: 'error'` **立即抛出 `PdfRenderError`**(`err.code === 'FONT_UNAVAILABLE'`,`err.failedFonts` 列出每个候选的索引、`family`、`weight`、`url` 与具体原因),不静默改用其他输出方式。
92
+ - 未显式传入 `render.fonts` 时,保持原有行为不变。
91
93
  3. **缺字诊断(F5)**:
92
- - 在 `subset-ttf` 下,生成前扫描全部页面可见文本与表格单元格(含数值/货币/百分比格式化后的符号),对比所选字体 `cmap`:
93
- - 若存在字体未收录的码位(如生僻字、Emoji),按 `(pageId, elementId)` 聚合缺失字符数组 `chars` 与码位列表 `codePoints`(如 `'U+9F98'`、`'U+1F680'`)。
94
- - `missingGlyph: 'error'`:抛出 `PdfRenderError`(`err.code === 'MISSING_GLYPH'`,`err.missingGlyphs` 含完整定位明细)。
95
- - `missingGlyph: 'warn'`(默认):逐元素调用 `onWarning({ code: 'MISSING_GLYPH', pageId, elementId, details })` 明确告警,不静默输出无提示 `.notdef` 方框。
96
- 4. **粗体与斜体实现方式(F6)**:
94
+ - 在 `subset-ttf` 下,生成前扫描全部页面可见文本与表格单元格(含数值/货币/百分比格式化后的符号),对比所选字体 `cmap`,按 `(pageId, elementId)` 聚合缺失字符数组 `chars` 与码位列表 `codePoints`(如 `'U+9F98'`、`'U+1F680'`):
95
+ - **显式传入 `render.fonts` 时默认 `missingGlyph: 'error'`**(未显式传入 `render.fonts` 时默认 `'warn'`):抛出 `PdfRenderError`(`err.code === 'MISSING_GLYPH'`,`err.message` 与 `err.missingGlyphs` 均定位到具体页面、元素与码位)。
96
+ - 显式传 `missingGlyph: 'warn'` 时:逐元素调用 `onWarning({ code: 'MISSING_GLYPH', pageId, elementId, details })` 明确告警。
97
+ 4. **免字库 `cid-vector` 与 CMap 失败诊断**:
98
+ - `cid-vector` 默认不启用,仅在显式指定 `cjkTextMode: 'cid-vector'` 时输出未嵌入轮廓的 `STSong-Light` + `/UniGB-UTF16-H` + `/ToUnicode` CMap 流,内容流 `Tj` 不写入前导 UTF-16BE BOM(`FEFF`),确保 PDFBox 与 PDF.js 提取文本无替代字符。
99
+ - 浏览器查看器与底图渲染器通过受控 `CMapReaderFactory` 监控 `.bcmap` 加载;一旦 CMap 拉取失败立即抛出 `BrowserPdfRuntimeError('CMAP_LOAD_FAILED')`,避免静默渲染空白。
100
+ 5. **粗体与斜体实现方式(F6)**:
97
101
  - **粗体(`fontWeight: 'bold'`)**:若 `render.fonts` 中同时提供了可用的 `weight: 'bold'` TrueType 字体文件,则单独子集嵌入第二套粗体 `Type0` 字体并使用真实粗体字形;若未提供独立粗体字库,则采用 PDF 内容流描边加粗模拟(`2 Tr` 填充并描边,线宽 `fontSize * 0.032`)。
98
102
  - **斜体(`italic: true`)**:矢量路径统一采用 PDF 文本仿射倾斜矩阵(`[1, 0, 0.2126, 1, x, y] Tm`,约 `12°` 斜切)模拟。
99
103
 
package/lib/cjs/index.js CHANGED
@@ -52,6 +52,10 @@ __export(src_exports, {
52
52
  Barcode: () => Barcode,
53
53
  Box: () => Box,
54
54
  CIRCLE_MARK_BEZIER_KAPPA: () => CIRCLE_MARK_BEZIER_KAPPA,
55
+ DEFAULT_PDF_CJK_FONT_FAMILY: () => DEFAULT_PDF_CJK_FONT_FAMILY,
56
+ DEFAULT_PDF_CJK_FONT_FILES: () => DEFAULT_PDF_CJK_FONT_FILES,
57
+ DEFAULT_PDF_CJK_FONT_PACKAGE: () => DEFAULT_PDF_CJK_FONT_PACKAGE,
58
+ DEFAULT_PDF_CJK_FONT_VERSION: () => DEFAULT_PDF_CJK_FONT_VERSION,
55
59
  DeleteSelectedPdfElementsCommand: () => DeleteSelectedPdfElementsCommand,
56
60
  DistributeSelectedPdfElementsCommand: () => DistributeSelectedPdfElementsCommand,
57
61
  Document: () => Document,
@@ -172,6 +176,7 @@ __export(src_exports, {
172
176
  createDefaultPdfUnitData: () => createDefaultPdfUnitData,
173
177
  createHttpSilentPrintAdapter: () => createHttpSilentPrintAdapter,
174
178
  createPdfBrowserFidelitySamples: () => createPdfBrowserFidelitySamples,
179
+ createPdfCjkFontSources: () => createPdfCjkFontSources,
175
180
  createPdfJsxNode: () => createPdfJsxNode,
176
181
  detectCJKCharacters: () => detectCJKCharacters,
177
182
  detectCJKInPdfInputs: () => detectCJKInPdfInputs,
@@ -9588,6 +9593,64 @@ var PdfRenderError = class extends Error {
9588
9593
  if (extra?.missingGlyphs) this.missingGlyphs = extra.missingGlyphs;
9589
9594
  }
9590
9595
  };
9596
+ var DEFAULT_PDF_CJK_FONT_PACKAGE = "@yudaocode/univer-pdf-fonts";
9597
+ var DEFAULT_PDF_CJK_FONT_VERSION = "1.0.0";
9598
+ var DEFAULT_PDF_CJK_FONT_FAMILY = "Noto Sans SC";
9599
+ var DEFAULT_PDF_CJK_FONT_FILES = Object.freeze({
9600
+ normal: Object.freeze({
9601
+ file: "NotoSansSC-Regular.ttf",
9602
+ family: DEFAULT_PDF_CJK_FONT_FAMILY,
9603
+ weight: "normal",
9604
+ integrity: "sha384-WYgE+CQjxrXCFCynsUOYE86llni41IspZsiH2huo8yxlgR2GKNE5fzeurmHXRfIe"
9605
+ }),
9606
+ bold: Object.freeze({
9607
+ file: "NotoSansSC-Bold.ttf",
9608
+ family: DEFAULT_PDF_CJK_FONT_FAMILY,
9609
+ weight: "bold",
9610
+ integrity: "sha384-jI+dGvcJGGgO8RayO+x2LHDI85inVoe36tfbBKtSD6SQ0A8VKi5s+0lG+of4qB6j"
9611
+ })
9612
+ });
9613
+ function createPdfCjkFontSources(options) {
9614
+ const ver = (options?.version ?? DEFAULT_PDF_CJK_FONT_VERSION).trim() || DEFAULT_PDF_CJK_FONT_VERSION;
9615
+ const family = options?.family ?? DEFAULT_PDF_CJK_FONT_FAMILY;
9616
+ const rawBase = (options?.baseUrl ?? `https://cdn.jsdmirror.com/npm/${DEFAULT_PDF_CJK_FONT_PACKAGE}@${ver}/fonts`).replace(/\{version\}/g, ver);
9617
+ const cleanBase = rawBase.replace(/\/+$/, "");
9618
+ let requestedWeights;
9619
+ if (options?.weights === "both") {
9620
+ requestedWeights = ["normal", "bold"];
9621
+ } else if (options?.weights === "normal" || options?.weights === "bold") {
9622
+ requestedWeights = [options.weights];
9623
+ } else if (Array.isArray(options?.weights) && options.weights.length > 0) {
9624
+ requestedWeights = [];
9625
+ for (const w of options.weights) {
9626
+ if ((w === "normal" || w === "bold") && !requestedWeights.includes(w)) {
9627
+ requestedWeights.push(w);
9628
+ }
9629
+ }
9630
+ if (requestedWeights.length === 0) {
9631
+ requestedWeights = ["normal"];
9632
+ }
9633
+ } else {
9634
+ requestedWeights = ["normal"];
9635
+ }
9636
+ return requestedWeights.map((weight) => {
9637
+ const preset = DEFAULT_PDF_CJK_FONT_FILES[weight];
9638
+ let integrity;
9639
+ if (options?.integrity && typeof options.integrity === "object") {
9640
+ integrity = options.integrity[weight];
9641
+ } else if (options?.integrity === false) {
9642
+ integrity = void 0;
9643
+ } else if (options?.integrity === true || options?.integrity === void 0 && ver === DEFAULT_PDF_CJK_FONT_VERSION) {
9644
+ integrity = preset.integrity;
9645
+ }
9646
+ return {
9647
+ url: `${cleanBase}/${preset.file}`,
9648
+ family,
9649
+ weight,
9650
+ ...integrity ? { integrity } : {}
9651
+ };
9652
+ });
9653
+ }
9591
9654
  var pdfFontUrlByteCache = /* @__PURE__ */ new Map();
9592
9655
  function clearPdfFontUrlCache() {
9593
9656
  pdfFontUrlByteCache.clear();
@@ -9923,39 +9986,147 @@ function registerSubsetType0FontInDoc(pdfDoc, fontBytes, usedCodePoints, fontTag
9923
9986
  );
9924
9987
  return { type0FontRef, subset };
9925
9988
  }
9926
- async function resolveRenderFontsForExport(snapshot, options) {
9989
+ function buildCidUtf16ToUnicodeCmapString(usedCodePoints) {
9990
+ const bmpHexList = [];
9991
+ const suppHexList = [];
9992
+ const seen = /* @__PURE__ */ new Set();
9993
+ for (const cp of usedCodePoints) {
9994
+ if (!Number.isInteger(cp) || cp <= 0 || cp === 65279 || seen.has(cp)) continue;
9995
+ seen.add(cp);
9996
+ const hex = toUtf16BeHex(String.fromCodePoint(cp), false);
9997
+ if (cp <= 65535) {
9998
+ bmpHexList.push(hex);
9999
+ } else {
10000
+ suppHexList.push(hex);
10001
+ }
10002
+ }
10003
+ bmpHexList.sort();
10004
+ suppHexList.sort();
10005
+ const bfBlocks = [];
10006
+ for (const list of [bmpHexList, suppHexList]) {
10007
+ for (let i = 0; i < list.length; i += 100) {
10008
+ const chunk = list.slice(i, i + 100);
10009
+ const lines = chunk.map((h) => `<${h}> <${h}>`).join("\n");
10010
+ bfBlocks.push(`${chunk.length} beginbfchar
10011
+ ${lines}
10012
+ endbfchar`);
10013
+ }
10014
+ }
10015
+ const codespaceLines = suppHexList.length > 0 ? ["2 begincodespacerange", "<0000> <FFFF>", "<D800DC00> <DBFFDFFF>", "endcodespacerange"] : ["1 begincodespacerange", "<0000> <FFFF>", "endcodespacerange"];
10016
+ return [
10017
+ "/CIDInit /ProcSet findresource begin",
10018
+ "12 dict begin",
10019
+ "begincmap",
10020
+ "/CIDSystemInfo << /Registry (Adobe) /Ordering (UCS) /Supplement 0 >> def",
10021
+ "/CMapName /Adobe-Identity-UCS def",
10022
+ "/CMapType 2 def",
10023
+ ...codespaceLines,
10024
+ ...bfBlocks,
10025
+ "endcmap",
10026
+ "CMapName currentdict /CMap defineresource pop",
10027
+ "end",
10028
+ "end"
10029
+ ].join("\n");
10030
+ }
10031
+ function detectUsedPdfTextWeights(snapshot, effectiveData) {
10032
+ let usesNormal = false;
10033
+ let usesBold = false;
10034
+ if (snapshot.metadata?.watermarkText && snapshot.metadata?.watermarkConfig?.enabled !== false) {
10035
+ usesNormal = true;
10036
+ }
10037
+ if (snapshot.metadata?.batesConfig?.enabled) {
10038
+ usesNormal = true;
10039
+ }
10040
+ const totalPages = snapshot.document.pageOrder.length;
10041
+ const startPageOffset = Math.max(1, Number(snapshot.metadata?.startPageNumber ?? 1) || 1);
10042
+ snapshot.document.pageOrder.forEach((pageId, pIdx) => {
10043
+ const pageCtx = { pageNumber: startPageOffset + pIdx, totalPages: startPageOffset + totalPages - 1 };
10044
+ const map = snapshot.editState.elementsByPage[pageId] ?? {};
10045
+ const order = snapshot.editState.elementOrderByPage[pageId] ?? Object.keys(map);
10046
+ for (const id of order) {
10047
+ const el = map[id];
10048
+ if (!el || el.hidden) continue;
10049
+ if (el.type === "text" /* TEXT */) {
10050
+ if (el.richSpans?.length) {
10051
+ for (const span of el.richSpans) {
10052
+ const t = resolveTemplateString(span.text, void 0, effectiveData, pageCtx);
10053
+ if (!t) continue;
10054
+ const spanIsBold = span.bold !== void 0 ? span.bold : el.style?.fontWeight === "bold";
10055
+ if (spanIsBold) usesBold = true;
10056
+ else usesNormal = true;
10057
+ }
10058
+ } else {
10059
+ const t = resolveTemplateString(el.content, el.fieldKey || el.bindingField, effectiveData, pageCtx);
10060
+ if (t) {
10061
+ if (el.style?.fontWeight === "bold") usesBold = true;
10062
+ else usesNormal = true;
10063
+ }
10064
+ }
10065
+ } else if (el.type === "list" /* LIST */) {
10066
+ if (el.items?.length) {
10067
+ if (el.style?.fontWeight === "bold") usesBold = true;
10068
+ else usesNormal = true;
10069
+ }
10070
+ } else if (el.type === "stamp" /* STAMP */) {
10071
+ if (el.primaryText) usesBold = true;
10072
+ if (el.secondaryText) usesNormal = true;
10073
+ } else if (el.type === "table" /* TABLE */) {
10074
+ if (el.showHead !== false && el.columns?.length) {
10075
+ if ((el.headerStyle?.fontWeight ?? "bold") === "bold") usesBold = true;
10076
+ else usesNormal = true;
10077
+ }
10078
+ if (el.rows && el.rows.length > 0 || Boolean(el.bindingField && effectiveData)) {
10079
+ if (el.bodyStyle?.fontWeight === "bold") usesBold = true;
10080
+ else usesNormal = true;
10081
+ }
10082
+ if (el.showPageSubtotal || el.showGrandTotal) {
10083
+ usesBold = true;
10084
+ }
10085
+ } else if (el.type === "checkbox" /* CHECKBOX */ || el.type === "radioGroup" /* RADIO_GROUP */ || el.type === "select" /* SELECT */ || el.type === "dateTime" /* DATE_TIME */ || el.type === "barcode" /* BARCODE */ || el.type === "redaction" /* REDACTION */ || el.type === "annotation" /* ANNOTATION */) {
10086
+ usesNormal = true;
10087
+ }
10088
+ }
10089
+ });
10090
+ return { usesNormal, usesBold };
10091
+ }
10092
+ async function resolveRenderFontsForExport(snapshot, effectiveData, options) {
9927
10093
  const renderCfg = options?.render;
9928
- const hasHostFonts = Boolean(renderCfg?.fonts && renderCfg.fonts.length > 0);
10094
+ const hasExplicitRenderFonts = Array.isArray(renderCfg?.fonts);
9929
10095
  const explicitMode = renderCfg?.cjkTextMode ?? options?.cjkTextMode;
9930
- const requestedMode = explicitMode ?? (hasHostFonts ? "subset-ttf" : "raster-hd");
10096
+ const requestedMode = explicitMode ?? (hasExplicitRenderFonts ? "subset-ttf" : "raster-hd");
9931
10097
  if (requestedMode === "raster-hd" || requestedMode === "cid-vector") {
9932
- return { effectiveMode: requestedMode };
10098
+ return { effectiveMode: requestedMode, hasExplicitRenderFonts };
9933
10099
  }
9934
10100
  const failedFonts = [];
9935
10101
  let normalFontBytes;
9936
- let boldFontBytes = options?.customBoldFontBytes;
9937
- if (hasHostFonts && renderCfg?.fonts) {
10102
+ let boldFontBytes;
10103
+ if (hasExplicitRenderFonts && renderCfg?.fonts) {
9938
10104
  const normalCandidates = renderCfg.fonts.map((f, index) => ({ f, index })).filter(({ f }) => f.weight !== "bold");
9939
10105
  const boldCandidates = renderCfg.fonts.map((f, index) => ({ f, index })).filter(({ f }) => f.weight === "bold");
9940
- const primaryOrder = normalCandidates.length > 0 ? normalCandidates : boldCandidates;
9941
- for (const { f, index } of primaryOrder) {
9942
- try {
9943
- normalFontBytes = await loadSingleFontCandidate(f);
9944
- break;
9945
- } catch (err) {
9946
- failedFonts.push({
9947
- index,
9948
- family: f.family,
9949
- weight: f.weight,
9950
- url: f.url,
9951
- reason: err?.message || String(err)
9952
- });
10106
+ const { usesNormal, usesBold } = detectUsedPdfTextWeights(snapshot, effectiveData);
10107
+ let requiredWeightsFailed = renderCfg.fonts.length === 0;
10108
+ if (normalCandidates.length > 0 && boldCandidates.length === 0) {
10109
+ for (const { f, index } of normalCandidates) {
10110
+ try {
10111
+ normalFontBytes = await loadSingleFontCandidate(f);
10112
+ break;
10113
+ } catch (err) {
10114
+ failedFonts.push({
10115
+ index,
10116
+ family: f.family,
10117
+ weight: f.weight,
10118
+ url: f.url,
10119
+ reason: err?.message || String(err)
10120
+ });
10121
+ }
9953
10122
  }
9954
- }
9955
- if (normalFontBytes && !boldFontBytes && boldCandidates.length > 0 && normalCandidates.length > 0) {
10123
+ if (!normalFontBytes) requiredWeightsFailed = true;
10124
+ } else if (normalCandidates.length === 0 && boldCandidates.length > 0) {
9956
10125
  for (const { f, index } of boldCandidates) {
9957
10126
  try {
9958
- boldFontBytes = await loadSingleFontCandidate(f);
10127
+ const loadedBold = await loadSingleFontCandidate(f);
10128
+ normalFontBytes = loadedBold;
10129
+ boldFontBytes = loadedBold;
9959
10130
  break;
9960
10131
  } catch (err) {
9961
10132
  failedFonts.push({
@@ -9967,50 +10138,106 @@ async function resolveRenderFontsForExport(snapshot, options) {
9967
10138
  });
9968
10139
  }
9969
10140
  }
10141
+ if (!normalFontBytes) requiredWeightsFailed = true;
10142
+ } else if (normalCandidates.length > 0 && boldCandidates.length > 0) {
10143
+ const needNormal = usesNormal || !usesBold;
10144
+ const needBold = usesBold;
10145
+ if (needNormal) {
10146
+ for (const { f, index } of normalCandidates) {
10147
+ try {
10148
+ normalFontBytes = await loadSingleFontCandidate(f);
10149
+ break;
10150
+ } catch (err) {
10151
+ failedFonts.push({
10152
+ index,
10153
+ family: f.family,
10154
+ weight: f.weight,
10155
+ url: f.url,
10156
+ reason: err?.message || String(err)
10157
+ });
10158
+ }
10159
+ }
10160
+ if (!normalFontBytes) requiredWeightsFailed = true;
10161
+ }
10162
+ if (!requiredWeightsFailed && needBold) {
10163
+ for (const { f, index } of boldCandidates) {
10164
+ try {
10165
+ boldFontBytes = await loadSingleFontCandidate(f);
10166
+ break;
10167
+ } catch (err) {
10168
+ failedFonts.push({
10169
+ index,
10170
+ family: f.family,
10171
+ weight: f.weight,
10172
+ url: f.url,
10173
+ reason: err?.message || String(err)
10174
+ });
10175
+ }
10176
+ }
10177
+ if (!boldFontBytes) requiredWeightsFailed = true;
10178
+ if (!needNormal && boldFontBytes) {
10179
+ normalFontBytes = boldFontBytes;
10180
+ }
10181
+ }
9970
10182
  }
9971
- }
9972
- if (!normalFontBytes && options?.customFontBytes && options.customFontBytes.byteLength > 0) {
9973
- try {
9974
- inspectTrueTypeFont(options.customFontBytes);
9975
- normalFontBytes = options.customFontBytes;
9976
- } catch (err) {
9977
- failedFonts.push({
9978
- index: failedFonts.length,
9979
- reason: err?.message || String(err)
9980
- });
10183
+ if (!requiredWeightsFailed && normalFontBytes && normalFontBytes.byteLength > 0) {
10184
+ return {
10185
+ effectiveMode: "subset-ttf",
10186
+ normalFontBytes,
10187
+ boldFontBytes,
10188
+ hasExplicitRenderFonts: true
10189
+ };
9981
10190
  }
9982
- }
9983
- if (!normalFontBytes && snapshot?.resourceBindings) {
9984
- const fontBinding = Object.values(snapshot.resourceBindings).find(
9985
- (b) => b.type === "font" && Boolean(b.dataUri)
9986
- );
9987
- if (fontBinding?.dataUri) {
10191
+ } else {
10192
+ boldFontBytes = options?.customBoldFontBytes;
10193
+ if (options?.customFontBytes && options.customFontBytes.byteLength > 0) {
9988
10194
  try {
9989
- const decoded = dataUriToBytes(fontBinding.dataUri);
9990
- inspectTrueTypeFont(decoded);
9991
- normalFontBytes = decoded;
10195
+ inspectTrueTypeFont(options.customFontBytes);
10196
+ normalFontBytes = options.customFontBytes;
9992
10197
  } catch (err) {
9993
10198
  failedFonts.push({
9994
10199
  index: failedFonts.length,
9995
- family: fontBinding.name,
9996
10200
  reason: err?.message || String(err)
9997
10201
  });
9998
10202
  }
9999
10203
  }
10000
- }
10001
- if (normalFontBytes && normalFontBytes.byteLength > 0) {
10002
- if (boldFontBytes) {
10003
- try {
10004
- inspectTrueTypeFont(boldFontBytes);
10005
- } catch {
10006
- boldFontBytes = void 0;
10204
+ if (!normalFontBytes && snapshot?.resourceBindings) {
10205
+ const fontBinding = Object.values(snapshot.resourceBindings).find(
10206
+ (b) => b.type === "font" && Boolean(b.dataUri)
10207
+ );
10208
+ if (fontBinding?.dataUri) {
10209
+ try {
10210
+ const decoded = dataUriToBytes(fontBinding.dataUri);
10211
+ inspectTrueTypeFont(decoded);
10212
+ normalFontBytes = decoded;
10213
+ } catch (err) {
10214
+ failedFonts.push({
10215
+ index: failedFonts.length,
10216
+ family: fontBinding.name,
10217
+ reason: err?.message || String(err)
10218
+ });
10219
+ }
10220
+ }
10221
+ }
10222
+ if (normalFontBytes && normalFontBytes.byteLength > 0) {
10223
+ if (boldFontBytes) {
10224
+ try {
10225
+ inspectTrueTypeFont(boldFontBytes);
10226
+ } catch {
10227
+ boldFontBytes = void 0;
10228
+ }
10007
10229
  }
10230
+ return {
10231
+ effectiveMode: "subset-ttf",
10232
+ normalFontBytes,
10233
+ boldFontBytes,
10234
+ hasExplicitRenderFonts: false
10235
+ };
10008
10236
  }
10009
- return { effectiveMode: "subset-ttf", normalFontBytes, boldFontBytes };
10010
10237
  }
10011
10238
  const fallbackPolicy = renderCfg?.fallback ?? "error";
10012
10239
  const detailSummary = failedFonts.length > 0 ? failedFonts.map(
10013
- (e) => `#${e.index}${e.family ? ` (${e.family})` : ""}${e.url ? ` [${e.url}]` : ""}: ${e.reason}`
10240
+ (e) => `#${e.index}${e.family ? ` (${e.family})` : ""}${e.weight ? ` [${e.weight}]` : ""}${e.url ? ` [${e.url}]` : ""}: ${e.reason}`
10014
10241
  ).join("; ") : "\u672A\u63D0\u4F9B\u53EF\u7528\u7684 TrueType (.ttf) \u5B57\u4F53\u5B57\u8282\u6216\u5730\u5740";
10015
10242
  if (fallbackPolicy === "raster-hd" || fallbackPolicy === "cid-vector") {
10016
10243
  renderCfg?.onWarning?.({
@@ -10018,7 +10245,7 @@ async function resolveRenderFontsForExport(snapshot, options) {
10018
10245
  message: `\u4E2D\u6587\u5B57\u4F53\u52A0\u8F7D\u5931\u8D25\uFF0C\u5DF2\u6309\u663E\u5F0F\u56DE\u9000\u7B56\u7565\u5207\u6362\u81F3 '${fallbackPolicy}'\uFF1A${detailSummary}`,
10019
10246
  details: { fallback: fallbackPolicy, failedFonts }
10020
10247
  });
10021
- return { effectiveMode: fallbackPolicy };
10248
+ return { effectiveMode: fallbackPolicy, hasExplicitRenderFonts };
10022
10249
  }
10023
10250
  throw new PdfRenderError(
10024
10251
  "FONT_UNAVAILABLE",
@@ -10029,8 +10256,11 @@ async function resolveRenderFontsForExport(snapshot, options) {
10029
10256
  function initVectorCjkEmbedState(pdfDoc, snapshot, effectiveData, options, preResolved) {
10030
10257
  const requested = preResolved?.effectiveMode ?? options?.render?.cjkTextMode ?? options?.cjkTextMode ?? "raster-hd";
10031
10258
  if (requested === "raster-hd") return null;
10032
- let resolvedFontBytes = preResolved?.normalFontBytes ?? options?.customFontBytes;
10033
- if ((!resolvedFontBytes || resolvedFontBytes.byteLength === 0) && !preResolved && snapshot?.resourceBindings) {
10259
+ const hasExplicitRenderFonts = Boolean(
10260
+ preResolved?.hasExplicitRenderFonts ?? Array.isArray(options?.render?.fonts)
10261
+ );
10262
+ let resolvedFontBytes = preResolved ? preResolved.normalFontBytes : hasExplicitRenderFonts ? void 0 : options?.customFontBytes;
10263
+ if ((!resolvedFontBytes || resolvedFontBytes.byteLength === 0) && !preResolved && !hasExplicitRenderFonts && snapshot?.resourceBindings) {
10034
10264
  const fontBinding = Object.values(snapshot.resourceBindings).find(
10035
10265
  (b) => b.type === "font" && Boolean(b.dataUri)
10036
10266
  );
@@ -10056,6 +10286,24 @@ function initVectorCjkEmbedState(pdfDoc, snapshot, effectiveData, options, preRe
10056
10286
  usedCodePoints,
10057
10287
  "UNVPDF+SubsetTTF"
10058
10288
  );
10289
+ let boldType0FontRef;
10290
+ let boldSubset;
10291
+ const boldBytes = preResolved ? preResolved.boldFontBytes : hasExplicitRenderFonts ? void 0 : options?.customBoldFontBytes;
10292
+ if (boldBytes && boldBytes.byteLength > 0) {
10293
+ if (boldBytes === resolvedFontBytes) {
10294
+ boldType0FontRef = type0FontRef2;
10295
+ boldSubset = subset;
10296
+ } else {
10297
+ const regBold = registerSubsetType0FontInDoc(
10298
+ pdfDoc,
10299
+ boldBytes,
10300
+ usedCodePoints,
10301
+ "UNVPDF+SubsetTTFBold"
10302
+ );
10303
+ boldType0FontRef = regBold.type0FontRef;
10304
+ boldSubset = regBold.subset;
10305
+ }
10306
+ }
10059
10307
  const missingItems = collectMissingGlyphsFromPdfUnit(
10060
10308
  snapshot,
10061
10309
  (cp) => (subset.codePointToGid[cp] ?? 0) > 0,
@@ -10063,7 +10311,7 @@ function initVectorCjkEmbedState(pdfDoc, snapshot, effectiveData, options, preRe
10063
10311
  formatPdfTableCell
10064
10312
  );
10065
10313
  if (missingItems.length > 0) {
10066
- const missingPolicy = options?.render?.missingGlyph ?? "warn";
10314
+ const missingPolicy = options?.render?.missingGlyph ?? (hasExplicitRenderFonts ? "error" : "warn");
10067
10315
  if (missingPolicy === "error") {
10068
10316
  const desc = missingItems.map(
10069
10317
  (m) => `${m.pageId ? `${m.pageId}/` : ""}${m.elementId}: ${m.chars.map((c, idx) => `'${c}' (${m.codePoints[idx]})`).join(", ")}`
@@ -10086,19 +10334,6 @@ function initVectorCjkEmbedState(pdfDoc, snapshot, effectiveData, options, preRe
10086
10334
  }
10087
10335
  }
10088
10336
  }
10089
- let boldType0FontRef;
10090
- let boldSubset;
10091
- const boldBytes = preResolved?.boldFontBytes ?? options?.customBoldFontBytes;
10092
- if (boldBytes && boldBytes.byteLength > 0) {
10093
- const regBold = registerSubsetType0FontInDoc(
10094
- pdfDoc,
10095
- boldBytes,
10096
- usedCodePoints,
10097
- "UNVPDF+SubsetTTFBold"
10098
- );
10099
- boldType0FontRef = regBold.type0FontRef;
10100
- boldSubset = regBold.subset;
10101
- }
10102
10337
  return {
10103
10338
  mode: "subset-ttf",
10104
10339
  type0FontRef: type0FontRef2,
@@ -10107,6 +10342,9 @@ function initVectorCjkEmbedState(pdfDoc, snapshot, effectiveData, options, preRe
10107
10342
  ...boldType0FontRef ? { boldType0FontRef, boldSubset, boldPageFontKeys: /* @__PURE__ */ new WeakMap() } : {}
10108
10343
  };
10109
10344
  }
10345
+ const usedCidCodePoints = collectUsedCodePointsFromPdfUnit(snapshot, effectiveData);
10346
+ const cidToUnicodeCmap = buildCidUtf16ToUnicodeCmapString(usedCidCodePoints);
10347
+ const cidToUnicodeRef = pdfDoc.context.register(pdfDoc.context.flateStream(cidToUnicodeCmap));
10110
10348
  const fontDescriptorRef = pdfDoc.context.register(
10111
10349
  pdfDoc.context.obj({
10112
10350
  Type: "FontDescriptor",
@@ -10140,7 +10378,8 @@ function initVectorCjkEmbedState(pdfDoc, snapshot, effectiveData, options, preRe
10140
10378
  Subtype: "Type0",
10141
10379
  BaseFont: "STSong-Light",
10142
10380
  Encoding: "UniGB-UTF16-H",
10143
- DescendantFonts: [cidFontRef]
10381
+ DescendantFonts: [cidFontRef],
10382
+ ToUnicode: cidToUnicodeRef
10144
10383
  })
10145
10384
  );
10146
10385
  return {
@@ -10291,7 +10530,7 @@ function encodeVectorCjkLineHex(line, state, overrideSubset) {
10291
10530
  }
10292
10531
  return hex;
10293
10532
  }
10294
- return toUtf16BeHex(line, true);
10533
+ return toUtf16BeHex(line.replace(/\uFEFF/g, ""), false);
10295
10534
  }
10296
10535
  function drawVectorCjkTextBox(page, pageHeight, text, left, top, width, height, style, state, noWrapSingleLine = false, colorType, overrideCharacterSpacing) {
10297
10536
  const wantBold = style?.fontWeight === "bold";
@@ -12409,7 +12648,7 @@ async function exportPdfBytes(snapshot, runtimeData, options) {
12409
12648
  options?.accessibilityTagged ?? snapshot.accessibilityTagged ?? snapshot.metadata?.accessibilityTagged
12410
12649
  );
12411
12650
  const optimizeSize = Boolean(options?.optimizeSize);
12412
- const preResolvedFonts = await resolveRenderFontsForExport(snapshot, options);
12651
+ const preResolvedFonts = await resolveRenderFontsForExport(snapshot, effectiveData, options);
12413
12652
  const pdfDoc = await import_pdf_lib3.PDFDocument.create();
12414
12653
  if (snapshot.metadata?.sanitized) {
12415
12654
  pdfDoc.setTitle("");
@@ -16107,7 +16346,7 @@ function buildCompositeTestGlyph(compGidA, compGidB) {
16107
16346
  view.setInt16(24, 80, false);
16108
16347
  return buf;
16109
16348
  }
16110
- var DEFAULT_FIXTURE_CJK_TEXT = "\u987A\u4E30\u7535\u5B50\u9762\u5355\u4E09\u8054\u91C7\u8D2D\u51FA\u5E93\u5957\u6253\u6A21\u677F\u542B\u8FFD\u6EAF\u7801\u660E\u7EC6\u8868\u4E0E\u7B7E\u6536\u7EA2\u7AE0\u828B\u9053\u4F01\u4E1A\u7EA7\u62A5\u8868\u8BA2\u5355\u7F16\u53F7\u5BA2\u6237\u540D\u79F0\u6536\u8D27\u5730\u5740\u5546\u54C1\u89C4\u683C\u6570\u91CF\u5355\u4EF7\u91D1\u989D\u5408\u8BA1\u5DF2\u6838\u9A8C\u4FDD\u4EF7\u8FD0\u8F93\u6B21\u65E5\u8FBE\u9646\u8FD0\u4E13\u7968\u666E\u7968\u4E0A\u6D77\u6D66\u4E1C\u5F20\u6C5F\u9AD8\u79D1\u6280\u56ED\u533A\u5317\u4EAC\u6DF1\u5733\u676D\u5DDE\u4E2D\u6587\u77E2\u91CF\u53EF\u68C0\u7D22\u5B57\u4F53\u5B50\u96C6\u5316\u6D4B\u8BD5\u4E00\u4E8C\u4E09\u56DB\u4E94\u516D\u4E03\u516B\u4E5D\u5341\u767E\u5343\u4E07\u96F6\u5143\u89D2\u5206\u5E74\u6708\u65E5\u65F6\u5206\u79D2\u9875\u5171\u7B2C\u5185\u90E8\u8D44\u6599\u590D\u5370\u65E0\u6548\u8D22\u52A1\u4E13\u7528\u7AE0\u4ED3\u5E93\u7B7E\u7AE0\u9879\u76EE\u6458\u8981\u5BA1\u6279\u4EBA\u65E5\u671F\u8BF4\u660E\u72B6\u6001\u901A\u8FC7\u5F85\u5BA1\u6BD4\u4F8B\u589E\u957F\u7387\u5B8C\u6210\u5EA6\u6708\u5EA6\u5B63\u5EA6\u5E74\u5EA6\u5DE5\u4E1A\u4F20\u611F\u5668\u6A21\u5757\u63A7\u5236\u5668\u7CBE\u5BC6\u7EC4\u4EF6\u534E\u4E1C\u534E\u5357\u534E\u5317\u7ECF\u8425\u7B80\u62A5\u6838\u5FC3\u6B63\u5E38\u884C\u51FA\u88C1\u5207\u5916\u6EA2\u90BB\u683C\u5F20\u5DE5\u636E\u6001\u5165\u8DE8\u8868\u5934\u6591\u9A6C\u7EB9\u8FDE\u7EED\u6027\u8BC1\u5E8F\u5DE6\u5BF9\u9F50\u9876\u90E8\u5E95\u53F3\u7F29\u5C0F\u5B57\u81EA\u9002\u5E94\u591A\u6BB5\u6DF7\u6392\u957F\u6587\u672C\u793A\u4F8B\u5168\u89D2\u6807\u70B9\u5907\u6CE8\u751F\u50FB\u56FE\u6807\u7F3A\u8BCA\u65AD\u5DEE\u9519\u4EA4\u4ED8\u56FA\u9AD8\u5C06\u5728\u4E25\u7EDD\u5411\u4E0B\u65B9\u5143\u7D20\u4F4D\u8FB9\u4E4B\u5C45\u5782\u76F4\u7387\u5F53\u7D27\u51D1\u52A8\u81F3\u4F4E\u4FDD\u7559\u6536\u7F16\u5907\u54C1\u5957\u9996\u4FB5\u5165\u4EC5\u672B\u5C3E\u73B0\u91CD\u53E0\u680F\u51C6\u7248\u5730\u5B9A\u5BB9\u500D\u540E\xD7\xA5\uFFE5\uFF0C\u3002\uFF1A\uFF1B\uFF01\uFF1F\uFF08\uFF09\u3010\u3011\u300A\u300B\uFF05\u2014\xB7\u201C\u201D\u2018\u2019\uFF5C\u2605";
16349
+ var DEFAULT_FIXTURE_CJK_TEXT = "\u987A\u4E30\u7535\u5B50\u9762\u5355\u4E09\u8054\u91C7\u8D2D\u51FA\u5E93\u5957\u6253\u6A21\u677F\u542B\u8FFD\u6EAF\u7801\u660E\u7EC6\u8868\u4E0E\u7B7E\u6536\u7EA2\u7AE0\u828B\u9053\u4F01\u4E1A\u7EA7\u62A5\u8868\u8BA2\u5355\u7F16\u53F7\u5BA2\u6237\u540D\u79F0\u6536\u8D27\u5730\u5740\u5546\u54C1\u89C4\u683C\u6570\u91CF\u5355\u4EF7\u91D1\u989D\u5408\u8BA1\u5DF2\u6838\u9A8C\u4FDD\u4EF7\u8FD0\u8F93\u6B21\u65E5\u8FBE\u9646\u8FD0\u4E13\u7968\u666E\u7968\u4E0A\u6D77\u6D66\u4E1C\u5F20\u6C5F\u9AD8\u79D1\u6280\u56ED\u533A\u5317\u4EAC\u6DF1\u5733\u676D\u5DDE\u4E2D\u6587\u77E2\u91CF\u53EF\u68C0\u7D22\u5B57\u4F53\u5B50\u96C6\u5316\u6D4B\u8BD5\u4E00\u4E8C\u4E09\u56DB\u4E94\u516D\u4E03\u516B\u4E5D\u5341\u767E\u5343\u4E07\u96F6\u5143\u89D2\u5206\u5E74\u6708\u65E5\u65F6\u5206\u79D2\u9875\u5171\u7B2C\u5185\u90E8\u8D44\u6599\u590D\u5370\u65E0\u6548\u8D22\u52A1\u4E13\u7528\u7AE0\u4ED3\u5E93\u7B7E\u7AE0\u9879\u76EE\u6458\u8981\u5BA1\u6279\u4EBA\u65E5\u671F\u8BF4\u660E\u72B6\u6001\u901A\u8FC7\u5F85\u5BA1\u6BD4\u4F8B\u589E\u957F\u7387\u5B8C\u6210\u5EA6\u6708\u5EA6\u5B63\u5EA6\u5E74\u5EA6\u5DE5\u4E1A\u4F20\u611F\u5668\u6A21\u5757\u63A7\u5236\u5668\u7CBE\u5BC6\u7EC4\u4EF6\u534E\u4E1C\u534E\u5357\u534E\u5317\u7ECF\u8425\u7B80\u62A5\u6838\u5FC3\u6B63\u5E38\u884C\u51FA\u88C1\u5207\u5916\u6EA2\u90BB\u683C\u5F20\u5DE5\u636E\u6001\u5165\u8DE8\u8868\u5934\u6591\u9A6C\u7EB9\u8FDE\u7EED\u6027\u8BC1\u5E8F\u5DE6\u5BF9\u9F50\u9876\u90E8\u5E95\u53F3\u7F29\u5C0F\u5B57\u81EA\u9002\u5E94\u591A\u6BB5\u6DF7\u6392\u957F\u6587\u672C\u793A\u4F8B\u5168\u89D2\u6807\u70B9\u5907\u6CE8\u751F\u50FB\u56FE\u6807\u7F3A\u8BCA\u65AD\u5DEE\u9519\u4EA4\u4ED8\u56FA\u9AD8\u5C06\u5728\u4E25\u7EDD\u5411\u4E0B\u65B9\u5143\u7D20\u4F4D\u8FB9\u4E4B\u5C45\u5782\u76F4\u7387\u5F53\u7D27\u51D1\u52A8\u81F3\u4F4E\u4FDD\u7559\u6536\u7F16\u5907\u54C1\u5957\u9996\u4FB5\u5165\u4EC5\u672B\u5C3E\u73B0\u91CD\u53E0\u680F\u51C6\u7248\u5730\u5B9A\u5BB9\u500D\u540E\u77ED\u897F\u6846\u8D85\u7684\u754C\u6700\u6574\u5217\u5F0F\u5BBD\u503C\u5E01\u5305\u88C5\u663E\u7A84\u9ED8\u8BA4\u7167\u5F00\u542F\u6D41\u8F6C\u5F02\u672A\u5149\u6805\u517C\xD7\xA5\uFFE5\uFF0C\u3001\u3002\uFF1A\uFF1B\uFF01\uFF1F\uFF08\uFF09\u3010\u3011\u300A\u300B\uFF05\u2014\u2013\xB7\u201C\u201D\u2018\u2019\uFF5C\u2605";
16111
16350
  function buildMinimalTestTrueTypeFont(extraCodePoints) {
16112
16351
  const cpSet = /* @__PURE__ */ new Set();
16113
16352
  for (let ascii = 32; ascii <= 126; ascii++) {
@@ -24490,6 +24729,10 @@ UniverPdfsPlugin = __decorateClass([
24490
24729
  Barcode,
24491
24730
  Box,
24492
24731
  CIRCLE_MARK_BEZIER_KAPPA,
24732
+ DEFAULT_PDF_CJK_FONT_FAMILY,
24733
+ DEFAULT_PDF_CJK_FONT_FILES,
24734
+ DEFAULT_PDF_CJK_FONT_PACKAGE,
24735
+ DEFAULT_PDF_CJK_FONT_VERSION,
24493
24736
  DeleteSelectedPdfElementsCommand,
24494
24737
  DistributeSelectedPdfElementsCommand,
24495
24738
  Document,
@@ -24610,6 +24853,7 @@ UniverPdfsPlugin = __decorateClass([
24610
24853
  createDefaultPdfUnitData,
24611
24854
  createHttpSilentPrintAdapter,
24612
24855
  createPdfBrowserFidelitySamples,
24856
+ createPdfCjkFontSources,
24613
24857
  createPdfJsxNode,
24614
24858
  detectCJKCharacters,
24615
24859
  detectCJKInPdfInputs,