@yudaocode/univer-pdfs 1.6.214 → 1.6.216

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.
@@ -6626,10 +6626,96 @@ var PdfRenderError = class extends Error {
6626
6626
  if (extra?.missingGlyphs) this.missingGlyphs = extra.missingGlyphs;
6627
6627
  }
6628
6628
  };
6629
+ var DEFAULT_PDF_CJK_FONT_PACKAGE = "@yudaocode/univer-pdf-fonts";
6630
+ var DEFAULT_PDF_CJK_FONT_VERSION = "1.0.0";
6631
+ var DEFAULT_PDF_CJK_FONT_FAMILY = "Noto Sans SC";
6632
+ var DEFAULT_PDF_CJK_FONT_FILES = Object.freeze({
6633
+ normal: Object.freeze({
6634
+ file: "NotoSansSC-Regular.ttf",
6635
+ family: DEFAULT_PDF_CJK_FONT_FAMILY,
6636
+ weight: "normal",
6637
+ integrity: "sha384-WYgE+CQjxrXCFCynsUOYE86llni41IspZsiH2huo8yxlgR2GKNE5fzeurmHXRfIe"
6638
+ }),
6639
+ bold: Object.freeze({
6640
+ file: "NotoSansSC-Bold.ttf",
6641
+ family: DEFAULT_PDF_CJK_FONT_FAMILY,
6642
+ weight: "bold",
6643
+ integrity: "sha384-jI+dGvcJGGgO8RayO+x2LHDI85inVoe36tfbBKtSD6SQ0A8VKi5s+0lG+of4qB6j"
6644
+ })
6645
+ });
6646
+ function createPdfCjkFontSources(options) {
6647
+ const ver = (options?.version ?? DEFAULT_PDF_CJK_FONT_VERSION).trim() || DEFAULT_PDF_CJK_FONT_VERSION;
6648
+ const family = options?.family ?? DEFAULT_PDF_CJK_FONT_FAMILY;
6649
+ const rawBase = (options?.baseUrl ?? `https://cdn.jsdmirror.com/npm/${DEFAULT_PDF_CJK_FONT_PACKAGE}@${ver}/fonts`).replace(/\{version\}/g, ver);
6650
+ const cleanBase = rawBase.replace(/\/+$/, "");
6651
+ let requestedWeights;
6652
+ if (options?.weights === "both") {
6653
+ requestedWeights = ["normal", "bold"];
6654
+ } else if (options?.weights === "normal" || options?.weights === "bold") {
6655
+ requestedWeights = [options.weights];
6656
+ } else if (Array.isArray(options?.weights) && options.weights.length > 0) {
6657
+ requestedWeights = [];
6658
+ for (const w of options.weights) {
6659
+ if ((w === "normal" || w === "bold") && !requestedWeights.includes(w)) {
6660
+ requestedWeights.push(w);
6661
+ }
6662
+ }
6663
+ if (requestedWeights.length === 0) {
6664
+ requestedWeights = ["normal"];
6665
+ }
6666
+ } else {
6667
+ requestedWeights = ["normal"];
6668
+ }
6669
+ return requestedWeights.map((weight) => {
6670
+ const preset = DEFAULT_PDF_CJK_FONT_FILES[weight];
6671
+ let integrity;
6672
+ if (options?.integrity && typeof options.integrity === "object") {
6673
+ integrity = options.integrity[weight];
6674
+ } else if (options?.integrity === false) {
6675
+ integrity = void 0;
6676
+ } else if (options?.integrity === true || options?.integrity === void 0 && ver === DEFAULT_PDF_CJK_FONT_VERSION) {
6677
+ integrity = preset.integrity;
6678
+ }
6679
+ return {
6680
+ url: `${cleanBase}/${preset.file}`,
6681
+ family,
6682
+ weight,
6683
+ ...integrity ? { integrity } : {},
6684
+ ...options?.credentials !== void 0 ? { credentials: options.credentials } : {},
6685
+ ...options?.fetchInit !== void 0 ? { fetchInit: options.fetchInit } : {}
6686
+ };
6687
+ });
6688
+ }
6629
6689
  var pdfFontUrlByteCache = /* @__PURE__ */ new Map();
6690
+ function computeFontUrlCacheKey(url, integrity) {
6691
+ return `${url}|${integrity ?? ""}`;
6692
+ }
6630
6693
  function clearPdfFontUrlCache() {
6631
6694
  pdfFontUrlByteCache.clear();
6632
6695
  }
6696
+ var PdfFontCandidateLoadError = class extends Error {
6697
+ constructor(kind, message, status) {
6698
+ super(message);
6699
+ this.name = "PdfFontCandidateLoadError";
6700
+ this.kind = kind;
6701
+ if (status !== void 0) {
6702
+ this.status = status;
6703
+ }
6704
+ }
6705
+ };
6706
+ function toFailedFontEntry(index, src, err) {
6707
+ const kind = err instanceof PdfFontCandidateLoadError ? err.kind : "format";
6708
+ const status = err instanceof PdfFontCandidateLoadError ? err.status : void 0;
6709
+ return {
6710
+ index,
6711
+ ...src.family !== void 0 ? { family: src.family } : {},
6712
+ ...src.weight !== void 0 ? { weight: src.weight } : {},
6713
+ ...src.url !== void 0 ? { url: src.url } : {},
6714
+ kind,
6715
+ ...status !== void 0 ? { status } : {},
6716
+ reason: err?.message || String(err)
6717
+ };
6718
+ }
6633
6719
  function bytesToBase64Standard(bytes) {
6634
6720
  if (typeof Buffer !== "undefined") {
6635
6721
  return Buffer.from(bytes).toString("base64");
@@ -6645,7 +6731,10 @@ async function verifyFontSubresourceIntegrity(bytes, integrity) {
6645
6731
  if (!trimmed) return;
6646
6732
  const m = trimmed.match(/^(sha256|sha384|sha512)-([A-Za-z0-9+/=_-]+)$/i);
6647
6733
  if (!m) {
6648
- throw new Error(`Unsupported integrity format '${trimmed}' (expected sha256-/sha384-/sha512-).`);
6734
+ throw new PdfFontCandidateLoadError(
6735
+ "integrity",
6736
+ `Unsupported integrity format '${trimmed}' (expected sha256-/sha384-/sha512-).`
6737
+ );
6649
6738
  }
6650
6739
  const algoMap = {
6651
6740
  sha256: "SHA-256",
@@ -6656,7 +6745,10 @@ async function verifyFontSubresourceIntegrity(bytes, integrity) {
6656
6745
  const expectedB64 = m[2].replace(/-/g, "+").replace(/_/g, "/");
6657
6746
  const subtle = globalThis.crypto?.subtle;
6658
6747
  if (!subtle) {
6659
- throw new Error("Web Crypto API is unavailable to verify font integrity.");
6748
+ throw new PdfFontCandidateLoadError(
6749
+ "integrity",
6750
+ "Web Crypto API is unavailable to verify font integrity."
6751
+ );
6660
6752
  }
6661
6753
  const digestBuf = await subtle.digest(
6662
6754
  algo,
@@ -6665,45 +6757,84 @@ async function verifyFontSubresourceIntegrity(bytes, integrity) {
6665
6757
  const actualB64 = bytesToBase64Standard(new Uint8Array(digestBuf)).replace(/=+$/, "");
6666
6758
  const normExpected = expectedB64.replace(/=+$/, "");
6667
6759
  if (actualB64 !== normExpected) {
6668
- throw new Error(`Font SRI integrity mismatch (${m[1]}).`);
6760
+ throw new PdfFontCandidateLoadError("integrity", `Font SRI integrity mismatch (${m[1]}).`);
6761
+ }
6762
+ }
6763
+ async function fetchFontBytesWithSri(url, options) {
6764
+ const cacheKey = computeFontUrlCacheKey(url, options?.integrity);
6765
+ const cached = pdfFontUrlByteCache.get(cacheKey);
6766
+ if (cached) {
6767
+ return cached;
6768
+ }
6769
+ const mergedInit = {
6770
+ ...options?.fetchInit ?? {},
6771
+ ...options?.credentials !== void 0 ? { credentials: options.credentials } : {}
6772
+ };
6773
+ const hasInitKeys = Object.keys(mergedInit).length > 0;
6774
+ let resp;
6775
+ try {
6776
+ resp = hasInitKeys ? await fetch(url, mergedInit) : await fetch(url);
6777
+ } catch (err) {
6778
+ throw new PdfFontCandidateLoadError(
6779
+ "network",
6780
+ `Network error fetching '${url}': ${err?.message || String(err)}`
6781
+ );
6782
+ }
6783
+ if (!resp.ok) {
6784
+ throw new PdfFontCandidateLoadError(
6785
+ "http",
6786
+ `HTTP ${resp.status} fetching '${url}'.`,
6787
+ resp.status
6788
+ );
6789
+ }
6790
+ let ab;
6791
+ try {
6792
+ ab = await resp.arrayBuffer();
6793
+ } catch (err) {
6794
+ throw new PdfFontCandidateLoadError(
6795
+ "network",
6796
+ `Network error reading font body for '${url}': ${err?.message || String(err)}`
6797
+ );
6669
6798
  }
6799
+ const rawBytes = new Uint8Array(ab);
6800
+ if (rawBytes.byteLength === 0) {
6801
+ throw new PdfFontCandidateLoadError("empty", `Font response for '${url}' is empty (0 bytes).`);
6802
+ }
6803
+ if (options?.integrity) {
6804
+ await verifyFontSubresourceIntegrity(rawBytes, options.integrity);
6805
+ }
6806
+ try {
6807
+ inspectTrueTypeFont(rawBytes);
6808
+ } catch (err) {
6809
+ throw new PdfFontCandidateLoadError("format", err?.message || String(err));
6810
+ }
6811
+ pdfFontUrlByteCache.set(cacheKey, rawBytes);
6812
+ return rawBytes;
6670
6813
  }
6671
6814
  async function loadSingleFontCandidate(src) {
6672
- let rawBytes;
6673
6815
  if (src.bytes != null) {
6674
- rawBytes = src.bytes instanceof Uint8Array ? src.bytes : new Uint8Array(src.bytes);
6816
+ const rawBytes = src.bytes instanceof Uint8Array ? src.bytes : new Uint8Array(src.bytes);
6817
+ if (rawBytes.byteLength === 0) {
6818
+ throw new PdfFontCandidateLoadError("empty", "Font binary is empty (0 bytes).");
6819
+ }
6675
6820
  if (src.integrity) {
6676
6821
  await verifyFontSubresourceIntegrity(rawBytes, src.integrity);
6677
6822
  }
6678
- } else if (src.url) {
6679
- const cacheKey = `${src.url}|${src.integrity ?? ""}`;
6680
- const cached = pdfFontUrlByteCache.get(cacheKey);
6681
- if (cached) {
6682
- rawBytes = cached;
6683
- } else {
6684
- let resp;
6685
- try {
6686
- resp = await fetch(src.url);
6687
- } catch (err) {
6688
- throw new Error(`Network error fetching '${src.url}': ${err?.message || String(err)}`);
6689
- }
6690
- if (!resp.ok) {
6691
- throw new Error(`HTTP ${resp.status} fetching '${src.url}'.`);
6692
- }
6693
- const ab = await resp.arrayBuffer();
6694
- rawBytes = new Uint8Array(ab);
6695
- if (src.integrity) {
6696
- await verifyFontSubresourceIntegrity(rawBytes, src.integrity);
6697
- }
6823
+ try {
6698
6824
  inspectTrueTypeFont(rawBytes);
6699
- pdfFontUrlByteCache.set(cacheKey, rawBytes);
6700
- return rawBytes;
6825
+ } catch (err) {
6826
+ throw new PdfFontCandidateLoadError("format", err?.message || String(err));
6701
6827
  }
6702
- } else {
6703
- throw new Error("Font source has neither bytes nor url.");
6828
+ return rawBytes;
6704
6829
  }
6705
- inspectTrueTypeFont(rawBytes);
6706
- return rawBytes;
6830
+ if (src.url && src.url.trim()) {
6831
+ return fetchFontBytesWithSri(src.url, {
6832
+ integrity: src.integrity,
6833
+ credentials: src.credentials,
6834
+ fetchInit: src.fetchInit
6835
+ });
6836
+ }
6837
+ throw new PdfFontCandidateLoadError("empty", "Font source has neither bytes nor url.");
6707
6838
  }
6708
6839
  function getByPath(data, path) {
6709
6840
  if (!data || !path) return void 0;
@@ -6961,94 +7092,253 @@ function registerSubsetType0FontInDoc(pdfDoc, fontBytes, usedCodePoints, fontTag
6961
7092
  );
6962
7093
  return { type0FontRef, subset };
6963
7094
  }
6964
- async function resolveRenderFontsForExport(snapshot, options) {
7095
+ function buildCidUtf16ToUnicodeCmapString(usedCodePoints) {
7096
+ const bmpHexList = [];
7097
+ const suppHexList = [];
7098
+ const seen = /* @__PURE__ */ new Set();
7099
+ for (const cp of usedCodePoints) {
7100
+ if (!Number.isInteger(cp) || cp <= 0 || cp === 65279 || seen.has(cp)) continue;
7101
+ seen.add(cp);
7102
+ const hex = toUtf16BeHex(String.fromCodePoint(cp), false);
7103
+ if (cp <= 65535) {
7104
+ bmpHexList.push(hex);
7105
+ } else {
7106
+ suppHexList.push(hex);
7107
+ }
7108
+ }
7109
+ bmpHexList.sort();
7110
+ suppHexList.sort();
7111
+ const bfBlocks = [];
7112
+ for (const list of [bmpHexList, suppHexList]) {
7113
+ for (let i = 0; i < list.length; i += 100) {
7114
+ const chunk = list.slice(i, i + 100);
7115
+ const lines = chunk.map((h) => `<${h}> <${h}>`).join("\n");
7116
+ bfBlocks.push(`${chunk.length} beginbfchar
7117
+ ${lines}
7118
+ endbfchar`);
7119
+ }
7120
+ }
7121
+ const codespaceLines = suppHexList.length > 0 ? ["2 begincodespacerange", "<0000> <FFFF>", "<D800DC00> <DBFFDFFF>", "endcodespacerange"] : ["1 begincodespacerange", "<0000> <FFFF>", "endcodespacerange"];
7122
+ return [
7123
+ "/CIDInit /ProcSet findresource begin",
7124
+ "12 dict begin",
7125
+ "begincmap",
7126
+ "/CIDSystemInfo << /Registry (Adobe) /Ordering (UCS) /Supplement 0 >> def",
7127
+ "/CMapName /Adobe-Identity-UCS def",
7128
+ "/CMapType 2 def",
7129
+ ...codespaceLines,
7130
+ ...bfBlocks,
7131
+ "endcmap",
7132
+ "CMapName currentdict /CMap defineresource pop",
7133
+ "end",
7134
+ "end"
7135
+ ].join("\n");
7136
+ }
7137
+ function detectUsedPdfTextWeights(snapshot, effectiveData) {
7138
+ let usesNormal = false;
7139
+ let usesBold = false;
7140
+ if (snapshot.metadata?.watermarkText && snapshot.metadata?.watermarkConfig?.enabled !== false) {
7141
+ usesNormal = true;
7142
+ }
7143
+ if (snapshot.metadata?.batesConfig?.enabled) {
7144
+ usesNormal = true;
7145
+ }
7146
+ const totalPages = snapshot.document.pageOrder.length;
7147
+ const startPageOffset = Math.max(1, Number(snapshot.metadata?.startPageNumber ?? 1) || 1);
7148
+ snapshot.document.pageOrder.forEach((pageId, pIdx) => {
7149
+ const pageCtx = { pageNumber: startPageOffset + pIdx, totalPages: startPageOffset + totalPages - 1 };
7150
+ const map = snapshot.editState.elementsByPage[pageId] ?? {};
7151
+ const order = snapshot.editState.elementOrderByPage[pageId] ?? Object.keys(map);
7152
+ for (const id of order) {
7153
+ const el = map[id];
7154
+ if (!el || el.hidden) continue;
7155
+ if (el.type === "text" /* TEXT */) {
7156
+ if (el.richSpans?.length) {
7157
+ for (const span of el.richSpans) {
7158
+ const t = resolveTemplateString(span.text, void 0, effectiveData, pageCtx);
7159
+ if (!t) continue;
7160
+ const spanIsBold = span.bold !== void 0 ? span.bold : el.style?.fontWeight === "bold";
7161
+ if (spanIsBold) usesBold = true;
7162
+ else usesNormal = true;
7163
+ }
7164
+ } else {
7165
+ const t = resolveTemplateString(el.content, el.fieldKey || el.bindingField, effectiveData, pageCtx);
7166
+ if (t) {
7167
+ if (el.style?.fontWeight === "bold") usesBold = true;
7168
+ else usesNormal = true;
7169
+ }
7170
+ }
7171
+ } else if (el.type === "list" /* LIST */) {
7172
+ if (el.items?.length) {
7173
+ if (el.style?.fontWeight === "bold") usesBold = true;
7174
+ else usesNormal = true;
7175
+ }
7176
+ } else if (el.type === "stamp" /* STAMP */) {
7177
+ if (el.primaryText) usesBold = true;
7178
+ if (el.secondaryText) usesNormal = true;
7179
+ } else if (el.type === "table" /* TABLE */) {
7180
+ if (el.showHead !== false && el.columns?.length) {
7181
+ if ((el.headerStyle?.fontWeight ?? "bold") === "bold") usesBold = true;
7182
+ else usesNormal = true;
7183
+ }
7184
+ if (el.rows && el.rows.length > 0 || Boolean(el.bindingField && effectiveData)) {
7185
+ if (el.bodyStyle?.fontWeight === "bold") usesBold = true;
7186
+ else usesNormal = true;
7187
+ }
7188
+ if (el.showPageSubtotal || el.showGrandTotal) {
7189
+ usesBold = true;
7190
+ }
7191
+ } 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 */) {
7192
+ usesNormal = true;
7193
+ }
7194
+ }
7195
+ });
7196
+ return { usesNormal, usesBold };
7197
+ }
7198
+ async function resolveRenderFontsForExport(snapshot, effectiveData, options) {
6965
7199
  const renderCfg = options?.render;
6966
- const hasHostFonts = Boolean(renderCfg?.fonts && renderCfg.fonts.length > 0);
7200
+ const hasExplicitRenderFonts = Array.isArray(renderCfg?.fonts);
6967
7201
  const explicitMode = renderCfg?.cjkTextMode ?? options?.cjkTextMode;
6968
- const requestedMode = explicitMode ?? (hasHostFonts ? "subset-ttf" : "raster-hd");
7202
+ const requestedMode = explicitMode ?? (hasExplicitRenderFonts ? "subset-ttf" : "raster-hd");
6969
7203
  if (requestedMode === "raster-hd" || requestedMode === "cid-vector") {
6970
- return { effectiveMode: requestedMode };
7204
+ return { effectiveMode: requestedMode, hasExplicitRenderFonts };
6971
7205
  }
6972
7206
  const failedFonts = [];
6973
7207
  let normalFontBytes;
6974
- let boldFontBytes = options?.customBoldFontBytes;
6975
- if (hasHostFonts && renderCfg?.fonts) {
7208
+ let boldFontBytes;
7209
+ if (hasExplicitRenderFonts && renderCfg?.fonts) {
6976
7210
  const normalCandidates = renderCfg.fonts.map((f, index) => ({ f, index })).filter(({ f }) => f.weight !== "bold");
6977
7211
  const boldCandidates = renderCfg.fonts.map((f, index) => ({ f, index })).filter(({ f }) => f.weight === "bold");
6978
- const primaryOrder = normalCandidates.length > 0 ? normalCandidates : boldCandidates;
6979
- for (const { f, index } of primaryOrder) {
6980
- try {
6981
- normalFontBytes = await loadSingleFontCandidate(f);
6982
- break;
6983
- } catch (err) {
6984
- failedFonts.push({
6985
- index,
6986
- family: f.family,
6987
- weight: f.weight,
6988
- url: f.url,
6989
- reason: err?.message || String(err)
6990
- });
7212
+ const { usesNormal, usesBold } = detectUsedPdfTextWeights(snapshot, effectiveData);
7213
+ let requiredWeightsFailed = renderCfg.fonts.length === 0;
7214
+ if (normalCandidates.length > 0 && boldCandidates.length === 0) {
7215
+ for (const { f, index } of normalCandidates) {
7216
+ try {
7217
+ normalFontBytes = await loadSingleFontCandidate(f);
7218
+ break;
7219
+ } catch (err) {
7220
+ failedFonts.push(toFailedFontEntry(index, f, err));
7221
+ }
6991
7222
  }
6992
- }
6993
- if (normalFontBytes && !boldFontBytes && boldCandidates.length > 0 && normalCandidates.length > 0) {
7223
+ if (!normalFontBytes) requiredWeightsFailed = true;
7224
+ } else if (normalCandidates.length === 0 && boldCandidates.length > 0) {
6994
7225
  for (const { f, index } of boldCandidates) {
6995
7226
  try {
6996
- boldFontBytes = await loadSingleFontCandidate(f);
7227
+ const loadedBold = await loadSingleFontCandidate(f);
7228
+ normalFontBytes = loadedBold;
7229
+ boldFontBytes = loadedBold;
6997
7230
  break;
6998
7231
  } catch (err) {
6999
- failedFonts.push({
7000
- index,
7001
- family: f.family,
7002
- weight: f.weight,
7003
- url: f.url,
7004
- reason: err?.message || String(err)
7005
- });
7232
+ failedFonts.push(toFailedFontEntry(index, f, err));
7233
+ }
7234
+ }
7235
+ if (!normalFontBytes) requiredWeightsFailed = true;
7236
+ } else if (normalCandidates.length > 0 && boldCandidates.length > 0) {
7237
+ const needNormal = usesNormal || !usesBold;
7238
+ const needBold = usesBold;
7239
+ if (needNormal) {
7240
+ for (const { f, index } of normalCandidates) {
7241
+ try {
7242
+ normalFontBytes = await loadSingleFontCandidate(f);
7243
+ break;
7244
+ } catch (err) {
7245
+ failedFonts.push(toFailedFontEntry(index, f, err));
7246
+ }
7247
+ }
7248
+ if (!normalFontBytes) requiredWeightsFailed = true;
7249
+ }
7250
+ if (!requiredWeightsFailed && needBold) {
7251
+ for (const { f, index } of boldCandidates) {
7252
+ try {
7253
+ boldFontBytes = await loadSingleFontCandidate(f);
7254
+ break;
7255
+ } catch (err) {
7256
+ failedFonts.push(toFailedFontEntry(index, f, err));
7257
+ }
7258
+ }
7259
+ if (!boldFontBytes) requiredWeightsFailed = true;
7260
+ if (!needNormal && boldFontBytes) {
7261
+ normalFontBytes = boldFontBytes;
7006
7262
  }
7007
7263
  }
7008
7264
  }
7009
- }
7010
- if (!normalFontBytes && options?.customFontBytes && options.customFontBytes.byteLength > 0) {
7011
- try {
7012
- inspectTrueTypeFont(options.customFontBytes);
7013
- normalFontBytes = options.customFontBytes;
7014
- } catch (err) {
7015
- failedFonts.push({
7016
- index: failedFonts.length,
7017
- reason: err?.message || String(err)
7018
- });
7265
+ if (!requiredWeightsFailed && normalFontBytes && normalFontBytes.byteLength > 0) {
7266
+ return {
7267
+ effectiveMode: "subset-ttf",
7268
+ normalFontBytes,
7269
+ boldFontBytes,
7270
+ hasExplicitRenderFonts: true
7271
+ };
7019
7272
  }
7020
- }
7021
- if (!normalFontBytes && snapshot?.resourceBindings) {
7022
- const fontBinding = Object.values(snapshot.resourceBindings).find(
7023
- (b) => b.type === "font" && Boolean(b.dataUri)
7024
- );
7025
- if (fontBinding?.dataUri) {
7026
- try {
7027
- const decoded = dataUriToBytes(fontBinding.dataUri);
7028
- inspectTrueTypeFont(decoded);
7029
- normalFontBytes = decoded;
7030
- } catch (err) {
7273
+ } else {
7274
+ boldFontBytes = options?.customBoldFontBytes;
7275
+ if (options?.customFontBytes !== void 0) {
7276
+ if (options.customFontBytes.byteLength === 0) {
7031
7277
  failedFonts.push({
7032
7278
  index: failedFonts.length,
7033
- family: fontBinding.name,
7034
- reason: err?.message || String(err)
7279
+ kind: "empty",
7280
+ reason: "Font binary is empty (0 bytes)."
7035
7281
  });
7282
+ } else {
7283
+ try {
7284
+ inspectTrueTypeFont(options.customFontBytes);
7285
+ normalFontBytes = options.customFontBytes;
7286
+ } catch (err) {
7287
+ failedFonts.push({
7288
+ index: failedFonts.length,
7289
+ kind: "format",
7290
+ reason: err?.message || String(err)
7291
+ });
7292
+ }
7036
7293
  }
7037
7294
  }
7038
- }
7039
- if (normalFontBytes && normalFontBytes.byteLength > 0) {
7040
- if (boldFontBytes) {
7041
- try {
7042
- inspectTrueTypeFont(boldFontBytes);
7043
- } catch {
7044
- boldFontBytes = void 0;
7295
+ if (!normalFontBytes && snapshot?.resourceBindings) {
7296
+ const fontBinding = Object.values(snapshot.resourceBindings).find(
7297
+ (b) => b.type === "font" && Boolean(b.dataUri)
7298
+ );
7299
+ if (fontBinding?.dataUri) {
7300
+ try {
7301
+ const decoded = dataUriToBytes(fontBinding.dataUri);
7302
+ if (decoded.byteLength === 0) {
7303
+ failedFonts.push({
7304
+ index: failedFonts.length,
7305
+ ...fontBinding.name ? { family: fontBinding.name } : {},
7306
+ kind: "empty",
7307
+ reason: "Font binary is empty (0 bytes)."
7308
+ });
7309
+ } else {
7310
+ inspectTrueTypeFont(decoded);
7311
+ normalFontBytes = decoded;
7312
+ }
7313
+ } catch (err) {
7314
+ failedFonts.push({
7315
+ index: failedFonts.length,
7316
+ ...fontBinding.name ? { family: fontBinding.name } : {},
7317
+ kind: "format",
7318
+ reason: err?.message || String(err)
7319
+ });
7320
+ }
7321
+ }
7322
+ }
7323
+ if (normalFontBytes && normalFontBytes.byteLength > 0) {
7324
+ if (boldFontBytes) {
7325
+ try {
7326
+ inspectTrueTypeFont(boldFontBytes);
7327
+ } catch {
7328
+ boldFontBytes = void 0;
7329
+ }
7045
7330
  }
7331
+ return {
7332
+ effectiveMode: "subset-ttf",
7333
+ normalFontBytes,
7334
+ boldFontBytes,
7335
+ hasExplicitRenderFonts: false
7336
+ };
7046
7337
  }
7047
- return { effectiveMode: "subset-ttf", normalFontBytes, boldFontBytes };
7048
7338
  }
7049
7339
  const fallbackPolicy = renderCfg?.fallback ?? "error";
7050
7340
  const detailSummary = failedFonts.length > 0 ? failedFonts.map(
7051
- (e) => `#${e.index}${e.family ? ` (${e.family})` : ""}${e.url ? ` [${e.url}]` : ""}: ${e.reason}`
7341
+ (e) => `#${e.index}${e.family ? ` (${e.family})` : ""}${e.weight ? ` [${e.weight}]` : ""}${e.url ? ` [${e.url}]` : ""}: ${e.reason}`
7052
7342
  ).join("; ") : "\u672A\u63D0\u4F9B\u53EF\u7528\u7684 TrueType (.ttf) \u5B57\u4F53\u5B57\u8282\u6216\u5730\u5740";
7053
7343
  if (fallbackPolicy === "raster-hd" || fallbackPolicy === "cid-vector") {
7054
7344
  renderCfg?.onWarning?.({
@@ -7056,7 +7346,7 @@ async function resolveRenderFontsForExport(snapshot, options) {
7056
7346
  message: `\u4E2D\u6587\u5B57\u4F53\u52A0\u8F7D\u5931\u8D25\uFF0C\u5DF2\u6309\u663E\u5F0F\u56DE\u9000\u7B56\u7565\u5207\u6362\u81F3 '${fallbackPolicy}'\uFF1A${detailSummary}`,
7057
7347
  details: { fallback: fallbackPolicy, failedFonts }
7058
7348
  });
7059
- return { effectiveMode: fallbackPolicy };
7349
+ return { effectiveMode: fallbackPolicy, hasExplicitRenderFonts };
7060
7350
  }
7061
7351
  throw new PdfRenderError(
7062
7352
  "FONT_UNAVAILABLE",
@@ -7067,8 +7357,11 @@ async function resolveRenderFontsForExport(snapshot, options) {
7067
7357
  function initVectorCjkEmbedState(pdfDoc, snapshot, effectiveData, options, preResolved) {
7068
7358
  const requested = preResolved?.effectiveMode ?? options?.render?.cjkTextMode ?? options?.cjkTextMode ?? "raster-hd";
7069
7359
  if (requested === "raster-hd") return null;
7070
- let resolvedFontBytes = preResolved?.normalFontBytes ?? options?.customFontBytes;
7071
- if ((!resolvedFontBytes || resolvedFontBytes.byteLength === 0) && !preResolved && snapshot?.resourceBindings) {
7360
+ const hasExplicitRenderFonts = Boolean(
7361
+ preResolved?.hasExplicitRenderFonts ?? Array.isArray(options?.render?.fonts)
7362
+ );
7363
+ let resolvedFontBytes = preResolved ? preResolved.normalFontBytes : hasExplicitRenderFonts ? void 0 : options?.customFontBytes;
7364
+ if ((!resolvedFontBytes || resolvedFontBytes.byteLength === 0) && !preResolved && !hasExplicitRenderFonts && snapshot?.resourceBindings) {
7072
7365
  const fontBinding = Object.values(snapshot.resourceBindings).find(
7073
7366
  (b) => b.type === "font" && Boolean(b.dataUri)
7074
7367
  );
@@ -7094,6 +7387,24 @@ function initVectorCjkEmbedState(pdfDoc, snapshot, effectiveData, options, preRe
7094
7387
  usedCodePoints,
7095
7388
  "UNVPDF+SubsetTTF"
7096
7389
  );
7390
+ let boldType0FontRef;
7391
+ let boldSubset;
7392
+ const boldBytes = preResolved ? preResolved.boldFontBytes : hasExplicitRenderFonts ? void 0 : options?.customBoldFontBytes;
7393
+ if (boldBytes && boldBytes.byteLength > 0) {
7394
+ if (boldBytes === resolvedFontBytes) {
7395
+ boldType0FontRef = type0FontRef2;
7396
+ boldSubset = subset;
7397
+ } else {
7398
+ const regBold = registerSubsetType0FontInDoc(
7399
+ pdfDoc,
7400
+ boldBytes,
7401
+ usedCodePoints,
7402
+ "UNVPDF+SubsetTTFBold"
7403
+ );
7404
+ boldType0FontRef = regBold.type0FontRef;
7405
+ boldSubset = regBold.subset;
7406
+ }
7407
+ }
7097
7408
  const missingItems = collectMissingGlyphsFromPdfUnit(
7098
7409
  snapshot,
7099
7410
  (cp) => (subset.codePointToGid[cp] ?? 0) > 0,
@@ -7101,7 +7412,7 @@ function initVectorCjkEmbedState(pdfDoc, snapshot, effectiveData, options, preRe
7101
7412
  formatPdfTableCell
7102
7413
  );
7103
7414
  if (missingItems.length > 0) {
7104
- const missingPolicy = options?.render?.missingGlyph ?? "warn";
7415
+ const missingPolicy = options?.render?.missingGlyph ?? (hasExplicitRenderFonts ? "error" : "warn");
7105
7416
  if (missingPolicy === "error") {
7106
7417
  const desc = missingItems.map(
7107
7418
  (m) => `${m.pageId ? `${m.pageId}/` : ""}${m.elementId}: ${m.chars.map((c, idx) => `'${c}' (${m.codePoints[idx]})`).join(", ")}`
@@ -7124,19 +7435,6 @@ function initVectorCjkEmbedState(pdfDoc, snapshot, effectiveData, options, preRe
7124
7435
  }
7125
7436
  }
7126
7437
  }
7127
- let boldType0FontRef;
7128
- let boldSubset;
7129
- const boldBytes = preResolved?.boldFontBytes ?? options?.customBoldFontBytes;
7130
- if (boldBytes && boldBytes.byteLength > 0) {
7131
- const regBold = registerSubsetType0FontInDoc(
7132
- pdfDoc,
7133
- boldBytes,
7134
- usedCodePoints,
7135
- "UNVPDF+SubsetTTFBold"
7136
- );
7137
- boldType0FontRef = regBold.type0FontRef;
7138
- boldSubset = regBold.subset;
7139
- }
7140
7438
  return {
7141
7439
  mode: "subset-ttf",
7142
7440
  type0FontRef: type0FontRef2,
@@ -7145,6 +7443,9 @@ function initVectorCjkEmbedState(pdfDoc, snapshot, effectiveData, options, preRe
7145
7443
  ...boldType0FontRef ? { boldType0FontRef, boldSubset, boldPageFontKeys: /* @__PURE__ */ new WeakMap() } : {}
7146
7444
  };
7147
7445
  }
7446
+ const usedCidCodePoints = collectUsedCodePointsFromPdfUnit(snapshot, effectiveData);
7447
+ const cidToUnicodeCmap = buildCidUtf16ToUnicodeCmapString(usedCidCodePoints);
7448
+ const cidToUnicodeRef = pdfDoc.context.register(pdfDoc.context.flateStream(cidToUnicodeCmap));
7148
7449
  const fontDescriptorRef = pdfDoc.context.register(
7149
7450
  pdfDoc.context.obj({
7150
7451
  Type: "FontDescriptor",
@@ -7178,7 +7479,8 @@ function initVectorCjkEmbedState(pdfDoc, snapshot, effectiveData, options, preRe
7178
7479
  Subtype: "Type0",
7179
7480
  BaseFont: "STSong-Light",
7180
7481
  Encoding: "UniGB-UTF16-H",
7181
- DescendantFonts: [cidFontRef]
7482
+ DescendantFonts: [cidFontRef],
7483
+ ToUnicode: cidToUnicodeRef
7182
7484
  })
7183
7485
  );
7184
7486
  return {
@@ -7329,7 +7631,7 @@ function encodeVectorCjkLineHex(line, state, overrideSubset) {
7329
7631
  }
7330
7632
  return hex;
7331
7633
  }
7332
- return toUtf16BeHex(line, true);
7634
+ return toUtf16BeHex(line.replace(/\uFEFF/g, ""), false);
7333
7635
  }
7334
7636
  function drawVectorCjkTextBox(page, pageHeight, text, left, top, width, height, style, state, noWrapSingleLine = false, colorType, overrideCharacterSpacing) {
7335
7637
  const wantBold = style?.fontWeight === "bold";
@@ -9433,6 +9735,12 @@ async function drawPageHeaderAndFooter(pdfDoc, pdfPage, pageWidth, pageHeight, c
9433
9735
  }
9434
9736
  }
9435
9737
  async function exportPdfBytes(snapshot, runtimeData, options) {
9738
+ const throwIfExportAborted = () => {
9739
+ if (options?.signal?.aborted) {
9740
+ throw typeof DOMException === "function" ? new DOMException("The operation was aborted.", "AbortError") : Object.assign(new Error("The operation was aborted."), { name: "AbortError" });
9741
+ }
9742
+ };
9743
+ throwIfExportAborted();
9436
9744
  const effectiveData = runtimeData ?? snapshot.metadata?.sampleData;
9437
9745
  const excludeBasePdf = Boolean(snapshot.metadata?.excludeBasePdfOnExport);
9438
9746
  const wmCfg = snapshot.metadata?.watermarkConfig;
@@ -9447,7 +9755,8 @@ async function exportPdfBytes(snapshot, runtimeData, options) {
9447
9755
  options?.accessibilityTagged ?? snapshot.accessibilityTagged ?? snapshot.metadata?.accessibilityTagged
9448
9756
  );
9449
9757
  const optimizeSize = Boolean(options?.optimizeSize);
9450
- const preResolvedFonts = await resolveRenderFontsForExport(snapshot, options);
9758
+ const preResolvedFonts = await resolveRenderFontsForExport(snapshot, effectiveData, options);
9759
+ throwIfExportAborted();
9451
9760
  const pdfDoc = await PDFDocument2.create();
9452
9761
  if (snapshot.metadata?.sanitized) {
9453
9762
  pdfDoc.setTitle("");
@@ -11709,7 +12018,9 @@ async function exportPdfBytes(snapshot, runtimeData, options) {
11709
12018
  if (optimizeSize) {
11710
12019
  pruneUnreferencedObjectsAndCompressStreams(pdfDoc);
11711
12020
  }
12021
+ throwIfExportAborted();
11712
12022
  const savedPdfBytes = interactiveForm && hasAnyAcroWidget ? await pdfDoc.save({ updateFieldAppearances: false }) : await pdfDoc.save();
12023
+ throwIfExportAborted();
11713
12024
  if (options?.diagnosticGridOverlay) {
11714
12025
  const gridOpts = typeof options.diagnosticGridOverlay === "object" ? options.diagnosticGridOverlay : void 0;
11715
12026
  return await overlayDiagnosticGridOnPdfBytes(savedPdfBytes, snapshot, gridOpts);
@@ -13145,7 +13456,7 @@ function buildCompositeTestGlyph(compGidA, compGidB) {
13145
13456
  view.setInt16(24, 80, false);
13146
13457
  return buf;
13147
13458
  }
13148
- 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";
13459
+ 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";
13149
13460
  function buildMinimalTestTrueTypeFont(extraCodePoints) {
13150
13461
  const cpSet = /* @__PURE__ */ new Set();
13151
13462
  for (let ascii = 32; ascii <= 126; ascii++) {
@@ -15954,6 +16265,12 @@ export {
15954
16265
  parseSvgToVectorCommands,
15955
16266
  drawVectorSvgOnPdfPage,
15956
16267
  PdfRenderError,
16268
+ DEFAULT_PDF_CJK_FONT_PACKAGE,
16269
+ DEFAULT_PDF_CJK_FONT_VERSION,
16270
+ DEFAULT_PDF_CJK_FONT_FAMILY,
16271
+ DEFAULT_PDF_CJK_FONT_FILES,
16272
+ createPdfCjkFontSources,
16273
+ computeFontUrlCacheKey,
15957
16274
  clearPdfFontUrlCache,
15958
16275
  resolveTemplateString,
15959
16276
  validatePdfTemplateVariables,
@@ -16020,4 +16337,4 @@ export {
16020
16337
  renderJsxToPdfmeTemplate,
16021
16338
  exportJsxToPdfBytes
16022
16339
  };
16023
- //# sourceMappingURL=chunk-4A226M74.js.map
16340
+ //# sourceMappingURL=chunk-EMSHTYYU.js.map