@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.
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,
@@ -73,6 +77,7 @@ __export(src_exports, {
73
77
  PDF_JSX_ELEMENT_SYMBOL: () => PDF_JSX_ELEMENT_SYMBOL,
74
78
  PDF_JSX_FRAGMENT_SYMBOL: () => PDF_JSX_FRAGMENT_SYMBOL,
75
79
  PDF_PAGE_PRESETS: () => PDF_PAGE_PRESETS,
80
+ PDF_S1_S7_FIDELITY_EXPECTATIONS: () => PDF_S1_S7_FIDELITY_EXPECTATIONS,
76
81
  PDF_TABLE_THEME_PRESETS: () => PDF_TABLE_THEME_PRESETS,
77
82
  PT_PER_MM: () => PT_PER_MM,
78
83
  Page: () => Page,
@@ -155,6 +160,7 @@ __export(src_exports, {
155
160
  computeExifTransformMatrix: () => computeExifTransformMatrix,
156
161
  computeExpandedTextHeightMm: () => computeExpandedTextHeightMm,
157
162
  computeExpandedTextHeightPt: () => computeExpandedTextHeightPt,
163
+ computeFontUrlCacheKey: () => computeFontUrlCacheKey,
158
164
  computeImageFitPlacement: () => computeImageFitPlacement,
159
165
  computePasteCascadeOffset: () => computePasteCascadeOffset,
160
166
  computePdfPayloadDigest: () => computePdfPayloadDigest,
@@ -171,7 +177,10 @@ __export(src_exports, {
171
177
  createDefaultElement: () => createDefaultElement,
172
178
  createDefaultPdfUnitData: () => createDefaultPdfUnitData,
173
179
  createHttpSilentPrintAdapter: () => createHttpSilentPrintAdapter,
180
+ createPdfAbortError: () => createPdfAbortError,
181
+ createPdfBrowserFidelityExpectations: () => createPdfBrowserFidelityExpectations,
174
182
  createPdfBrowserFidelitySamples: () => createPdfBrowserFidelitySamples,
183
+ createPdfCjkFontSources: () => createPdfCjkFontSources,
175
184
  createPdfJsxNode: () => createPdfJsxNode,
176
185
  detectCJKCharacters: () => detectCJKCharacters,
177
186
  detectCJKInPdfInputs: () => detectCJKInPdfInputs,
@@ -207,6 +216,7 @@ __export(src_exports, {
207
216
  exportPdfBytes: () => exportPdfBytes,
208
217
  exportPdfToDocxSnapshot: () => exportPdfToDocxSnapshot,
209
218
  exportPdfToWorkbookSnapshot: () => exportPdfToWorkbookSnapshot,
219
+ exportPdfWithTarget: () => exportPdfWithTarget,
210
220
  exportSignedPdfWithAuditSeal: () => exportSignedPdfWithAuditSeal,
211
221
  exportToPdfmeTemplate: () => exportToPdfmeTemplate,
212
222
  extractAcroFormValuesFromPdfBytes: () => extractAcroFormValuesFromPdfBytes,
@@ -9588,10 +9598,96 @@ var PdfRenderError = class extends Error {
9588
9598
  if (extra?.missingGlyphs) this.missingGlyphs = extra.missingGlyphs;
9589
9599
  }
9590
9600
  };
9601
+ var DEFAULT_PDF_CJK_FONT_PACKAGE = "@yudaocode/univer-pdf-fonts";
9602
+ var DEFAULT_PDF_CJK_FONT_VERSION = "1.0.0";
9603
+ var DEFAULT_PDF_CJK_FONT_FAMILY = "Noto Sans SC";
9604
+ var DEFAULT_PDF_CJK_FONT_FILES = Object.freeze({
9605
+ normal: Object.freeze({
9606
+ file: "NotoSansSC-Regular.ttf",
9607
+ family: DEFAULT_PDF_CJK_FONT_FAMILY,
9608
+ weight: "normal",
9609
+ integrity: "sha384-WYgE+CQjxrXCFCynsUOYE86llni41IspZsiH2huo8yxlgR2GKNE5fzeurmHXRfIe"
9610
+ }),
9611
+ bold: Object.freeze({
9612
+ file: "NotoSansSC-Bold.ttf",
9613
+ family: DEFAULT_PDF_CJK_FONT_FAMILY,
9614
+ weight: "bold",
9615
+ integrity: "sha384-jI+dGvcJGGgO8RayO+x2LHDI85inVoe36tfbBKtSD6SQ0A8VKi5s+0lG+of4qB6j"
9616
+ })
9617
+ });
9618
+ function createPdfCjkFontSources(options) {
9619
+ const ver = (options?.version ?? DEFAULT_PDF_CJK_FONT_VERSION).trim() || DEFAULT_PDF_CJK_FONT_VERSION;
9620
+ const family = options?.family ?? DEFAULT_PDF_CJK_FONT_FAMILY;
9621
+ const rawBase = (options?.baseUrl ?? `https://cdn.jsdmirror.com/npm/${DEFAULT_PDF_CJK_FONT_PACKAGE}@${ver}/fonts`).replace(/\{version\}/g, ver);
9622
+ const cleanBase = rawBase.replace(/\/+$/, "");
9623
+ let requestedWeights;
9624
+ if (options?.weights === "both") {
9625
+ requestedWeights = ["normal", "bold"];
9626
+ } else if (options?.weights === "normal" || options?.weights === "bold") {
9627
+ requestedWeights = [options.weights];
9628
+ } else if (Array.isArray(options?.weights) && options.weights.length > 0) {
9629
+ requestedWeights = [];
9630
+ for (const w of options.weights) {
9631
+ if ((w === "normal" || w === "bold") && !requestedWeights.includes(w)) {
9632
+ requestedWeights.push(w);
9633
+ }
9634
+ }
9635
+ if (requestedWeights.length === 0) {
9636
+ requestedWeights = ["normal"];
9637
+ }
9638
+ } else {
9639
+ requestedWeights = ["normal"];
9640
+ }
9641
+ return requestedWeights.map((weight) => {
9642
+ const preset = DEFAULT_PDF_CJK_FONT_FILES[weight];
9643
+ let integrity;
9644
+ if (options?.integrity && typeof options.integrity === "object") {
9645
+ integrity = options.integrity[weight];
9646
+ } else if (options?.integrity === false) {
9647
+ integrity = void 0;
9648
+ } else if (options?.integrity === true || options?.integrity === void 0 && ver === DEFAULT_PDF_CJK_FONT_VERSION) {
9649
+ integrity = preset.integrity;
9650
+ }
9651
+ return {
9652
+ url: `${cleanBase}/${preset.file}`,
9653
+ family,
9654
+ weight,
9655
+ ...integrity ? { integrity } : {},
9656
+ ...options?.credentials !== void 0 ? { credentials: options.credentials } : {},
9657
+ ...options?.fetchInit !== void 0 ? { fetchInit: options.fetchInit } : {}
9658
+ };
9659
+ });
9660
+ }
9591
9661
  var pdfFontUrlByteCache = /* @__PURE__ */ new Map();
9662
+ function computeFontUrlCacheKey(url, integrity) {
9663
+ return `${url}|${integrity ?? ""}`;
9664
+ }
9592
9665
  function clearPdfFontUrlCache() {
9593
9666
  pdfFontUrlByteCache.clear();
9594
9667
  }
9668
+ var PdfFontCandidateLoadError = class extends Error {
9669
+ constructor(kind, message, status) {
9670
+ super(message);
9671
+ this.name = "PdfFontCandidateLoadError";
9672
+ this.kind = kind;
9673
+ if (status !== void 0) {
9674
+ this.status = status;
9675
+ }
9676
+ }
9677
+ };
9678
+ function toFailedFontEntry(index, src, err) {
9679
+ const kind = err instanceof PdfFontCandidateLoadError ? err.kind : "format";
9680
+ const status = err instanceof PdfFontCandidateLoadError ? err.status : void 0;
9681
+ return {
9682
+ index,
9683
+ ...src.family !== void 0 ? { family: src.family } : {},
9684
+ ...src.weight !== void 0 ? { weight: src.weight } : {},
9685
+ ...src.url !== void 0 ? { url: src.url } : {},
9686
+ kind,
9687
+ ...status !== void 0 ? { status } : {},
9688
+ reason: err?.message || String(err)
9689
+ };
9690
+ }
9595
9691
  function bytesToBase64Standard(bytes) {
9596
9692
  if (typeof Buffer !== "undefined") {
9597
9693
  return Buffer.from(bytes).toString("base64");
@@ -9607,7 +9703,10 @@ async function verifyFontSubresourceIntegrity(bytes, integrity) {
9607
9703
  if (!trimmed) return;
9608
9704
  const m = trimmed.match(/^(sha256|sha384|sha512)-([A-Za-z0-9+/=_-]+)$/i);
9609
9705
  if (!m) {
9610
- throw new Error(`Unsupported integrity format '${trimmed}' (expected sha256-/sha384-/sha512-).`);
9706
+ throw new PdfFontCandidateLoadError(
9707
+ "integrity",
9708
+ `Unsupported integrity format '${trimmed}' (expected sha256-/sha384-/sha512-).`
9709
+ );
9611
9710
  }
9612
9711
  const algoMap = {
9613
9712
  sha256: "SHA-256",
@@ -9618,7 +9717,10 @@ async function verifyFontSubresourceIntegrity(bytes, integrity) {
9618
9717
  const expectedB64 = m[2].replace(/-/g, "+").replace(/_/g, "/");
9619
9718
  const subtle = globalThis.crypto?.subtle;
9620
9719
  if (!subtle) {
9621
- throw new Error("Web Crypto API is unavailable to verify font integrity.");
9720
+ throw new PdfFontCandidateLoadError(
9721
+ "integrity",
9722
+ "Web Crypto API is unavailable to verify font integrity."
9723
+ );
9622
9724
  }
9623
9725
  const digestBuf = await subtle.digest(
9624
9726
  algo,
@@ -9627,45 +9729,84 @@ async function verifyFontSubresourceIntegrity(bytes, integrity) {
9627
9729
  const actualB64 = bytesToBase64Standard(new Uint8Array(digestBuf)).replace(/=+$/, "");
9628
9730
  const normExpected = expectedB64.replace(/=+$/, "");
9629
9731
  if (actualB64 !== normExpected) {
9630
- throw new Error(`Font SRI integrity mismatch (${m[1]}).`);
9732
+ throw new PdfFontCandidateLoadError("integrity", `Font SRI integrity mismatch (${m[1]}).`);
9631
9733
  }
9632
9734
  }
9735
+ async function fetchFontBytesWithSri(url, options) {
9736
+ const cacheKey = computeFontUrlCacheKey(url, options?.integrity);
9737
+ const cached = pdfFontUrlByteCache.get(cacheKey);
9738
+ if (cached) {
9739
+ return cached;
9740
+ }
9741
+ const mergedInit = {
9742
+ ...options?.fetchInit ?? {},
9743
+ ...options?.credentials !== void 0 ? { credentials: options.credentials } : {}
9744
+ };
9745
+ const hasInitKeys = Object.keys(mergedInit).length > 0;
9746
+ let resp;
9747
+ try {
9748
+ resp = hasInitKeys ? await fetch(url, mergedInit) : await fetch(url);
9749
+ } catch (err) {
9750
+ throw new PdfFontCandidateLoadError(
9751
+ "network",
9752
+ `Network error fetching '${url}': ${err?.message || String(err)}`
9753
+ );
9754
+ }
9755
+ if (!resp.ok) {
9756
+ throw new PdfFontCandidateLoadError(
9757
+ "http",
9758
+ `HTTP ${resp.status} fetching '${url}'.`,
9759
+ resp.status
9760
+ );
9761
+ }
9762
+ let ab;
9763
+ try {
9764
+ ab = await resp.arrayBuffer();
9765
+ } catch (err) {
9766
+ throw new PdfFontCandidateLoadError(
9767
+ "network",
9768
+ `Network error reading font body for '${url}': ${err?.message || String(err)}`
9769
+ );
9770
+ }
9771
+ const rawBytes = new Uint8Array(ab);
9772
+ if (rawBytes.byteLength === 0) {
9773
+ throw new PdfFontCandidateLoadError("empty", `Font response for '${url}' is empty (0 bytes).`);
9774
+ }
9775
+ if (options?.integrity) {
9776
+ await verifyFontSubresourceIntegrity(rawBytes, options.integrity);
9777
+ }
9778
+ try {
9779
+ inspectTrueTypeFont(rawBytes);
9780
+ } catch (err) {
9781
+ throw new PdfFontCandidateLoadError("format", err?.message || String(err));
9782
+ }
9783
+ pdfFontUrlByteCache.set(cacheKey, rawBytes);
9784
+ return rawBytes;
9785
+ }
9633
9786
  async function loadSingleFontCandidate(src) {
9634
- let rawBytes;
9635
9787
  if (src.bytes != null) {
9636
- rawBytes = src.bytes instanceof Uint8Array ? src.bytes : new Uint8Array(src.bytes);
9788
+ const rawBytes = src.bytes instanceof Uint8Array ? src.bytes : new Uint8Array(src.bytes);
9789
+ if (rawBytes.byteLength === 0) {
9790
+ throw new PdfFontCandidateLoadError("empty", "Font binary is empty (0 bytes).");
9791
+ }
9637
9792
  if (src.integrity) {
9638
9793
  await verifyFontSubresourceIntegrity(rawBytes, src.integrity);
9639
9794
  }
9640
- } else if (src.url) {
9641
- const cacheKey = `${src.url}|${src.integrity ?? ""}`;
9642
- const cached = pdfFontUrlByteCache.get(cacheKey);
9643
- if (cached) {
9644
- rawBytes = cached;
9645
- } else {
9646
- let resp;
9647
- try {
9648
- resp = await fetch(src.url);
9649
- } catch (err) {
9650
- throw new Error(`Network error fetching '${src.url}': ${err?.message || String(err)}`);
9651
- }
9652
- if (!resp.ok) {
9653
- throw new Error(`HTTP ${resp.status} fetching '${src.url}'.`);
9654
- }
9655
- const ab = await resp.arrayBuffer();
9656
- rawBytes = new Uint8Array(ab);
9657
- if (src.integrity) {
9658
- await verifyFontSubresourceIntegrity(rawBytes, src.integrity);
9659
- }
9795
+ try {
9660
9796
  inspectTrueTypeFont(rawBytes);
9661
- pdfFontUrlByteCache.set(cacheKey, rawBytes);
9662
- return rawBytes;
9797
+ } catch (err) {
9798
+ throw new PdfFontCandidateLoadError("format", err?.message || String(err));
9663
9799
  }
9664
- } else {
9665
- throw new Error("Font source has neither bytes nor url.");
9800
+ return rawBytes;
9666
9801
  }
9667
- inspectTrueTypeFont(rawBytes);
9668
- return rawBytes;
9802
+ if (src.url && src.url.trim()) {
9803
+ return fetchFontBytesWithSri(src.url, {
9804
+ integrity: src.integrity,
9805
+ credentials: src.credentials,
9806
+ fetchInit: src.fetchInit
9807
+ });
9808
+ }
9809
+ throw new PdfFontCandidateLoadError("empty", "Font source has neither bytes nor url.");
9669
9810
  }
9670
9811
  function getByPath(data, path) {
9671
9812
  if (!data || !path) return void 0;
@@ -9923,94 +10064,253 @@ function registerSubsetType0FontInDoc(pdfDoc, fontBytes, usedCodePoints, fontTag
9923
10064
  );
9924
10065
  return { type0FontRef, subset };
9925
10066
  }
9926
- async function resolveRenderFontsForExport(snapshot, options) {
10067
+ function buildCidUtf16ToUnicodeCmapString(usedCodePoints) {
10068
+ const bmpHexList = [];
10069
+ const suppHexList = [];
10070
+ const seen = /* @__PURE__ */ new Set();
10071
+ for (const cp of usedCodePoints) {
10072
+ if (!Number.isInteger(cp) || cp <= 0 || cp === 65279 || seen.has(cp)) continue;
10073
+ seen.add(cp);
10074
+ const hex = toUtf16BeHex(String.fromCodePoint(cp), false);
10075
+ if (cp <= 65535) {
10076
+ bmpHexList.push(hex);
10077
+ } else {
10078
+ suppHexList.push(hex);
10079
+ }
10080
+ }
10081
+ bmpHexList.sort();
10082
+ suppHexList.sort();
10083
+ const bfBlocks = [];
10084
+ for (const list of [bmpHexList, suppHexList]) {
10085
+ for (let i = 0; i < list.length; i += 100) {
10086
+ const chunk = list.slice(i, i + 100);
10087
+ const lines = chunk.map((h) => `<${h}> <${h}>`).join("\n");
10088
+ bfBlocks.push(`${chunk.length} beginbfchar
10089
+ ${lines}
10090
+ endbfchar`);
10091
+ }
10092
+ }
10093
+ const codespaceLines = suppHexList.length > 0 ? ["2 begincodespacerange", "<0000> <FFFF>", "<D800DC00> <DBFFDFFF>", "endcodespacerange"] : ["1 begincodespacerange", "<0000> <FFFF>", "endcodespacerange"];
10094
+ return [
10095
+ "/CIDInit /ProcSet findresource begin",
10096
+ "12 dict begin",
10097
+ "begincmap",
10098
+ "/CIDSystemInfo << /Registry (Adobe) /Ordering (UCS) /Supplement 0 >> def",
10099
+ "/CMapName /Adobe-Identity-UCS def",
10100
+ "/CMapType 2 def",
10101
+ ...codespaceLines,
10102
+ ...bfBlocks,
10103
+ "endcmap",
10104
+ "CMapName currentdict /CMap defineresource pop",
10105
+ "end",
10106
+ "end"
10107
+ ].join("\n");
10108
+ }
10109
+ function detectUsedPdfTextWeights(snapshot, effectiveData) {
10110
+ let usesNormal = false;
10111
+ let usesBold = false;
10112
+ if (snapshot.metadata?.watermarkText && snapshot.metadata?.watermarkConfig?.enabled !== false) {
10113
+ usesNormal = true;
10114
+ }
10115
+ if (snapshot.metadata?.batesConfig?.enabled) {
10116
+ usesNormal = true;
10117
+ }
10118
+ const totalPages = snapshot.document.pageOrder.length;
10119
+ const startPageOffset = Math.max(1, Number(snapshot.metadata?.startPageNumber ?? 1) || 1);
10120
+ snapshot.document.pageOrder.forEach((pageId, pIdx) => {
10121
+ const pageCtx = { pageNumber: startPageOffset + pIdx, totalPages: startPageOffset + totalPages - 1 };
10122
+ const map = snapshot.editState.elementsByPage[pageId] ?? {};
10123
+ const order = snapshot.editState.elementOrderByPage[pageId] ?? Object.keys(map);
10124
+ for (const id of order) {
10125
+ const el = map[id];
10126
+ if (!el || el.hidden) continue;
10127
+ if (el.type === "text" /* TEXT */) {
10128
+ if (el.richSpans?.length) {
10129
+ for (const span of el.richSpans) {
10130
+ const t = resolveTemplateString(span.text, void 0, effectiveData, pageCtx);
10131
+ if (!t) continue;
10132
+ const spanIsBold = span.bold !== void 0 ? span.bold : el.style?.fontWeight === "bold";
10133
+ if (spanIsBold) usesBold = true;
10134
+ else usesNormal = true;
10135
+ }
10136
+ } else {
10137
+ const t = resolveTemplateString(el.content, el.fieldKey || el.bindingField, effectiveData, pageCtx);
10138
+ if (t) {
10139
+ if (el.style?.fontWeight === "bold") usesBold = true;
10140
+ else usesNormal = true;
10141
+ }
10142
+ }
10143
+ } else if (el.type === "list" /* LIST */) {
10144
+ if (el.items?.length) {
10145
+ if (el.style?.fontWeight === "bold") usesBold = true;
10146
+ else usesNormal = true;
10147
+ }
10148
+ } else if (el.type === "stamp" /* STAMP */) {
10149
+ if (el.primaryText) usesBold = true;
10150
+ if (el.secondaryText) usesNormal = true;
10151
+ } else if (el.type === "table" /* TABLE */) {
10152
+ if (el.showHead !== false && el.columns?.length) {
10153
+ if ((el.headerStyle?.fontWeight ?? "bold") === "bold") usesBold = true;
10154
+ else usesNormal = true;
10155
+ }
10156
+ if (el.rows && el.rows.length > 0 || Boolean(el.bindingField && effectiveData)) {
10157
+ if (el.bodyStyle?.fontWeight === "bold") usesBold = true;
10158
+ else usesNormal = true;
10159
+ }
10160
+ if (el.showPageSubtotal || el.showGrandTotal) {
10161
+ usesBold = true;
10162
+ }
10163
+ } 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 */) {
10164
+ usesNormal = true;
10165
+ }
10166
+ }
10167
+ });
10168
+ return { usesNormal, usesBold };
10169
+ }
10170
+ async function resolveRenderFontsForExport(snapshot, effectiveData, options) {
9927
10171
  const renderCfg = options?.render;
9928
- const hasHostFonts = Boolean(renderCfg?.fonts && renderCfg.fonts.length > 0);
10172
+ const hasExplicitRenderFonts = Array.isArray(renderCfg?.fonts);
9929
10173
  const explicitMode = renderCfg?.cjkTextMode ?? options?.cjkTextMode;
9930
- const requestedMode = explicitMode ?? (hasHostFonts ? "subset-ttf" : "raster-hd");
10174
+ const requestedMode = explicitMode ?? (hasExplicitRenderFonts ? "subset-ttf" : "raster-hd");
9931
10175
  if (requestedMode === "raster-hd" || requestedMode === "cid-vector") {
9932
- return { effectiveMode: requestedMode };
10176
+ return { effectiveMode: requestedMode, hasExplicitRenderFonts };
9933
10177
  }
9934
10178
  const failedFonts = [];
9935
10179
  let normalFontBytes;
9936
- let boldFontBytes = options?.customBoldFontBytes;
9937
- if (hasHostFonts && renderCfg?.fonts) {
10180
+ let boldFontBytes;
10181
+ if (hasExplicitRenderFonts && renderCfg?.fonts) {
9938
10182
  const normalCandidates = renderCfg.fonts.map((f, index) => ({ f, index })).filter(({ f }) => f.weight !== "bold");
9939
10183
  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
- });
10184
+ const { usesNormal, usesBold } = detectUsedPdfTextWeights(snapshot, effectiveData);
10185
+ let requiredWeightsFailed = renderCfg.fonts.length === 0;
10186
+ if (normalCandidates.length > 0 && boldCandidates.length === 0) {
10187
+ for (const { f, index } of normalCandidates) {
10188
+ try {
10189
+ normalFontBytes = await loadSingleFontCandidate(f);
10190
+ break;
10191
+ } catch (err) {
10192
+ failedFonts.push(toFailedFontEntry(index, f, err));
10193
+ }
9953
10194
  }
9954
- }
9955
- if (normalFontBytes && !boldFontBytes && boldCandidates.length > 0 && normalCandidates.length > 0) {
10195
+ if (!normalFontBytes) requiredWeightsFailed = true;
10196
+ } else if (normalCandidates.length === 0 && boldCandidates.length > 0) {
9956
10197
  for (const { f, index } of boldCandidates) {
9957
10198
  try {
9958
- boldFontBytes = await loadSingleFontCandidate(f);
10199
+ const loadedBold = await loadSingleFontCandidate(f);
10200
+ normalFontBytes = loadedBold;
10201
+ boldFontBytes = loadedBold;
9959
10202
  break;
9960
10203
  } catch (err) {
9961
- failedFonts.push({
9962
- index,
9963
- family: f.family,
9964
- weight: f.weight,
9965
- url: f.url,
9966
- reason: err?.message || String(err)
9967
- });
10204
+ failedFonts.push(toFailedFontEntry(index, f, err));
10205
+ }
10206
+ }
10207
+ if (!normalFontBytes) requiredWeightsFailed = true;
10208
+ } else if (normalCandidates.length > 0 && boldCandidates.length > 0) {
10209
+ const needNormal = usesNormal || !usesBold;
10210
+ const needBold = usesBold;
10211
+ if (needNormal) {
10212
+ for (const { f, index } of normalCandidates) {
10213
+ try {
10214
+ normalFontBytes = await loadSingleFontCandidate(f);
10215
+ break;
10216
+ } catch (err) {
10217
+ failedFonts.push(toFailedFontEntry(index, f, err));
10218
+ }
10219
+ }
10220
+ if (!normalFontBytes) requiredWeightsFailed = true;
10221
+ }
10222
+ if (!requiredWeightsFailed && needBold) {
10223
+ for (const { f, index } of boldCandidates) {
10224
+ try {
10225
+ boldFontBytes = await loadSingleFontCandidate(f);
10226
+ break;
10227
+ } catch (err) {
10228
+ failedFonts.push(toFailedFontEntry(index, f, err));
10229
+ }
10230
+ }
10231
+ if (!boldFontBytes) requiredWeightsFailed = true;
10232
+ if (!needNormal && boldFontBytes) {
10233
+ normalFontBytes = boldFontBytes;
9968
10234
  }
9969
10235
  }
9970
10236
  }
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
- });
10237
+ if (!requiredWeightsFailed && normalFontBytes && normalFontBytes.byteLength > 0) {
10238
+ return {
10239
+ effectiveMode: "subset-ttf",
10240
+ normalFontBytes,
10241
+ boldFontBytes,
10242
+ hasExplicitRenderFonts: true
10243
+ };
9981
10244
  }
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) {
9988
- try {
9989
- const decoded = dataUriToBytes(fontBinding.dataUri);
9990
- inspectTrueTypeFont(decoded);
9991
- normalFontBytes = decoded;
9992
- } catch (err) {
10245
+ } else {
10246
+ boldFontBytes = options?.customBoldFontBytes;
10247
+ if (options?.customFontBytes !== void 0) {
10248
+ if (options.customFontBytes.byteLength === 0) {
9993
10249
  failedFonts.push({
9994
10250
  index: failedFonts.length,
9995
- family: fontBinding.name,
9996
- reason: err?.message || String(err)
10251
+ kind: "empty",
10252
+ reason: "Font binary is empty (0 bytes)."
9997
10253
  });
10254
+ } else {
10255
+ try {
10256
+ inspectTrueTypeFont(options.customFontBytes);
10257
+ normalFontBytes = options.customFontBytes;
10258
+ } catch (err) {
10259
+ failedFonts.push({
10260
+ index: failedFonts.length,
10261
+ kind: "format",
10262
+ reason: err?.message || String(err)
10263
+ });
10264
+ }
9998
10265
  }
9999
10266
  }
10000
- }
10001
- if (normalFontBytes && normalFontBytes.byteLength > 0) {
10002
- if (boldFontBytes) {
10003
- try {
10004
- inspectTrueTypeFont(boldFontBytes);
10005
- } catch {
10006
- boldFontBytes = void 0;
10267
+ if (!normalFontBytes && snapshot?.resourceBindings) {
10268
+ const fontBinding = Object.values(snapshot.resourceBindings).find(
10269
+ (b) => b.type === "font" && Boolean(b.dataUri)
10270
+ );
10271
+ if (fontBinding?.dataUri) {
10272
+ try {
10273
+ const decoded = dataUriToBytes(fontBinding.dataUri);
10274
+ if (decoded.byteLength === 0) {
10275
+ failedFonts.push({
10276
+ index: failedFonts.length,
10277
+ ...fontBinding.name ? { family: fontBinding.name } : {},
10278
+ kind: "empty",
10279
+ reason: "Font binary is empty (0 bytes)."
10280
+ });
10281
+ } else {
10282
+ inspectTrueTypeFont(decoded);
10283
+ normalFontBytes = decoded;
10284
+ }
10285
+ } catch (err) {
10286
+ failedFonts.push({
10287
+ index: failedFonts.length,
10288
+ ...fontBinding.name ? { family: fontBinding.name } : {},
10289
+ kind: "format",
10290
+ reason: err?.message || String(err)
10291
+ });
10292
+ }
10007
10293
  }
10008
10294
  }
10009
- return { effectiveMode: "subset-ttf", normalFontBytes, boldFontBytes };
10295
+ if (normalFontBytes && normalFontBytes.byteLength > 0) {
10296
+ if (boldFontBytes) {
10297
+ try {
10298
+ inspectTrueTypeFont(boldFontBytes);
10299
+ } catch {
10300
+ boldFontBytes = void 0;
10301
+ }
10302
+ }
10303
+ return {
10304
+ effectiveMode: "subset-ttf",
10305
+ normalFontBytes,
10306
+ boldFontBytes,
10307
+ hasExplicitRenderFonts: false
10308
+ };
10309
+ }
10010
10310
  }
10011
10311
  const fallbackPolicy = renderCfg?.fallback ?? "error";
10012
10312
  const detailSummary = failedFonts.length > 0 ? failedFonts.map(
10013
- (e) => `#${e.index}${e.family ? ` (${e.family})` : ""}${e.url ? ` [${e.url}]` : ""}: ${e.reason}`
10313
+ (e) => `#${e.index}${e.family ? ` (${e.family})` : ""}${e.weight ? ` [${e.weight}]` : ""}${e.url ? ` [${e.url}]` : ""}: ${e.reason}`
10014
10314
  ).join("; ") : "\u672A\u63D0\u4F9B\u53EF\u7528\u7684 TrueType (.ttf) \u5B57\u4F53\u5B57\u8282\u6216\u5730\u5740";
10015
10315
  if (fallbackPolicy === "raster-hd" || fallbackPolicy === "cid-vector") {
10016
10316
  renderCfg?.onWarning?.({
@@ -10018,7 +10318,7 @@ async function resolveRenderFontsForExport(snapshot, options) {
10018
10318
  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
10319
  details: { fallback: fallbackPolicy, failedFonts }
10020
10320
  });
10021
- return { effectiveMode: fallbackPolicy };
10321
+ return { effectiveMode: fallbackPolicy, hasExplicitRenderFonts };
10022
10322
  }
10023
10323
  throw new PdfRenderError(
10024
10324
  "FONT_UNAVAILABLE",
@@ -10029,8 +10329,11 @@ async function resolveRenderFontsForExport(snapshot, options) {
10029
10329
  function initVectorCjkEmbedState(pdfDoc, snapshot, effectiveData, options, preResolved) {
10030
10330
  const requested = preResolved?.effectiveMode ?? options?.render?.cjkTextMode ?? options?.cjkTextMode ?? "raster-hd";
10031
10331
  if (requested === "raster-hd") return null;
10032
- let resolvedFontBytes = preResolved?.normalFontBytes ?? options?.customFontBytes;
10033
- if ((!resolvedFontBytes || resolvedFontBytes.byteLength === 0) && !preResolved && snapshot?.resourceBindings) {
10332
+ const hasExplicitRenderFonts = Boolean(
10333
+ preResolved?.hasExplicitRenderFonts ?? Array.isArray(options?.render?.fonts)
10334
+ );
10335
+ let resolvedFontBytes = preResolved ? preResolved.normalFontBytes : hasExplicitRenderFonts ? void 0 : options?.customFontBytes;
10336
+ if ((!resolvedFontBytes || resolvedFontBytes.byteLength === 0) && !preResolved && !hasExplicitRenderFonts && snapshot?.resourceBindings) {
10034
10337
  const fontBinding = Object.values(snapshot.resourceBindings).find(
10035
10338
  (b) => b.type === "font" && Boolean(b.dataUri)
10036
10339
  );
@@ -10056,6 +10359,24 @@ function initVectorCjkEmbedState(pdfDoc, snapshot, effectiveData, options, preRe
10056
10359
  usedCodePoints,
10057
10360
  "UNVPDF+SubsetTTF"
10058
10361
  );
10362
+ let boldType0FontRef;
10363
+ let boldSubset;
10364
+ const boldBytes = preResolved ? preResolved.boldFontBytes : hasExplicitRenderFonts ? void 0 : options?.customBoldFontBytes;
10365
+ if (boldBytes && boldBytes.byteLength > 0) {
10366
+ if (boldBytes === resolvedFontBytes) {
10367
+ boldType0FontRef = type0FontRef2;
10368
+ boldSubset = subset;
10369
+ } else {
10370
+ const regBold = registerSubsetType0FontInDoc(
10371
+ pdfDoc,
10372
+ boldBytes,
10373
+ usedCodePoints,
10374
+ "UNVPDF+SubsetTTFBold"
10375
+ );
10376
+ boldType0FontRef = regBold.type0FontRef;
10377
+ boldSubset = regBold.subset;
10378
+ }
10379
+ }
10059
10380
  const missingItems = collectMissingGlyphsFromPdfUnit(
10060
10381
  snapshot,
10061
10382
  (cp) => (subset.codePointToGid[cp] ?? 0) > 0,
@@ -10063,7 +10384,7 @@ function initVectorCjkEmbedState(pdfDoc, snapshot, effectiveData, options, preRe
10063
10384
  formatPdfTableCell
10064
10385
  );
10065
10386
  if (missingItems.length > 0) {
10066
- const missingPolicy = options?.render?.missingGlyph ?? "warn";
10387
+ const missingPolicy = options?.render?.missingGlyph ?? (hasExplicitRenderFonts ? "error" : "warn");
10067
10388
  if (missingPolicy === "error") {
10068
10389
  const desc = missingItems.map(
10069
10390
  (m) => `${m.pageId ? `${m.pageId}/` : ""}${m.elementId}: ${m.chars.map((c, idx) => `'${c}' (${m.codePoints[idx]})`).join(", ")}`
@@ -10086,19 +10407,6 @@ function initVectorCjkEmbedState(pdfDoc, snapshot, effectiveData, options, preRe
10086
10407
  }
10087
10408
  }
10088
10409
  }
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
10410
  return {
10103
10411
  mode: "subset-ttf",
10104
10412
  type0FontRef: type0FontRef2,
@@ -10107,6 +10415,9 @@ function initVectorCjkEmbedState(pdfDoc, snapshot, effectiveData, options, preRe
10107
10415
  ...boldType0FontRef ? { boldType0FontRef, boldSubset, boldPageFontKeys: /* @__PURE__ */ new WeakMap() } : {}
10108
10416
  };
10109
10417
  }
10418
+ const usedCidCodePoints = collectUsedCodePointsFromPdfUnit(snapshot, effectiveData);
10419
+ const cidToUnicodeCmap = buildCidUtf16ToUnicodeCmapString(usedCidCodePoints);
10420
+ const cidToUnicodeRef = pdfDoc.context.register(pdfDoc.context.flateStream(cidToUnicodeCmap));
10110
10421
  const fontDescriptorRef = pdfDoc.context.register(
10111
10422
  pdfDoc.context.obj({
10112
10423
  Type: "FontDescriptor",
@@ -10140,7 +10451,8 @@ function initVectorCjkEmbedState(pdfDoc, snapshot, effectiveData, options, preRe
10140
10451
  Subtype: "Type0",
10141
10452
  BaseFont: "STSong-Light",
10142
10453
  Encoding: "UniGB-UTF16-H",
10143
- DescendantFonts: [cidFontRef]
10454
+ DescendantFonts: [cidFontRef],
10455
+ ToUnicode: cidToUnicodeRef
10144
10456
  })
10145
10457
  );
10146
10458
  return {
@@ -10291,7 +10603,7 @@ function encodeVectorCjkLineHex(line, state, overrideSubset) {
10291
10603
  }
10292
10604
  return hex;
10293
10605
  }
10294
- return toUtf16BeHex(line, true);
10606
+ return toUtf16BeHex(line.replace(/\uFEFF/g, ""), false);
10295
10607
  }
10296
10608
  function drawVectorCjkTextBox(page, pageHeight, text, left, top, width, height, style, state, noWrapSingleLine = false, colorType, overrideCharacterSpacing) {
10297
10609
  const wantBold = style?.fontWeight === "bold";
@@ -12395,6 +12707,12 @@ async function drawPageHeaderAndFooter(pdfDoc, pdfPage, pageWidth, pageHeight, c
12395
12707
  }
12396
12708
  }
12397
12709
  async function exportPdfBytes(snapshot, runtimeData, options) {
12710
+ const throwIfExportAborted = () => {
12711
+ if (options?.signal?.aborted) {
12712
+ throw typeof DOMException === "function" ? new DOMException("The operation was aborted.", "AbortError") : Object.assign(new Error("The operation was aborted."), { name: "AbortError" });
12713
+ }
12714
+ };
12715
+ throwIfExportAborted();
12398
12716
  const effectiveData = runtimeData ?? snapshot.metadata?.sampleData;
12399
12717
  const excludeBasePdf = Boolean(snapshot.metadata?.excludeBasePdfOnExport);
12400
12718
  const wmCfg = snapshot.metadata?.watermarkConfig;
@@ -12409,7 +12727,8 @@ async function exportPdfBytes(snapshot, runtimeData, options) {
12409
12727
  options?.accessibilityTagged ?? snapshot.accessibilityTagged ?? snapshot.metadata?.accessibilityTagged
12410
12728
  );
12411
12729
  const optimizeSize = Boolean(options?.optimizeSize);
12412
- const preResolvedFonts = await resolveRenderFontsForExport(snapshot, options);
12730
+ const preResolvedFonts = await resolveRenderFontsForExport(snapshot, effectiveData, options);
12731
+ throwIfExportAborted();
12413
12732
  const pdfDoc = await import_pdf_lib3.PDFDocument.create();
12414
12733
  if (snapshot.metadata?.sanitized) {
12415
12734
  pdfDoc.setTitle("");
@@ -14671,7 +14990,9 @@ async function exportPdfBytes(snapshot, runtimeData, options) {
14671
14990
  if (optimizeSize) {
14672
14991
  pruneUnreferencedObjectsAndCompressStreams(pdfDoc);
14673
14992
  }
14993
+ throwIfExportAborted();
14674
14994
  const savedPdfBytes = interactiveForm && hasAnyAcroWidget ? await pdfDoc.save({ updateFieldAppearances: false }) : await pdfDoc.save();
14995
+ throwIfExportAborted();
14675
14996
  if (options?.diagnosticGridOverlay) {
14676
14997
  const gridOpts = typeof options.diagnosticGridOverlay === "object" ? options.diagnosticGridOverlay : void 0;
14677
14998
  return await overlayDiagnosticGridOnPdfBytes(savedPdfBytes, snapshot, gridOpts);
@@ -16107,7 +16428,7 @@ function buildCompositeTestGlyph(compGidA, compGidB) {
16107
16428
  view.setInt16(24, 80, false);
16108
16429
  return buf;
16109
16430
  }
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";
16431
+ 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
16432
  function buildMinimalTestTrueTypeFont(extraCodePoints) {
16112
16433
  const cpSet = /* @__PURE__ */ new Set();
16113
16434
  for (let ascii = 32; ascii <= 126; ascii++) {
@@ -22115,6 +22436,237 @@ function createPdfBrowserFidelitySamples() {
22115
22436
  s7DefaultNoFont
22116
22437
  };
22117
22438
  }
22439
+ function stripUndefinedDeep(val) {
22440
+ return JSON.parse(JSON.stringify(val));
22441
+ }
22442
+ function createPdfBrowserFidelityExpectations() {
22443
+ const samples = createPdfBrowserFidelitySamples();
22444
+ const entries = [
22445
+ {
22446
+ id: "S1",
22447
+ sampleKey: "s1ShortCjk",
22448
+ title: samples.s1ShortCjk.name,
22449
+ inputSnapshot: stripUndefinedDeep(samples.s1ShortCjk),
22450
+ renderScenario: {
22451
+ cjkTextMode: "subset-ttf",
22452
+ suppliesSubsetFont: true,
22453
+ omitsRenderOptions: false,
22454
+ description: "subset-ttf vector CJK short text, fullwidth punctuation, and mixed CJK/Latin"
22455
+ },
22456
+ expected: {
22457
+ pageCount: 1,
22458
+ tableRowsPerPage: [],
22459
+ extractableTextSnippetsByPage: [
22460
+ [
22461
+ "Monthly Report \xB7 \u6708\u5EA6\u7ECF\u8425\u7B80\u62A5\uFF082026\uFF09",
22462
+ "Vector Subset Font & ToUnicode Verification Sample",
22463
+ "Report Period:",
22464
+ "\u4E00\u6708\uFF082026Q1\uFF09",
22465
+ "\u534E\u4E1C\xB7\u4E0A\u6D77\u6D66\u4E1C\u5F20\u6C5F\u9AD8\u79D1\u6280\u56ED\u533A",
22466
+ "\u5DF2\u6838\u9A8C\uFF1A\u4E13\u7968\u901A\u8FC7\uFF01\u3010\u6279\u6B21 A-108\u3011",
22467
+ "\u6838\u5FC3\u6A21\u5757 Controller-V2 \u5B8C\u6210\u5EA6 98.5\uFF05\uFF1B\u6B21\u65E5\u8FBE\u6B63\u5E38\uFF0C\u201C\u96F6\u5DEE\u9519\u201D\u4EA4\u4ED8"
22468
+ ]
22469
+ ],
22470
+ embedsType0SubsetFont: true,
22471
+ usesRasterTextImages: false
22472
+ }
22473
+ },
22474
+ {
22475
+ id: "S2",
22476
+ sampleKey: "s2LongTextBox",
22477
+ title: samples.s2LongTextBox.name,
22478
+ inputSnapshot: stripUndefinedDeep(samples.s2LongTextBox),
22479
+ renderScenario: {
22480
+ cjkTextMode: "subset-ttf",
22481
+ suppliesSubsetFont: true,
22482
+ omitsRenderOptions: false,
22483
+ description: "subset-ttf multi-paragraph wrapping, 3x3 alignment, box clipping, and autoFitFontSize shrink"
22484
+ },
22485
+ expected: {
22486
+ pageCount: 1,
22487
+ tableRowsPerPage: [],
22488
+ extractableTextSnippetsByPage: [
22489
+ [
22490
+ "S2 \u591A\u6BB5\u6DF7\u6392\u957F\u6587\u672C\u6846",
22491
+ "English words wrap cleanly while",
22492
+ "\u5C45\u4E2D\xB7\u5782\u76F4\u5C45\u4E2D\u793A\u4F8B\uFF08Center / Middle\uFF09",
22493
+ "99.2\uFF05",
22494
+ "\u53F3\u5BF9\u9F50\xB7\u5E95\u90E8\u793A\u4F8B\uFF08Right / Bottom\uFF09",
22495
+ "2026-01-31",
22496
+ "\u7F29\u5C0F\u5B57\u53F7\u81EA\u9002\u5E94\u793A\u4F8B\uFF08autoFitFontSize\uFF09",
22497
+ "Batch-2026-Q1"
22498
+ ]
22499
+ ],
22500
+ embedsType0SubsetFont: true,
22501
+ usesRasterTextImages: false
22502
+ }
22503
+ },
22504
+ {
22505
+ id: "S3",
22506
+ sampleKey: "s3SinglePageTable",
22507
+ title: samples.s3SinglePageTable.name,
22508
+ inputSnapshot: stripUndefinedDeep(samples.s3SinglePageTable),
22509
+ renderScenario: {
22510
+ cjkTextMode: "subset-ttf",
22511
+ suppliesSubsetFont: true,
22512
+ omitsRenderOptions: false,
22513
+ description: "subset-ttf single-page 5-column (1:2:1:1:1) formatted table with zebra stripes"
22514
+ },
22515
+ expected: {
22516
+ pageCount: 1,
22517
+ tableRowsPerPage: [6],
22518
+ extractableTextSnippetsByPage: [
22519
+ [
22520
+ "S3 \u91C7\u8D2D\u51FA\u5E93\u6838\u9A8C\u5355\u9875\u660E\u7EC6\u8868",
22521
+ "\u5546\u54C1\u89C4\u683C\u8BF4\u660E",
22522
+ "A-01",
22523
+ "\u5DE5\u4E1A\u4F20\u611F\u5668\u6A21\u5757\uFF08\u534E\u4E1C\u6807\u51C6\u7248\uFF09",
22524
+ "1,200",
22525
+ "\xA5358.50",
22526
+ "98.5%",
22527
+ "A-06",
22528
+ "\xA52,150.40",
22529
+ "95.0%"
22530
+ ]
22531
+ ],
22532
+ embedsType0SubsetFont: true,
22533
+ usesRasterTextImages: false
22534
+ }
22535
+ },
22536
+ {
22537
+ id: "S4",
22538
+ sampleKey: "s4CellOverflow",
22539
+ title: samples.s4CellOverflow.name,
22540
+ inputSnapshot: stripUndefinedDeep(samples.s4CellOverflow),
22541
+ renderScenario: {
22542
+ cjkTextMode: "subset-ttf",
22543
+ suppliesSubsetFont: true,
22544
+ omitsRenderOptions: false,
22545
+ description: "subset-ttf narrow-column cell overflow clipping and table autoFitFontSize"
22546
+ },
22547
+ expected: {
22548
+ pageCount: 1,
22549
+ tableRowsPerPage: [2],
22550
+ extractableTextSnippetsByPage: [
22551
+ [
22552
+ "S4-A \u9ED8\u8BA4\u56FA\u5B9A\u884C\u9AD8\uFF0824pt\uFF09\u7A84\u5217\u6EA2\u51FA\u4E25\u683C\u88C1\u5207",
22553
+ "\u7A84\u5217\u957F\u4E2D\u6587",
22554
+ "\u7A84\u5217\u8D85\u957F\u897F\u6587",
22555
+ "\u6B63\u5E38\u90BB\u683C A1",
22556
+ "\u6B63\u5E38\u90BB\u683C A2",
22557
+ "S4-B \u5F00\u542F\u8868\u683C\u5355\u5143\u683C\u7F29\u5C0F\u5B57\u53F7"
22558
+ ]
22559
+ ],
22560
+ embedsType0SubsetFont: true,
22561
+ usesRasterTextImages: false
22562
+ }
22563
+ },
22564
+ {
22565
+ id: "S5",
22566
+ sampleKey: "s5MultiPageTable",
22567
+ title: samples.s5MultiPageTable.name,
22568
+ inputSnapshot: stripUndefinedDeep(samples.s5MultiPageTable),
22569
+ renderScenario: {
22570
+ cjkTextMode: "subset-ttf",
22571
+ suppliesSubsetFont: true,
22572
+ omitsRenderOptions: false,
22573
+ description: "subset-ttf 35-row multi-page table (14 + 14 + 7) with repeated headers and trailing footer flow"
22574
+ },
22575
+ expected: {
22576
+ pageCount: 3,
22577
+ tableRowsPerPage: [14, 14, 7],
22578
+ extractableTextSnippetsByPage: [
22579
+ [
22580
+ "S5 \u591A\u9875\u51FA\u5165\u5E93\u6838\u9A8C\u660E\u7EC6\u8868",
22581
+ "\u5355\u636E\u72B6\u6001\uFF1A\u5DF2\u6838\u9A8C",
22582
+ "\u8BA2\u5355\u7F16\u53F7",
22583
+ "R-01",
22584
+ "\u534E\u4E1C\u4E0A\u6D77\u56ED\u533A\xB7\u5DE5\u4E1A\u4F20\u611F\u5668\u6A21\u5757",
22585
+ "\xA5125.50",
22586
+ "R-14",
22587
+ "\xA51,757.00"
22588
+ ],
22589
+ [
22590
+ "\u8BA2\u5355\u7F16\u53F7",
22591
+ "R-15",
22592
+ "\xA51,882.50",
22593
+ "R-28",
22594
+ "\xA53,514.00"
22595
+ ],
22596
+ [
22597
+ "\u8BA2\u5355\u7F16\u53F7",
22598
+ "R-29",
22599
+ "\xA53,639.50",
22600
+ "R-35",
22601
+ "\xA54,392.50",
22602
+ "\u8868\u540E\u7B7E\u6536\u680F\uFF1A\u5BA1\u6279\u4EBA \u5F20\u5DE5 \uFF5C \u8D22\u52A1\u4E13\u7528\u7AE0 \uFF5C \u4ED3\u5E93\u7B7E\u7AE0"
22603
+ ]
22604
+ ],
22605
+ embedsType0SubsetFont: true,
22606
+ usesRasterTextImages: false
22607
+ }
22608
+ },
22609
+ {
22610
+ id: "S6",
22611
+ sampleKey: "s6MissingGlyphs",
22612
+ title: samples.s6MissingGlyphs.name,
22613
+ inputSnapshot: stripUndefinedDeep(samples.s6MissingGlyphs),
22614
+ renderScenario: {
22615
+ cjkTextMode: "subset-ttf",
22616
+ suppliesSubsetFont: true,
22617
+ omitsRenderOptions: false,
22618
+ missingGlyph: "warn",
22619
+ description: "subset-ttf missing-glyph diagnostics ('error' throws MISSING_GLYPH; 'warn' emits warning and renders)"
22620
+ },
22621
+ expected: {
22622
+ pageCount: 1,
22623
+ tableRowsPerPage: [],
22624
+ extractableTextSnippetsByPage: [
22625
+ [
22626
+ "Monthly Report \xB7 \u6708\u5EA6\u7ECF\u8425\u7B80\u62A5\uFF082026\uFF09",
22627
+ "\u4E00\u6708\uFF082026Q1\uFF09",
22628
+ "\u7F3A\u5B57\u8BCA\u65AD\u5907\u6CE8\uFF1A\u751F\u50FB\u5B57",
22629
+ "\u4E0E\u56FE\u6807",
22630
+ "\u6838\u9A8C"
22631
+ ]
22632
+ ],
22633
+ embedsType0SubsetFont: true,
22634
+ usesRasterTextImages: false,
22635
+ expectedErrorWhenStrict: {
22636
+ code: "MISSING_GLYPH",
22637
+ pageId: "page-1",
22638
+ elementId: "s6-missing-note",
22639
+ missingCodePoints: ["U+9F98", "U+1F680"]
22640
+ }
22641
+ }
22642
+ },
22643
+ {
22644
+ id: "S7",
22645
+ sampleKey: "s7DefaultNoFont",
22646
+ title: samples.s7DefaultNoFont.name,
22647
+ inputSnapshot: stripUndefinedDeep(samples.s7DefaultNoFont),
22648
+ renderScenario: {
22649
+ cjkTextMode: "raster-hd",
22650
+ suppliesSubsetFont: false,
22651
+ omitsRenderOptions: true,
22652
+ description: "default omitted render options preserving raster-hd compatibility without fonts"
22653
+ },
22654
+ expected: {
22655
+ pageCount: 1,
22656
+ tableRowsPerPage: [],
22657
+ extractableTextSnippetsByPage: [],
22658
+ embedsType0SubsetFont: false,
22659
+ usesRasterTextImages: true
22660
+ }
22661
+ }
22662
+ ];
22663
+ return {
22664
+ schema: "univer-pdf-fidelity-expectations",
22665
+ version: 1,
22666
+ samples: entries
22667
+ };
22668
+ }
22669
+ var PDF_S1_S7_FIDELITY_EXPECTATIONS = Object.freeze(createPdfBrowserFidelityExpectations());
22118
22670
 
22119
22671
  // src/jsx/types.ts
22120
22672
  var PDF_JSX_ELEMENT_SYMBOL = /* @__PURE__ */ Symbol.for("univer.pdfs.jsx.element");
@@ -23767,7 +24319,51 @@ function detectImportFileFormat(file) {
23767
24319
  }
23768
24320
  return "pdf";
23769
24321
  }
23770
- function attachSuggestedFallbackAndThrow(err, fallback) {
24322
+ function createPdfAbortError(signal) {
24323
+ const reason = signal?.reason;
24324
+ if (reason && typeof reason === "object" && reason.name === "AbortError") {
24325
+ return reason;
24326
+ }
24327
+ return typeof DOMException === "function" ? new DOMException("The operation was aborted.", "AbortError") : Object.assign(new Error("The operation was aborted."), { name: "AbortError" });
24328
+ }
24329
+ function isAbortErrorLike(err) {
24330
+ return Boolean(err && typeof err === "object" && err.name === "AbortError");
24331
+ }
24332
+ function throwIfSignalAborted(signal) {
24333
+ if (signal?.aborted) {
24334
+ throw createPdfAbortError(signal);
24335
+ }
24336
+ }
24337
+ async function raceWithAbortSignal(promise, signal) {
24338
+ throwIfSignalAborted(signal);
24339
+ if (!signal) {
24340
+ return promise;
24341
+ }
24342
+ let onAbort = null;
24343
+ const abortPromise = new Promise((_, reject) => {
24344
+ if (signal.aborted) {
24345
+ reject(createPdfAbortError(signal));
24346
+ return;
24347
+ }
24348
+ onAbort = () => reject(createPdfAbortError(signal));
24349
+ signal.addEventListener("abort", onAbort, { once: true });
24350
+ });
24351
+ void promise.catch(() => {
24352
+ });
24353
+ try {
24354
+ const result = await Promise.race([promise, abortPromise]);
24355
+ throwIfSignalAborted(signal);
24356
+ return result;
24357
+ } finally {
24358
+ if (onAbort) {
24359
+ signal.removeEventListener("abort", onAbort);
24360
+ }
24361
+ }
24362
+ }
24363
+ function attachSuggestedFallbackAndThrow(err, fallback, signal) {
24364
+ if (signal?.aborted || isAbortErrorLike(err)) {
24365
+ throw isAbortErrorLike(err) ? err : createPdfAbortError(signal);
24366
+ }
23771
24367
  if (err && typeof err === "object") {
23772
24368
  if (!err.suggestedFallback) {
23773
24369
  try {
@@ -23782,6 +24378,7 @@ function attachSuggestedFallbackAndThrow(err, fallback) {
23782
24378
  throw wrapped;
23783
24379
  }
23784
24380
  async function importPdfSource(source, options) {
24381
+ throwIfSignalAborted(options?.signal);
23785
24382
  let bytes;
23786
24383
  let fileName = options?.fileName || "imported.pdf";
23787
24384
  if (source instanceof Uint8Array) {
@@ -23813,7 +24410,7 @@ async function importPdfSource(source, options) {
23813
24410
  if ("name" in source && typeof source.name === "string" && source.name) {
23814
24411
  fileName = options?.fileName || source.name;
23815
24412
  }
23816
- const ab = await source.arrayBuffer();
24413
+ const ab = await raceWithAbortSignal(source.arrayBuffer(), options?.signal);
23817
24414
  bytes = new Uint8Array(ab);
23818
24415
  } else {
23819
24416
  throw new PdfImportError("INVALID_PDF_HEADER", "Unsupported PDF input source.");
@@ -23824,7 +24421,9 @@ async function importPdfSource(source, options) {
23824
24421
  "Invalid PDF binary: missing %PDF- header signature."
23825
24422
  );
23826
24423
  }
24424
+ throwIfSignalAborted(options?.signal);
23827
24425
  const { PDFArray: PDFArray6, PDFDict: PDFDict6, PDFDocument: PDFDocument6, PDFName: PDFName6 } = await import("pdf-lib");
24426
+ throwIfSignalAborted(options?.signal);
23828
24427
  let pageSizes = [];
23829
24428
  let warnings = [];
23830
24429
  try {
@@ -23924,6 +24523,7 @@ async function importPdfSource(source, options) {
23924
24523
  throw new PdfImportError("CORRUPT_PDF", `Corrupt PDF binary: ${errMsg}`);
23925
24524
  }
23926
24525
  }
24526
+ throwIfSignalAborted(options?.signal);
23927
24527
  const b64 = uint8ToBase64(bytes);
23928
24528
  const dataUri = `data:application/pdf;base64,${b64}`;
23929
24529
  return {
@@ -23940,9 +24540,11 @@ async function importPdfSource(source, options) {
23940
24540
  warnings
23941
24541
  };
23942
24542
  }
23943
- async function fallbackReadFileAsOutcome(file, baseSnapshot, password) {
24543
+ async function fallbackReadFileAsOutcome(file, baseSnapshot, password, signal, explicitFileName) {
24544
+ throwIfSignalAborted(signal);
23944
24545
  if (detectImportFileFormat(file) === "json") {
23945
- const rawText = typeof file.text === "function" ? await file.text() : new TextDecoder().decode(await file.arrayBuffer());
24546
+ const rawText = typeof file.text === "function" ? await raceWithAbortSignal(file.text(), signal) : new TextDecoder().decode(await raceWithAbortSignal(file.arrayBuffer(), signal));
24547
+ throwIfSignalAborted(signal);
23946
24548
  let parsed;
23947
24549
  try {
23948
24550
  parsed = JSON.parse(rawText);
@@ -23966,7 +24568,10 @@ async function fallbackReadFileAsOutcome(file, baseSnapshot, password) {
23966
24568
  mode: "snapshot",
23967
24569
  snapshot: fromPdfmeTemplate(parsed, {
23968
24570
  id: baseSnapshot.id,
23969
- name: (file.name || baseSnapshot.name || "Imported Template").replace(/\.json$/i, "")
24571
+ name: (explicitFileName || file.name || baseSnapshot.name || "Imported Template").replace(
24572
+ /\.json$/i,
24573
+ ""
24574
+ )
23970
24575
  })
23971
24576
  };
23972
24577
  }
@@ -23975,7 +24580,11 @@ async function fallbackReadFileAsOutcome(file, baseSnapshot, password) {
23975
24580
  "\u672A\u8BC6\u522B\u7684 JSON \u6A21\u677F\u683C\u5F0F\uFF1A\u8BF7\u63D0\u4F9B\u6807\u51C6 IPdfUnitData \u6216 pdfme Template JSON\u3002"
23976
24581
  );
23977
24582
  }
23978
- const imported = await importPdfSource(file, { fileName: file.name || "imported.pdf", password });
24583
+ const imported = await importPdfSource(file, {
24584
+ fileName: explicitFileName || file.name || "imported.pdf",
24585
+ password,
24586
+ signal
24587
+ });
23979
24588
  return {
23980
24589
  mode: "overlay",
23981
24590
  sourceDocumentRef: imported.sourceDocumentRef,
@@ -24205,6 +24814,8 @@ var PdfIoService = class extends import_core11.Disposable {
24205
24814
  return report.outcome;
24206
24815
  }
24207
24816
  async importPdfWithReport(file, context) {
24817
+ const signal = context?.signal;
24818
+ throwIfSignalAborted(signal);
24208
24819
  const { unitId, baseSnapshot } = this._resolveBaseSnapshotForImport(context);
24209
24820
  const adapter = this._adapter$.getValue();
24210
24821
  const caps = this.getIoCapabilities();
@@ -24213,11 +24824,12 @@ var PdfIoService = class extends import_core11.Disposable {
24213
24824
  const requested = context?.target ?? this.getDefaultIoTarget();
24214
24825
  const effective = requested === "auto" ? fmtCap.defaultTarget : requested;
24215
24826
  const defaultImport = async (f) => {
24827
+ throwIfSignalAborted(signal);
24216
24828
  if (context?.defaultImport) {
24217
- const customRaw = await context.defaultImport(f);
24829
+ const customRaw = await raceWithAbortSignal(context.defaultImport(f), signal);
24218
24830
  return normalizeAdapterImportResult(customRaw).outcome;
24219
24831
  }
24220
- return fallbackReadFileAsOutcome(f, baseSnapshot, context?.password);
24832
+ return fallbackReadFileAsOutcome(f, baseSnapshot, context?.password, signal, context?.fileName);
24221
24833
  };
24222
24834
  let rawResult;
24223
24835
  if (effective === "server") {
@@ -24227,49 +24839,85 @@ var PdfIoService = class extends import_core11.Disposable {
24227
24839
  );
24228
24840
  }
24229
24841
  try {
24230
- rawResult = await adapter.importPdf(file, {
24231
- unitId,
24232
- snapshot: import_core11.Tools.deepClone(baseSnapshot),
24233
- defaultImport
24234
- });
24842
+ rawResult = await raceWithAbortSignal(
24843
+ adapter.importPdf(file, {
24844
+ unitId,
24845
+ snapshot: import_core11.Tools.deepClone(baseSnapshot),
24846
+ ...signal ? { signal } : {},
24847
+ defaultImport
24848
+ }),
24849
+ signal
24850
+ );
24235
24851
  } catch (err) {
24236
- attachSuggestedFallbackAndThrow(err, "browser");
24852
+ attachSuggestedFallbackAndThrow(err, "browser", signal);
24237
24853
  }
24238
24854
  } else {
24239
24855
  if (!context?.defaultImport && !fmtCap.browser) {
24240
24856
  attachSuggestedFallbackAndThrow(
24241
24857
  new Error(`\u5F53\u524D\u6D4F\u89C8\u5668\u7AEF\u672A\u542F\u7528 .${fmt} \u683C\u5F0F\u5BFC\u5165\uFF1B\u8BF7\u5207\u6362\u4E3A\u300C\u670D\u52A1\u7AEF\u5904\u7406\u300D\u91CD\u8BD5`),
24242
- "server"
24858
+ "server",
24859
+ signal
24243
24860
  );
24244
24861
  }
24245
24862
  try {
24246
- rawResult = context?.defaultImport ? await context.defaultImport(file) : await fallbackReadFileAsOutcome(file, baseSnapshot, context?.password);
24863
+ rawResult = context?.defaultImport ? await raceWithAbortSignal(context.defaultImport(file), signal) : await fallbackReadFileAsOutcome(
24864
+ file,
24865
+ baseSnapshot,
24866
+ context?.password,
24867
+ signal,
24868
+ context?.fileName
24869
+ );
24247
24870
  } catch (err) {
24248
- attachSuggestedFallbackAndThrow(err, "server");
24871
+ attachSuggestedFallbackAndThrow(err, "server", signal);
24249
24872
  }
24250
24873
  }
24874
+ throwIfSignalAborted(signal);
24251
24875
  const { outcome, warnings } = normalizeAdapterImportResult(rawResult);
24252
24876
  const candidateSnapshot = outcome.mode === "snapshot" ? import_core11.Tools.deepClone(outcome.snapshot) : buildOverlayImportCandidateSnapshot(baseSnapshot, outcome);
24877
+ throwIfSignalAborted(signal);
24253
24878
  return {
24254
24879
  snapshot: candidateSnapshot,
24255
24880
  outcome,
24256
24881
  warnings,
24257
24882
  executedBy: effective,
24258
- fileName: file?.name || (outcome.mode === "overlay" ? outcome.sourceDocumentRef.fileName : candidateSnapshot.name) || void 0
24883
+ fileName: context?.fileName || file?.name || (outcome.mode === "overlay" ? outcome.sourceDocumentRef.fileName : candidateSnapshot.name) || void 0
24259
24884
  };
24260
24885
  }
24886
+ async exportPdfWithTarget(params) {
24887
+ const signal = params.signal ?? params.options?.signal;
24888
+ throwIfSignalAborted(signal);
24889
+ const { unitId, baseSnapshot } = this._resolveBaseSnapshotForImport({
24890
+ unitId: params.unitId,
24891
+ snapshot: params.snapshot
24892
+ });
24893
+ return this.exportPdf({
24894
+ unitId,
24895
+ snapshot: params.snapshot ?? baseSnapshot,
24896
+ data: params.data,
24897
+ options: params.options,
24898
+ target: params.target,
24899
+ signal
24900
+ });
24901
+ }
24261
24902
  async exportPdf(params) {
24903
+ const signal = params.signal ?? params.options?.signal;
24904
+ throwIfSignalAborted(signal);
24905
+ const effectiveOptions = signal ? { ...params.options ?? {}, signal } : params.options;
24262
24906
  const beforeEvent = {
24263
24907
  unitId: params.unitId,
24264
24908
  snapshot: params.snapshot,
24265
24909
  data: params.data,
24266
- options: params.options,
24910
+ options: effectiveOptions,
24267
24911
  cancel: false
24268
24912
  };
24269
24913
  if (this.runBeforeExportHooks(beforeEvent)) {
24270
24914
  throw new import_core11.CanceledError();
24271
24915
  }
24272
- const defaultExport = () => exportPdfBytes(params.snapshot, params.data, params.options);
24916
+ throwIfSignalAborted(signal);
24917
+ const defaultExport = () => raceWithAbortSignal(
24918
+ exportPdfBytes(params.snapshot, params.data, effectiveOptions),
24919
+ signal
24920
+ );
24273
24921
  const adapter = this._adapter$.getValue();
24274
24922
  const caps = this.getIoCapabilities();
24275
24923
  const pdfExportCap = caps.formats.export.pdf;
@@ -24283,17 +24931,22 @@ var PdfIoService = class extends import_core11.Disposable {
24283
24931
  }
24284
24932
  let bytes;
24285
24933
  try {
24286
- const raw = await adapter.exportPdf({
24287
- unitId: params.unitId,
24288
- snapshot: params.snapshot,
24289
- data: params.data,
24290
- options: params.options,
24291
- defaultExport
24292
- });
24293
- bytes = await normalizeBinaryToUint8Array(raw);
24934
+ const raw = await raceWithAbortSignal(
24935
+ adapter.exportPdf({
24936
+ unitId: params.unitId,
24937
+ snapshot: params.snapshot,
24938
+ data: params.data,
24939
+ options: effectiveOptions,
24940
+ ...signal ? { signal } : {},
24941
+ defaultExport
24942
+ }),
24943
+ signal
24944
+ );
24945
+ bytes = await raceWithAbortSignal(normalizeBinaryToUint8Array(raw), signal);
24294
24946
  } catch (err) {
24295
- attachSuggestedFallbackAndThrow(err, "browser");
24947
+ attachSuggestedFallbackAndThrow(err, "browser", signal);
24296
24948
  }
24949
+ throwIfSignalAborted(signal);
24297
24950
  this.notifyExported({
24298
24951
  unitId: params.unitId,
24299
24952
  bytes,
@@ -24305,11 +24958,13 @@ var PdfIoService = class extends import_core11.Disposable {
24305
24958
  if (!pdfExportCap.browser) {
24306
24959
  attachSuggestedFallbackAndThrow(
24307
24960
  new Error("\u5F53\u524D\u6D4F\u89C8\u5668\u7AEF\u672A\u542F\u7528 PDF \u5BFC\u51FA\uFF1B\u8BF7\u5207\u6362\u4E3A\u300C\u670D\u52A1\u7AEF\u5904\u7406\u300D\u91CD\u8BD5"),
24308
- "server"
24961
+ "server",
24962
+ signal
24309
24963
  );
24310
24964
  }
24311
24965
  try {
24312
24966
  const bytes = await defaultExport();
24967
+ throwIfSignalAborted(signal);
24313
24968
  this.notifyExported({
24314
24969
  unitId: params.unitId,
24315
24970
  bytes,
@@ -24318,7 +24973,7 @@ var PdfIoService = class extends import_core11.Disposable {
24318
24973
  });
24319
24974
  return bytes;
24320
24975
  } catch (err) {
24321
- attachSuggestedFallbackAndThrow(err, "server");
24976
+ attachSuggestedFallbackAndThrow(err, "server", signal);
24322
24977
  }
24323
24978
  }
24324
24979
  async silentPrint(params) {
@@ -24374,6 +25029,42 @@ var PdfIoService = class extends import_core11.Disposable {
24374
25029
  PdfIoService = __decorateClass([
24375
25030
  __decorateParam(0, (0, import_core11.Optional)(import_core11.IUniverInstanceService))
24376
25031
  ], PdfIoService);
25032
+ async function exportPdfWithTarget(arg1, arg2) {
25033
+ if (arg1 && typeof arg1.exportPdfWithTarget === "function") {
25034
+ return arg1.exportPdfWithTarget(arg2 ?? {});
25035
+ }
25036
+ if (arg1 && typeof arg1 === "object" && "document" in arg1 && "editState" in arg1) {
25037
+ const snap = arg1;
25038
+ const extIo = arg2?.ioService;
25039
+ if (extIo) {
25040
+ return extIo.exportPdfWithTarget({
25041
+ ...arg2,
25042
+ unitId: arg2?.unitId ?? snap.id,
25043
+ snapshot: snap
25044
+ });
25045
+ }
25046
+ const localIo2 = new PdfIoService();
25047
+ try {
25048
+ return await localIo2.exportPdfWithTarget({
25049
+ ...arg2,
25050
+ unitId: arg2?.unitId ?? snap.id,
25051
+ snapshot: snap
25052
+ });
25053
+ } finally {
25054
+ localIo2.dispose();
25055
+ }
25056
+ }
25057
+ const unified = arg1;
25058
+ if (unified.ioService) {
25059
+ return unified.ioService.exportPdfWithTarget(unified);
25060
+ }
25061
+ const localIo = new PdfIoService();
25062
+ try {
25063
+ return await localIo.exportPdfWithTarget(unified);
25064
+ } finally {
25065
+ localIo.dispose();
25066
+ }
25067
+ }
24377
25068
 
24378
25069
  // src/plugin.ts
24379
25070
  var UNIVER_PDFS_PLUGIN_NAME = "UNIVER_PDFS_PLUGIN";
@@ -24490,6 +25181,10 @@ UniverPdfsPlugin = __decorateClass([
24490
25181
  Barcode,
24491
25182
  Box,
24492
25183
  CIRCLE_MARK_BEZIER_KAPPA,
25184
+ DEFAULT_PDF_CJK_FONT_FAMILY,
25185
+ DEFAULT_PDF_CJK_FONT_FILES,
25186
+ DEFAULT_PDF_CJK_FONT_PACKAGE,
25187
+ DEFAULT_PDF_CJK_FONT_VERSION,
24493
25188
  DeleteSelectedPdfElementsCommand,
24494
25189
  DistributeSelectedPdfElementsCommand,
24495
25190
  Document,
@@ -24511,6 +25206,7 @@ UniverPdfsPlugin = __decorateClass([
24511
25206
  PDF_JSX_ELEMENT_SYMBOL,
24512
25207
  PDF_JSX_FRAGMENT_SYMBOL,
24513
25208
  PDF_PAGE_PRESETS,
25209
+ PDF_S1_S7_FIDELITY_EXPECTATIONS,
24514
25210
  PDF_TABLE_THEME_PRESETS,
24515
25211
  PT_PER_MM,
24516
25212
  Page,
@@ -24593,6 +25289,7 @@ UniverPdfsPlugin = __decorateClass([
24593
25289
  computeExifTransformMatrix,
24594
25290
  computeExpandedTextHeightMm,
24595
25291
  computeExpandedTextHeightPt,
25292
+ computeFontUrlCacheKey,
24596
25293
  computeImageFitPlacement,
24597
25294
  computePasteCascadeOffset,
24598
25295
  computePdfPayloadDigest,
@@ -24609,7 +25306,10 @@ UniverPdfsPlugin = __decorateClass([
24609
25306
  createDefaultElement,
24610
25307
  createDefaultPdfUnitData,
24611
25308
  createHttpSilentPrintAdapter,
25309
+ createPdfAbortError,
25310
+ createPdfBrowserFidelityExpectations,
24612
25311
  createPdfBrowserFidelitySamples,
25312
+ createPdfCjkFontSources,
24613
25313
  createPdfJsxNode,
24614
25314
  detectCJKCharacters,
24615
25315
  detectCJKInPdfInputs,
@@ -24645,6 +25345,7 @@ UniverPdfsPlugin = __decorateClass([
24645
25345
  exportPdfBytes,
24646
25346
  exportPdfToDocxSnapshot,
24647
25347
  exportPdfToWorkbookSnapshot,
25348
+ exportPdfWithTarget,
24648
25349
  exportSignedPdfWithAuditSeal,
24649
25350
  exportToPdfmeTemplate,
24650
25351
  extractAcroFormValuesFromPdfBytes,