@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.
@@ -5566,7 +5566,48 @@ var PdfRenderError = class extends Error {
5566
5566
  if (extra?.missingGlyphs) this.missingGlyphs = extra.missingGlyphs;
5567
5567
  }
5568
5568
  };
5569
+ var DEFAULT_PDF_CJK_FONT_FAMILY = "Noto Sans SC";
5570
+ var DEFAULT_PDF_CJK_FONT_FILES = Object.freeze({
5571
+ normal: Object.freeze({
5572
+ file: "NotoSansSC-Regular.ttf",
5573
+ family: DEFAULT_PDF_CJK_FONT_FAMILY,
5574
+ weight: "normal",
5575
+ integrity: "sha384-WYgE+CQjxrXCFCynsUOYE86llni41IspZsiH2huo8yxlgR2GKNE5fzeurmHXRfIe"
5576
+ }),
5577
+ bold: Object.freeze({
5578
+ file: "NotoSansSC-Bold.ttf",
5579
+ family: DEFAULT_PDF_CJK_FONT_FAMILY,
5580
+ weight: "bold",
5581
+ integrity: "sha384-jI+dGvcJGGgO8RayO+x2LHDI85inVoe36tfbBKtSD6SQ0A8VKi5s+0lG+of4qB6j"
5582
+ })
5583
+ });
5569
5584
  var pdfFontUrlByteCache = /* @__PURE__ */ new Map();
5585
+ function computeFontUrlCacheKey(url, integrity) {
5586
+ return `${url}|${integrity ?? ""}`;
5587
+ }
5588
+ var PdfFontCandidateLoadError = class extends Error {
5589
+ constructor(kind, message, status) {
5590
+ super(message);
5591
+ this.name = "PdfFontCandidateLoadError";
5592
+ this.kind = kind;
5593
+ if (status !== void 0) {
5594
+ this.status = status;
5595
+ }
5596
+ }
5597
+ };
5598
+ function toFailedFontEntry(index, src, err) {
5599
+ const kind = err instanceof PdfFontCandidateLoadError ? err.kind : "format";
5600
+ const status = err instanceof PdfFontCandidateLoadError ? err.status : void 0;
5601
+ return {
5602
+ index,
5603
+ ...src.family !== void 0 ? { family: src.family } : {},
5604
+ ...src.weight !== void 0 ? { weight: src.weight } : {},
5605
+ ...src.url !== void 0 ? { url: src.url } : {},
5606
+ kind,
5607
+ ...status !== void 0 ? { status } : {},
5608
+ reason: err?.message || String(err)
5609
+ };
5610
+ }
5570
5611
  function bytesToBase64Standard(bytes) {
5571
5612
  if (typeof Buffer !== "undefined") {
5572
5613
  return Buffer.from(bytes).toString("base64");
@@ -5582,7 +5623,10 @@ async function verifyFontSubresourceIntegrity(bytes, integrity) {
5582
5623
  if (!trimmed) return;
5583
5624
  const m = trimmed.match(/^(sha256|sha384|sha512)-([A-Za-z0-9+/=_-]+)$/i);
5584
5625
  if (!m) {
5585
- throw new Error(`Unsupported integrity format '${trimmed}' (expected sha256-/sha384-/sha512-).`);
5626
+ throw new PdfFontCandidateLoadError(
5627
+ "integrity",
5628
+ `Unsupported integrity format '${trimmed}' (expected sha256-/sha384-/sha512-).`
5629
+ );
5586
5630
  }
5587
5631
  const algoMap = {
5588
5632
  sha256: "SHA-256",
@@ -5593,7 +5637,10 @@ async function verifyFontSubresourceIntegrity(bytes, integrity) {
5593
5637
  const expectedB64 = m[2].replace(/-/g, "+").replace(/_/g, "/");
5594
5638
  const subtle = globalThis.crypto?.subtle;
5595
5639
  if (!subtle) {
5596
- throw new Error("Web Crypto API is unavailable to verify font integrity.");
5640
+ throw new PdfFontCandidateLoadError(
5641
+ "integrity",
5642
+ "Web Crypto API is unavailable to verify font integrity."
5643
+ );
5597
5644
  }
5598
5645
  const digestBuf = await subtle.digest(
5599
5646
  algo,
@@ -5602,45 +5649,84 @@ async function verifyFontSubresourceIntegrity(bytes, integrity) {
5602
5649
  const actualB64 = bytesToBase64Standard(new Uint8Array(digestBuf)).replace(/=+$/, "");
5603
5650
  const normExpected = expectedB64.replace(/=+$/, "");
5604
5651
  if (actualB64 !== normExpected) {
5605
- throw new Error(`Font SRI integrity mismatch (${m[1]}).`);
5652
+ throw new PdfFontCandidateLoadError("integrity", `Font SRI integrity mismatch (${m[1]}).`);
5606
5653
  }
5607
5654
  }
5655
+ async function fetchFontBytesWithSri(url, options) {
5656
+ const cacheKey = computeFontUrlCacheKey(url, options?.integrity);
5657
+ const cached = pdfFontUrlByteCache.get(cacheKey);
5658
+ if (cached) {
5659
+ return cached;
5660
+ }
5661
+ const mergedInit = {
5662
+ ...options?.fetchInit ?? {},
5663
+ ...options?.credentials !== void 0 ? { credentials: options.credentials } : {}
5664
+ };
5665
+ const hasInitKeys = Object.keys(mergedInit).length > 0;
5666
+ let resp;
5667
+ try {
5668
+ resp = hasInitKeys ? await fetch(url, mergedInit) : await fetch(url);
5669
+ } catch (err) {
5670
+ throw new PdfFontCandidateLoadError(
5671
+ "network",
5672
+ `Network error fetching '${url}': ${err?.message || String(err)}`
5673
+ );
5674
+ }
5675
+ if (!resp.ok) {
5676
+ throw new PdfFontCandidateLoadError(
5677
+ "http",
5678
+ `HTTP ${resp.status} fetching '${url}'.`,
5679
+ resp.status
5680
+ );
5681
+ }
5682
+ let ab;
5683
+ try {
5684
+ ab = await resp.arrayBuffer();
5685
+ } catch (err) {
5686
+ throw new PdfFontCandidateLoadError(
5687
+ "network",
5688
+ `Network error reading font body for '${url}': ${err?.message || String(err)}`
5689
+ );
5690
+ }
5691
+ const rawBytes = new Uint8Array(ab);
5692
+ if (rawBytes.byteLength === 0) {
5693
+ throw new PdfFontCandidateLoadError("empty", `Font response for '${url}' is empty (0 bytes).`);
5694
+ }
5695
+ if (options?.integrity) {
5696
+ await verifyFontSubresourceIntegrity(rawBytes, options.integrity);
5697
+ }
5698
+ try {
5699
+ inspectTrueTypeFont(rawBytes);
5700
+ } catch (err) {
5701
+ throw new PdfFontCandidateLoadError("format", err?.message || String(err));
5702
+ }
5703
+ pdfFontUrlByteCache.set(cacheKey, rawBytes);
5704
+ return rawBytes;
5705
+ }
5608
5706
  async function loadSingleFontCandidate(src) {
5609
- let rawBytes;
5610
5707
  if (src.bytes != null) {
5611
- rawBytes = src.bytes instanceof Uint8Array ? src.bytes : new Uint8Array(src.bytes);
5708
+ const rawBytes = src.bytes instanceof Uint8Array ? src.bytes : new Uint8Array(src.bytes);
5709
+ if (rawBytes.byteLength === 0) {
5710
+ throw new PdfFontCandidateLoadError("empty", "Font binary is empty (0 bytes).");
5711
+ }
5612
5712
  if (src.integrity) {
5613
5713
  await verifyFontSubresourceIntegrity(rawBytes, src.integrity);
5614
5714
  }
5615
- } else if (src.url) {
5616
- const cacheKey = `${src.url}|${src.integrity ?? ""}`;
5617
- const cached = pdfFontUrlByteCache.get(cacheKey);
5618
- if (cached) {
5619
- rawBytes = cached;
5620
- } else {
5621
- let resp;
5622
- try {
5623
- resp = await fetch(src.url);
5624
- } catch (err) {
5625
- throw new Error(`Network error fetching '${src.url}': ${err?.message || String(err)}`);
5626
- }
5627
- if (!resp.ok) {
5628
- throw new Error(`HTTP ${resp.status} fetching '${src.url}'.`);
5629
- }
5630
- const ab = await resp.arrayBuffer();
5631
- rawBytes = new Uint8Array(ab);
5632
- if (src.integrity) {
5633
- await verifyFontSubresourceIntegrity(rawBytes, src.integrity);
5634
- }
5715
+ try {
5635
5716
  inspectTrueTypeFont(rawBytes);
5636
- pdfFontUrlByteCache.set(cacheKey, rawBytes);
5637
- return rawBytes;
5717
+ } catch (err) {
5718
+ throw new PdfFontCandidateLoadError("format", err?.message || String(err));
5638
5719
  }
5639
- } else {
5640
- throw new Error("Font source has neither bytes nor url.");
5720
+ return rawBytes;
5641
5721
  }
5642
- inspectTrueTypeFont(rawBytes);
5643
- return rawBytes;
5722
+ if (src.url && src.url.trim()) {
5723
+ return fetchFontBytesWithSri(src.url, {
5724
+ integrity: src.integrity,
5725
+ credentials: src.credentials,
5726
+ fetchInit: src.fetchInit
5727
+ });
5728
+ }
5729
+ throw new PdfFontCandidateLoadError("empty", "Font source has neither bytes nor url.");
5644
5730
  }
5645
5731
  function getByPath(data, path) {
5646
5732
  if (!data || !path) return void 0;
@@ -5822,94 +5908,253 @@ function registerSubsetType0FontInDoc(pdfDoc, fontBytes, usedCodePoints, fontTag
5822
5908
  );
5823
5909
  return { type0FontRef, subset };
5824
5910
  }
5825
- async function resolveRenderFontsForExport(snapshot, options) {
5911
+ function buildCidUtf16ToUnicodeCmapString(usedCodePoints) {
5912
+ const bmpHexList = [];
5913
+ const suppHexList = [];
5914
+ const seen = /* @__PURE__ */ new Set();
5915
+ for (const cp of usedCodePoints) {
5916
+ if (!Number.isInteger(cp) || cp <= 0 || cp === 65279 || seen.has(cp)) continue;
5917
+ seen.add(cp);
5918
+ const hex = toUtf16BeHex(String.fromCodePoint(cp), false);
5919
+ if (cp <= 65535) {
5920
+ bmpHexList.push(hex);
5921
+ } else {
5922
+ suppHexList.push(hex);
5923
+ }
5924
+ }
5925
+ bmpHexList.sort();
5926
+ suppHexList.sort();
5927
+ const bfBlocks = [];
5928
+ for (const list of [bmpHexList, suppHexList]) {
5929
+ for (let i = 0; i < list.length; i += 100) {
5930
+ const chunk = list.slice(i, i + 100);
5931
+ const lines = chunk.map((h) => `<${h}> <${h}>`).join("\n");
5932
+ bfBlocks.push(`${chunk.length} beginbfchar
5933
+ ${lines}
5934
+ endbfchar`);
5935
+ }
5936
+ }
5937
+ const codespaceLines = suppHexList.length > 0 ? ["2 begincodespacerange", "<0000> <FFFF>", "<D800DC00> <DBFFDFFF>", "endcodespacerange"] : ["1 begincodespacerange", "<0000> <FFFF>", "endcodespacerange"];
5938
+ return [
5939
+ "/CIDInit /ProcSet findresource begin",
5940
+ "12 dict begin",
5941
+ "begincmap",
5942
+ "/CIDSystemInfo << /Registry (Adobe) /Ordering (UCS) /Supplement 0 >> def",
5943
+ "/CMapName /Adobe-Identity-UCS def",
5944
+ "/CMapType 2 def",
5945
+ ...codespaceLines,
5946
+ ...bfBlocks,
5947
+ "endcmap",
5948
+ "CMapName currentdict /CMap defineresource pop",
5949
+ "end",
5950
+ "end"
5951
+ ].join("\n");
5952
+ }
5953
+ function detectUsedPdfTextWeights(snapshot, effectiveData) {
5954
+ let usesNormal = false;
5955
+ let usesBold = false;
5956
+ if (snapshot.metadata?.watermarkText && snapshot.metadata?.watermarkConfig?.enabled !== false) {
5957
+ usesNormal = true;
5958
+ }
5959
+ if (snapshot.metadata?.batesConfig?.enabled) {
5960
+ usesNormal = true;
5961
+ }
5962
+ const totalPages = snapshot.document.pageOrder.length;
5963
+ const startPageOffset = Math.max(1, Number(snapshot.metadata?.startPageNumber ?? 1) || 1);
5964
+ snapshot.document.pageOrder.forEach((pageId, pIdx) => {
5965
+ const pageCtx = { pageNumber: startPageOffset + pIdx, totalPages: startPageOffset + totalPages - 1 };
5966
+ const map = snapshot.editState.elementsByPage[pageId] ?? {};
5967
+ const order = snapshot.editState.elementOrderByPage[pageId] ?? Object.keys(map);
5968
+ for (const id of order) {
5969
+ const el = map[id];
5970
+ if (!el || el.hidden) continue;
5971
+ if (el.type === "text" /* TEXT */) {
5972
+ if (el.richSpans?.length) {
5973
+ for (const span of el.richSpans) {
5974
+ const t = resolveTemplateString(span.text, void 0, effectiveData, pageCtx);
5975
+ if (!t) continue;
5976
+ const spanIsBold = span.bold !== void 0 ? span.bold : el.style?.fontWeight === "bold";
5977
+ if (spanIsBold) usesBold = true;
5978
+ else usesNormal = true;
5979
+ }
5980
+ } else {
5981
+ const t = resolveTemplateString(el.content, el.fieldKey || el.bindingField, effectiveData, pageCtx);
5982
+ if (t) {
5983
+ if (el.style?.fontWeight === "bold") usesBold = true;
5984
+ else usesNormal = true;
5985
+ }
5986
+ }
5987
+ } else if (el.type === "list" /* LIST */) {
5988
+ if (el.items?.length) {
5989
+ if (el.style?.fontWeight === "bold") usesBold = true;
5990
+ else usesNormal = true;
5991
+ }
5992
+ } else if (el.type === "stamp" /* STAMP */) {
5993
+ if (el.primaryText) usesBold = true;
5994
+ if (el.secondaryText) usesNormal = true;
5995
+ } else if (el.type === "table" /* TABLE */) {
5996
+ if (el.showHead !== false && el.columns?.length) {
5997
+ if ((el.headerStyle?.fontWeight ?? "bold") === "bold") usesBold = true;
5998
+ else usesNormal = true;
5999
+ }
6000
+ if (el.rows && el.rows.length > 0 || Boolean(el.bindingField && effectiveData)) {
6001
+ if (el.bodyStyle?.fontWeight === "bold") usesBold = true;
6002
+ else usesNormal = true;
6003
+ }
6004
+ if (el.showPageSubtotal || el.showGrandTotal) {
6005
+ usesBold = true;
6006
+ }
6007
+ } 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 */) {
6008
+ usesNormal = true;
6009
+ }
6010
+ }
6011
+ });
6012
+ return { usesNormal, usesBold };
6013
+ }
6014
+ async function resolveRenderFontsForExport(snapshot, effectiveData, options) {
5826
6015
  const renderCfg = options?.render;
5827
- const hasHostFonts = Boolean(renderCfg?.fonts && renderCfg.fonts.length > 0);
6016
+ const hasExplicitRenderFonts = Array.isArray(renderCfg?.fonts);
5828
6017
  const explicitMode = renderCfg?.cjkTextMode ?? options?.cjkTextMode;
5829
- const requestedMode = explicitMode ?? (hasHostFonts ? "subset-ttf" : "raster-hd");
6018
+ const requestedMode = explicitMode ?? (hasExplicitRenderFonts ? "subset-ttf" : "raster-hd");
5830
6019
  if (requestedMode === "raster-hd" || requestedMode === "cid-vector") {
5831
- return { effectiveMode: requestedMode };
6020
+ return { effectiveMode: requestedMode, hasExplicitRenderFonts };
5832
6021
  }
5833
6022
  const failedFonts = [];
5834
6023
  let normalFontBytes;
5835
- let boldFontBytes = options?.customBoldFontBytes;
5836
- if (hasHostFonts && renderCfg?.fonts) {
6024
+ let boldFontBytes;
6025
+ if (hasExplicitRenderFonts && renderCfg?.fonts) {
5837
6026
  const normalCandidates = renderCfg.fonts.map((f, index) => ({ f, index })).filter(({ f }) => f.weight !== "bold");
5838
6027
  const boldCandidates = renderCfg.fonts.map((f, index) => ({ f, index })).filter(({ f }) => f.weight === "bold");
5839
- const primaryOrder = normalCandidates.length > 0 ? normalCandidates : boldCandidates;
5840
- for (const { f, index } of primaryOrder) {
5841
- try {
5842
- normalFontBytes = await loadSingleFontCandidate(f);
5843
- break;
5844
- } catch (err) {
5845
- failedFonts.push({
5846
- index,
5847
- family: f.family,
5848
- weight: f.weight,
5849
- url: f.url,
5850
- reason: err?.message || String(err)
5851
- });
6028
+ const { usesNormal, usesBold } = detectUsedPdfTextWeights(snapshot, effectiveData);
6029
+ let requiredWeightsFailed = renderCfg.fonts.length === 0;
6030
+ if (normalCandidates.length > 0 && boldCandidates.length === 0) {
6031
+ for (const { f, index } of normalCandidates) {
6032
+ try {
6033
+ normalFontBytes = await loadSingleFontCandidate(f);
6034
+ break;
6035
+ } catch (err) {
6036
+ failedFonts.push(toFailedFontEntry(index, f, err));
6037
+ }
5852
6038
  }
5853
- }
5854
- if (normalFontBytes && !boldFontBytes && boldCandidates.length > 0 && normalCandidates.length > 0) {
6039
+ if (!normalFontBytes) requiredWeightsFailed = true;
6040
+ } else if (normalCandidates.length === 0 && boldCandidates.length > 0) {
5855
6041
  for (const { f, index } of boldCandidates) {
5856
6042
  try {
5857
- boldFontBytes = await loadSingleFontCandidate(f);
6043
+ const loadedBold = await loadSingleFontCandidate(f);
6044
+ normalFontBytes = loadedBold;
6045
+ boldFontBytes = loadedBold;
5858
6046
  break;
5859
6047
  } catch (err) {
5860
- failedFonts.push({
5861
- index,
5862
- family: f.family,
5863
- weight: f.weight,
5864
- url: f.url,
5865
- reason: err?.message || String(err)
5866
- });
6048
+ failedFonts.push(toFailedFontEntry(index, f, err));
6049
+ }
6050
+ }
6051
+ if (!normalFontBytes) requiredWeightsFailed = true;
6052
+ } else if (normalCandidates.length > 0 && boldCandidates.length > 0) {
6053
+ const needNormal = usesNormal || !usesBold;
6054
+ const needBold = usesBold;
6055
+ if (needNormal) {
6056
+ for (const { f, index } of normalCandidates) {
6057
+ try {
6058
+ normalFontBytes = await loadSingleFontCandidate(f);
6059
+ break;
6060
+ } catch (err) {
6061
+ failedFonts.push(toFailedFontEntry(index, f, err));
6062
+ }
6063
+ }
6064
+ if (!normalFontBytes) requiredWeightsFailed = true;
6065
+ }
6066
+ if (!requiredWeightsFailed && needBold) {
6067
+ for (const { f, index } of boldCandidates) {
6068
+ try {
6069
+ boldFontBytes = await loadSingleFontCandidate(f);
6070
+ break;
6071
+ } catch (err) {
6072
+ failedFonts.push(toFailedFontEntry(index, f, err));
6073
+ }
6074
+ }
6075
+ if (!boldFontBytes) requiredWeightsFailed = true;
6076
+ if (!needNormal && boldFontBytes) {
6077
+ normalFontBytes = boldFontBytes;
5867
6078
  }
5868
6079
  }
5869
6080
  }
5870
- }
5871
- if (!normalFontBytes && options?.customFontBytes && options.customFontBytes.byteLength > 0) {
5872
- try {
5873
- inspectTrueTypeFont(options.customFontBytes);
5874
- normalFontBytes = options.customFontBytes;
5875
- } catch (err) {
5876
- failedFonts.push({
5877
- index: failedFonts.length,
5878
- reason: err?.message || String(err)
5879
- });
6081
+ if (!requiredWeightsFailed && normalFontBytes && normalFontBytes.byteLength > 0) {
6082
+ return {
6083
+ effectiveMode: "subset-ttf",
6084
+ normalFontBytes,
6085
+ boldFontBytes,
6086
+ hasExplicitRenderFonts: true
6087
+ };
5880
6088
  }
5881
- }
5882
- if (!normalFontBytes && snapshot?.resourceBindings) {
5883
- const fontBinding = Object.values(snapshot.resourceBindings).find(
5884
- (b) => b.type === "font" && Boolean(b.dataUri)
5885
- );
5886
- if (fontBinding?.dataUri) {
5887
- try {
5888
- const decoded = dataUriToBytes(fontBinding.dataUri);
5889
- inspectTrueTypeFont(decoded);
5890
- normalFontBytes = decoded;
5891
- } catch (err) {
6089
+ } else {
6090
+ boldFontBytes = options?.customBoldFontBytes;
6091
+ if (options?.customFontBytes !== void 0) {
6092
+ if (options.customFontBytes.byteLength === 0) {
5892
6093
  failedFonts.push({
5893
6094
  index: failedFonts.length,
5894
- family: fontBinding.name,
5895
- reason: err?.message || String(err)
6095
+ kind: "empty",
6096
+ reason: "Font binary is empty (0 bytes)."
5896
6097
  });
6098
+ } else {
6099
+ try {
6100
+ inspectTrueTypeFont(options.customFontBytes);
6101
+ normalFontBytes = options.customFontBytes;
6102
+ } catch (err) {
6103
+ failedFonts.push({
6104
+ index: failedFonts.length,
6105
+ kind: "format",
6106
+ reason: err?.message || String(err)
6107
+ });
6108
+ }
5897
6109
  }
5898
6110
  }
5899
- }
5900
- if (normalFontBytes && normalFontBytes.byteLength > 0) {
5901
- if (boldFontBytes) {
5902
- try {
5903
- inspectTrueTypeFont(boldFontBytes);
5904
- } catch {
5905
- boldFontBytes = void 0;
6111
+ if (!normalFontBytes && snapshot?.resourceBindings) {
6112
+ const fontBinding = Object.values(snapshot.resourceBindings).find(
6113
+ (b) => b.type === "font" && Boolean(b.dataUri)
6114
+ );
6115
+ if (fontBinding?.dataUri) {
6116
+ try {
6117
+ const decoded = dataUriToBytes(fontBinding.dataUri);
6118
+ if (decoded.byteLength === 0) {
6119
+ failedFonts.push({
6120
+ index: failedFonts.length,
6121
+ ...fontBinding.name ? { family: fontBinding.name } : {},
6122
+ kind: "empty",
6123
+ reason: "Font binary is empty (0 bytes)."
6124
+ });
6125
+ } else {
6126
+ inspectTrueTypeFont(decoded);
6127
+ normalFontBytes = decoded;
6128
+ }
6129
+ } catch (err) {
6130
+ failedFonts.push({
6131
+ index: failedFonts.length,
6132
+ ...fontBinding.name ? { family: fontBinding.name } : {},
6133
+ kind: "format",
6134
+ reason: err?.message || String(err)
6135
+ });
6136
+ }
6137
+ }
6138
+ }
6139
+ if (normalFontBytes && normalFontBytes.byteLength > 0) {
6140
+ if (boldFontBytes) {
6141
+ try {
6142
+ inspectTrueTypeFont(boldFontBytes);
6143
+ } catch {
6144
+ boldFontBytes = void 0;
6145
+ }
5906
6146
  }
6147
+ return {
6148
+ effectiveMode: "subset-ttf",
6149
+ normalFontBytes,
6150
+ boldFontBytes,
6151
+ hasExplicitRenderFonts: false
6152
+ };
5907
6153
  }
5908
- return { effectiveMode: "subset-ttf", normalFontBytes, boldFontBytes };
5909
6154
  }
5910
6155
  const fallbackPolicy = renderCfg?.fallback ?? "error";
5911
6156
  const detailSummary = failedFonts.length > 0 ? failedFonts.map(
5912
- (e) => `#${e.index}${e.family ? ` (${e.family})` : ""}${e.url ? ` [${e.url}]` : ""}: ${e.reason}`
6157
+ (e) => `#${e.index}${e.family ? ` (${e.family})` : ""}${e.weight ? ` [${e.weight}]` : ""}${e.url ? ` [${e.url}]` : ""}: ${e.reason}`
5913
6158
  ).join("; ") : "\u672A\u63D0\u4F9B\u53EF\u7528\u7684 TrueType (.ttf) \u5B57\u4F53\u5B57\u8282\u6216\u5730\u5740";
5914
6159
  if (fallbackPolicy === "raster-hd" || fallbackPolicy === "cid-vector") {
5915
6160
  renderCfg?.onWarning?.({
@@ -5917,7 +6162,7 @@ async function resolveRenderFontsForExport(snapshot, options) {
5917
6162
  message: `\u4E2D\u6587\u5B57\u4F53\u52A0\u8F7D\u5931\u8D25\uFF0C\u5DF2\u6309\u663E\u5F0F\u56DE\u9000\u7B56\u7565\u5207\u6362\u81F3 '${fallbackPolicy}'\uFF1A${detailSummary}`,
5918
6163
  details: { fallback: fallbackPolicy, failedFonts }
5919
6164
  });
5920
- return { effectiveMode: fallbackPolicy };
6165
+ return { effectiveMode: fallbackPolicy, hasExplicitRenderFonts };
5921
6166
  }
5922
6167
  throw new PdfRenderError(
5923
6168
  "FONT_UNAVAILABLE",
@@ -5928,8 +6173,11 @@ async function resolveRenderFontsForExport(snapshot, options) {
5928
6173
  function initVectorCjkEmbedState(pdfDoc, snapshot, effectiveData, options, preResolved) {
5929
6174
  const requested = preResolved?.effectiveMode ?? options?.render?.cjkTextMode ?? options?.cjkTextMode ?? "raster-hd";
5930
6175
  if (requested === "raster-hd") return null;
5931
- let resolvedFontBytes = preResolved?.normalFontBytes ?? options?.customFontBytes;
5932
- if ((!resolvedFontBytes || resolvedFontBytes.byteLength === 0) && !preResolved && snapshot?.resourceBindings) {
6176
+ const hasExplicitRenderFonts = Boolean(
6177
+ preResolved?.hasExplicitRenderFonts ?? Array.isArray(options?.render?.fonts)
6178
+ );
6179
+ let resolvedFontBytes = preResolved ? preResolved.normalFontBytes : hasExplicitRenderFonts ? void 0 : options?.customFontBytes;
6180
+ if ((!resolvedFontBytes || resolvedFontBytes.byteLength === 0) && !preResolved && !hasExplicitRenderFonts && snapshot?.resourceBindings) {
5933
6181
  const fontBinding = Object.values(snapshot.resourceBindings).find(
5934
6182
  (b) => b.type === "font" && Boolean(b.dataUri)
5935
6183
  );
@@ -5955,6 +6203,24 @@ function initVectorCjkEmbedState(pdfDoc, snapshot, effectiveData, options, preRe
5955
6203
  usedCodePoints,
5956
6204
  "UNVPDF+SubsetTTF"
5957
6205
  );
6206
+ let boldType0FontRef;
6207
+ let boldSubset;
6208
+ const boldBytes = preResolved ? preResolved.boldFontBytes : hasExplicitRenderFonts ? void 0 : options?.customBoldFontBytes;
6209
+ if (boldBytes && boldBytes.byteLength > 0) {
6210
+ if (boldBytes === resolvedFontBytes) {
6211
+ boldType0FontRef = type0FontRef2;
6212
+ boldSubset = subset;
6213
+ } else {
6214
+ const regBold = registerSubsetType0FontInDoc(
6215
+ pdfDoc,
6216
+ boldBytes,
6217
+ usedCodePoints,
6218
+ "UNVPDF+SubsetTTFBold"
6219
+ );
6220
+ boldType0FontRef = regBold.type0FontRef;
6221
+ boldSubset = regBold.subset;
6222
+ }
6223
+ }
5958
6224
  const missingItems = collectMissingGlyphsFromPdfUnit(
5959
6225
  snapshot,
5960
6226
  (cp) => (subset.codePointToGid[cp] ?? 0) > 0,
@@ -5962,7 +6228,7 @@ function initVectorCjkEmbedState(pdfDoc, snapshot, effectiveData, options, preRe
5962
6228
  formatPdfTableCell
5963
6229
  );
5964
6230
  if (missingItems.length > 0) {
5965
- const missingPolicy = options?.render?.missingGlyph ?? "warn";
6231
+ const missingPolicy = options?.render?.missingGlyph ?? (hasExplicitRenderFonts ? "error" : "warn");
5966
6232
  if (missingPolicy === "error") {
5967
6233
  const desc = missingItems.map(
5968
6234
  (m) => `${m.pageId ? `${m.pageId}/` : ""}${m.elementId}: ${m.chars.map((c, idx) => `'${c}' (${m.codePoints[idx]})`).join(", ")}`
@@ -5985,19 +6251,6 @@ function initVectorCjkEmbedState(pdfDoc, snapshot, effectiveData, options, preRe
5985
6251
  }
5986
6252
  }
5987
6253
  }
5988
- let boldType0FontRef;
5989
- let boldSubset;
5990
- const boldBytes = preResolved?.boldFontBytes ?? options?.customBoldFontBytes;
5991
- if (boldBytes && boldBytes.byteLength > 0) {
5992
- const regBold = registerSubsetType0FontInDoc(
5993
- pdfDoc,
5994
- boldBytes,
5995
- usedCodePoints,
5996
- "UNVPDF+SubsetTTFBold"
5997
- );
5998
- boldType0FontRef = regBold.type0FontRef;
5999
- boldSubset = regBold.subset;
6000
- }
6001
6254
  return {
6002
6255
  mode: "subset-ttf",
6003
6256
  type0FontRef: type0FontRef2,
@@ -6006,6 +6259,9 @@ function initVectorCjkEmbedState(pdfDoc, snapshot, effectiveData, options, preRe
6006
6259
  ...boldType0FontRef ? { boldType0FontRef, boldSubset, boldPageFontKeys: /* @__PURE__ */ new WeakMap() } : {}
6007
6260
  };
6008
6261
  }
6262
+ const usedCidCodePoints = collectUsedCodePointsFromPdfUnit(snapshot, effectiveData);
6263
+ const cidToUnicodeCmap = buildCidUtf16ToUnicodeCmapString(usedCidCodePoints);
6264
+ const cidToUnicodeRef = pdfDoc.context.register(pdfDoc.context.flateStream(cidToUnicodeCmap));
6009
6265
  const fontDescriptorRef = pdfDoc.context.register(
6010
6266
  pdfDoc.context.obj({
6011
6267
  Type: "FontDescriptor",
@@ -6039,7 +6295,8 @@ function initVectorCjkEmbedState(pdfDoc, snapshot, effectiveData, options, preRe
6039
6295
  Subtype: "Type0",
6040
6296
  BaseFont: "STSong-Light",
6041
6297
  Encoding: "UniGB-UTF16-H",
6042
- DescendantFonts: [cidFontRef]
6298
+ DescendantFonts: [cidFontRef],
6299
+ ToUnicode: cidToUnicodeRef
6043
6300
  })
6044
6301
  );
6045
6302
  return {
@@ -6190,7 +6447,7 @@ function encodeVectorCjkLineHex(line, state, overrideSubset) {
6190
6447
  }
6191
6448
  return hex;
6192
6449
  }
6193
- return toUtf16BeHex(line, true);
6450
+ return toUtf16BeHex(line.replace(/\uFEFF/g, ""), false);
6194
6451
  }
6195
6452
  function drawVectorCjkTextBox(page, pageHeight, text, left, top, width, height, style, state, noWrapSingleLine = false, colorType, overrideCharacterSpacing) {
6196
6453
  const wantBold = style?.fontWeight === "bold";
@@ -8223,6 +8480,12 @@ async function drawPageHeaderAndFooter(pdfDoc, pdfPage, pageWidth, pageHeight, c
8223
8480
  }
8224
8481
  }
8225
8482
  async function exportPdfBytes(snapshot, runtimeData, options) {
8483
+ const throwIfExportAborted = () => {
8484
+ if (options?.signal?.aborted) {
8485
+ throw typeof DOMException === "function" ? new DOMException("The operation was aborted.", "AbortError") : Object.assign(new Error("The operation was aborted."), { name: "AbortError" });
8486
+ }
8487
+ };
8488
+ throwIfExportAborted();
8226
8489
  const effectiveData = runtimeData ?? snapshot.metadata?.sampleData;
8227
8490
  const excludeBasePdf = Boolean(snapshot.metadata?.excludeBasePdfOnExport);
8228
8491
  const wmCfg = snapshot.metadata?.watermarkConfig;
@@ -8237,7 +8500,8 @@ async function exportPdfBytes(snapshot, runtimeData, options) {
8237
8500
  options?.accessibilityTagged ?? snapshot.accessibilityTagged ?? snapshot.metadata?.accessibilityTagged
8238
8501
  );
8239
8502
  const optimizeSize = Boolean(options?.optimizeSize);
8240
- const preResolvedFonts = await resolveRenderFontsForExport(snapshot, options);
8503
+ const preResolvedFonts = await resolveRenderFontsForExport(snapshot, effectiveData, options);
8504
+ throwIfExportAborted();
8241
8505
  const pdfDoc = await import_pdf_lib3.PDFDocument.create();
8242
8506
  if (snapshot.metadata?.sanitized) {
8243
8507
  pdfDoc.setTitle("");
@@ -10499,7 +10763,9 @@ async function exportPdfBytes(snapshot, runtimeData, options) {
10499
10763
  if (optimizeSize) {
10500
10764
  pruneUnreferencedObjectsAndCompressStreams(pdfDoc);
10501
10765
  }
10766
+ throwIfExportAborted();
10502
10767
  const savedPdfBytes = interactiveForm && hasAnyAcroWidget ? await pdfDoc.save({ updateFieldAppearances: false }) : await pdfDoc.save();
10768
+ throwIfExportAborted();
10503
10769
  if (options?.diagnosticGridOverlay) {
10504
10770
  const gridOpts = typeof options.diagnosticGridOverlay === "object" ? options.diagnosticGridOverlay : void 0;
10505
10771
  return await overlayDiagnosticGridOnPdfBytes(savedPdfBytes, snapshot, gridOpts);