@yudaocode/univer-pdfs 1.6.212 → 1.6.213

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.
@@ -5557,6 +5557,91 @@ function drawVectorSvgOnPdfPage(pdfPage, pageHeight, left, top, width, height, s
5557
5557
  }
5558
5558
 
5559
5559
  // src/exporter/pdf-exporter.ts
5560
+ var PdfRenderError = class extends Error {
5561
+ constructor(code, message, extra) {
5562
+ super(message);
5563
+ this.name = "PdfRenderError";
5564
+ this.code = code;
5565
+ if (extra?.failedFonts) this.failedFonts = extra.failedFonts;
5566
+ if (extra?.missingGlyphs) this.missingGlyphs = extra.missingGlyphs;
5567
+ }
5568
+ };
5569
+ var pdfFontUrlByteCache = /* @__PURE__ */ new Map();
5570
+ function bytesToBase64Standard(bytes) {
5571
+ if (typeof Buffer !== "undefined") {
5572
+ return Buffer.from(bytes).toString("base64");
5573
+ }
5574
+ let bin = "";
5575
+ for (let i = 0; i < bytes.byteLength; i++) {
5576
+ bin += String.fromCharCode(bytes[i]);
5577
+ }
5578
+ return btoa(bin);
5579
+ }
5580
+ async function verifyFontSubresourceIntegrity(bytes, integrity) {
5581
+ const trimmed = integrity.trim();
5582
+ if (!trimmed) return;
5583
+ const m = trimmed.match(/^(sha256|sha384|sha512)-([A-Za-z0-9+/=_-]+)$/i);
5584
+ if (!m) {
5585
+ throw new Error(`Unsupported integrity format '${trimmed}' (expected sha256-/sha384-/sha512-).`);
5586
+ }
5587
+ const algoMap = {
5588
+ sha256: "SHA-256",
5589
+ sha384: "SHA-384",
5590
+ sha512: "SHA-512"
5591
+ };
5592
+ const algo = algoMap[m[1].toLowerCase()];
5593
+ const expectedB64 = m[2].replace(/-/g, "+").replace(/_/g, "/");
5594
+ const subtle = globalThis.crypto?.subtle;
5595
+ if (!subtle) {
5596
+ throw new Error("Web Crypto API is unavailable to verify font integrity.");
5597
+ }
5598
+ const digestBuf = await subtle.digest(
5599
+ algo,
5600
+ bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength)
5601
+ );
5602
+ const actualB64 = bytesToBase64Standard(new Uint8Array(digestBuf)).replace(/=+$/, "");
5603
+ const normExpected = expectedB64.replace(/=+$/, "");
5604
+ if (actualB64 !== normExpected) {
5605
+ throw new Error(`Font SRI integrity mismatch (${m[1]}).`);
5606
+ }
5607
+ }
5608
+ async function loadSingleFontCandidate(src) {
5609
+ let rawBytes;
5610
+ if (src.bytes != null) {
5611
+ rawBytes = src.bytes instanceof Uint8Array ? src.bytes : new Uint8Array(src.bytes);
5612
+ if (src.integrity) {
5613
+ await verifyFontSubresourceIntegrity(rawBytes, src.integrity);
5614
+ }
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
+ }
5635
+ inspectTrueTypeFont(rawBytes);
5636
+ pdfFontUrlByteCache.set(cacheKey, rawBytes);
5637
+ return rawBytes;
5638
+ }
5639
+ } else {
5640
+ throw new Error("Font source has neither bytes nor url.");
5641
+ }
5642
+ inspectTrueTypeFont(rawBytes);
5643
+ return rawBytes;
5644
+ }
5560
5645
  function getByPath(data, path) {
5561
5646
  if (!data || !path) return void 0;
5562
5647
  return safeLookupVariablePath(data, path);
@@ -5685,11 +5770,166 @@ endbfchar`);
5685
5770
  "end"
5686
5771
  ].join("\n");
5687
5772
  }
5688
- function initVectorCjkEmbedState(pdfDoc, snapshot, effectiveData, options) {
5689
- const requested = options?.cjkTextMode ?? "raster-hd";
5773
+ function registerSubsetType0FontInDoc(pdfDoc, fontBytes, usedCodePoints, fontTag) {
5774
+ const subset = subsetTrueTypeFont(fontBytes, usedCodePoints);
5775
+ const scale = 1e3 / (subset.unitsPerEm || 1e3);
5776
+ const fontFileStream = pdfDoc.context.flateStream(subset.subsetBytes, {
5777
+ Length1: subset.subsetBytes.byteLength
5778
+ });
5779
+ const fontFileRef = pdfDoc.context.register(fontFileStream);
5780
+ const scaledWidths = subset.gidAdvanceWidths.map((w) => Math.round(w * scale));
5781
+ const fontDescriptorRef = pdfDoc.context.register(
5782
+ pdfDoc.context.obj({
5783
+ Type: "FontDescriptor",
5784
+ FontName: fontTag,
5785
+ Flags: 32,
5786
+ FontBBox: subset.bbox.map((v) => Math.round(v * scale)),
5787
+ ItalicAngle: 0,
5788
+ Ascent: Math.round(subset.ascent * scale),
5789
+ Descent: Math.round(subset.descent * scale),
5790
+ CapHeight: Math.round(subset.ascent * scale),
5791
+ StemV: fontTag.includes("Bold") ? 140 : 80,
5792
+ FontFile2: fontFileRef
5793
+ })
5794
+ );
5795
+ const cidFontRef = pdfDoc.context.register(
5796
+ pdfDoc.context.obj({
5797
+ Type: "Font",
5798
+ Subtype: "CIDFontType2",
5799
+ BaseFont: fontTag,
5800
+ CIDSystemInfo: {
5801
+ Registry: import_pdf_lib3.PDFString.of("Adobe"),
5802
+ Ordering: import_pdf_lib3.PDFString.of("Identity"),
5803
+ Supplement: 0
5804
+ },
5805
+ FontDescriptor: fontDescriptorRef,
5806
+ DW: 1e3,
5807
+ W: [0, scaledWidths],
5808
+ CIDToGIDMap: "Identity"
5809
+ })
5810
+ );
5811
+ const toUnicodeCmap = buildToUnicodeCmapString(subset.codePointToGid);
5812
+ const toUnicodeRef = pdfDoc.context.register(pdfDoc.context.flateStream(toUnicodeCmap));
5813
+ const type0FontRef = pdfDoc.context.register(
5814
+ pdfDoc.context.obj({
5815
+ Type: "Font",
5816
+ Subtype: "Type0",
5817
+ BaseFont: fontTag,
5818
+ Encoding: "Identity-H",
5819
+ DescendantFonts: [cidFontRef],
5820
+ ToUnicode: toUnicodeRef
5821
+ })
5822
+ );
5823
+ return { type0FontRef, subset };
5824
+ }
5825
+ async function resolveRenderFontsForExport(snapshot, options) {
5826
+ const renderCfg = options?.render;
5827
+ const hasHostFonts = Boolean(renderCfg?.fonts && renderCfg.fonts.length > 0);
5828
+ const explicitMode = renderCfg?.cjkTextMode ?? options?.cjkTextMode;
5829
+ const requestedMode = explicitMode ?? (hasHostFonts ? "subset-ttf" : "raster-hd");
5830
+ if (requestedMode === "raster-hd" || requestedMode === "cid-vector") {
5831
+ return { effectiveMode: requestedMode };
5832
+ }
5833
+ const failedFonts = [];
5834
+ let normalFontBytes;
5835
+ let boldFontBytes = options?.customBoldFontBytes;
5836
+ if (hasHostFonts && renderCfg?.fonts) {
5837
+ const normalCandidates = renderCfg.fonts.map((f, index) => ({ f, index })).filter(({ f }) => f.weight !== "bold");
5838
+ 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
+ });
5852
+ }
5853
+ }
5854
+ if (normalFontBytes && !boldFontBytes && boldCandidates.length > 0 && normalCandidates.length > 0) {
5855
+ for (const { f, index } of boldCandidates) {
5856
+ try {
5857
+ boldFontBytes = await loadSingleFontCandidate(f);
5858
+ break;
5859
+ } 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
+ });
5867
+ }
5868
+ }
5869
+ }
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
+ });
5880
+ }
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) {
5892
+ failedFonts.push({
5893
+ index: failedFonts.length,
5894
+ family: fontBinding.name,
5895
+ reason: err?.message || String(err)
5896
+ });
5897
+ }
5898
+ }
5899
+ }
5900
+ if (normalFontBytes && normalFontBytes.byteLength > 0) {
5901
+ if (boldFontBytes) {
5902
+ try {
5903
+ inspectTrueTypeFont(boldFontBytes);
5904
+ } catch {
5905
+ boldFontBytes = void 0;
5906
+ }
5907
+ }
5908
+ return { effectiveMode: "subset-ttf", normalFontBytes, boldFontBytes };
5909
+ }
5910
+ const fallbackPolicy = renderCfg?.fallback ?? "error";
5911
+ const detailSummary = failedFonts.length > 0 ? failedFonts.map(
5912
+ (e) => `#${e.index}${e.family ? ` (${e.family})` : ""}${e.url ? ` [${e.url}]` : ""}: ${e.reason}`
5913
+ ).join("; ") : "\u672A\u63D0\u4F9B\u53EF\u7528\u7684 TrueType (.ttf) \u5B57\u4F53\u5B57\u8282\u6216\u5730\u5740";
5914
+ if (fallbackPolicy === "raster-hd" || fallbackPolicy === "cid-vector") {
5915
+ renderCfg?.onWarning?.({
5916
+ code: "FONT_FALLBACK_ACTIVATED",
5917
+ 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
+ details: { fallback: fallbackPolicy, failedFonts }
5919
+ });
5920
+ return { effectiveMode: fallbackPolicy };
5921
+ }
5922
+ throw new PdfRenderError(
5923
+ "FONT_UNAVAILABLE",
5924
+ `PDF \u5B50\u96C6\u5B57\u4F53\u4E0D\u53EF\u7528\uFF08cjkTextMode='subset-ttf'\uFF09\uFF1A${detailSummary}`,
5925
+ { failedFonts }
5926
+ );
5927
+ }
5928
+ function initVectorCjkEmbedState(pdfDoc, snapshot, effectiveData, options, preResolved) {
5929
+ const requested = preResolved?.effectiveMode ?? options?.render?.cjkTextMode ?? options?.cjkTextMode ?? "raster-hd";
5690
5930
  if (requested === "raster-hd") return null;
5691
- let resolvedFontBytes = options?.customFontBytes;
5692
- if ((!resolvedFontBytes || resolvedFontBytes.byteLength === 0) && snapshot?.resourceBindings) {
5931
+ let resolvedFontBytes = preResolved?.normalFontBytes ?? options?.customFontBytes;
5932
+ if ((!resolvedFontBytes || resolvedFontBytes.byteLength === 0) && !preResolved && snapshot?.resourceBindings) {
5693
5933
  const fontBinding = Object.values(snapshot.resourceBindings).find(
5694
5934
  (b) => b.type === "font" && Boolean(b.dataUri)
5695
5935
  );
@@ -5701,62 +5941,69 @@ function initVectorCjkEmbedState(pdfDoc, snapshot, effectiveData, options) {
5701
5941
  }
5702
5942
  }
5703
5943
  }
5704
- if (requested === "subset-ttf" && resolvedFontBytes && resolvedFontBytes.byteLength > 0) {
5944
+ if (requested === "subset-ttf") {
5945
+ if (!resolvedFontBytes || resolvedFontBytes.byteLength === 0) {
5946
+ throw new PdfRenderError(
5947
+ "FONT_UNAVAILABLE",
5948
+ "PDF \u5B50\u96C6\u5B57\u4F53\u4E0D\u53EF\u7528\uFF08cjkTextMode='subset-ttf'\uFF09\uFF1A\u672A\u63D0\u4F9B\u6709\u6548\u7684 TrueType (.ttf) \u5B57\u4F53\u6570\u636E\u3002"
5949
+ );
5950
+ }
5705
5951
  const usedCodePoints = collectUsedCodePointsFromPdfUnit(snapshot, effectiveData);
5706
- const subset = subsetTrueTypeFont(resolvedFontBytes, usedCodePoints);
5707
- const scale = 1e3 / (subset.unitsPerEm || 1e3);
5708
- const fontFileStream = pdfDoc.context.flateStream(subset.subsetBytes, {
5709
- Length1: subset.subsetBytes.byteLength
5710
- });
5711
- const fontFileRef = pdfDoc.context.register(fontFileStream);
5712
- const scaledWidths = subset.gidAdvanceWidths.map((w) => Math.round(w * scale));
5713
- const fontDescriptorRef2 = pdfDoc.context.register(
5714
- pdfDoc.context.obj({
5715
- Type: "FontDescriptor",
5716
- FontName: "UNVPDF+SubsetTTF",
5717
- Flags: 32,
5718
- FontBBox: subset.bbox.map((v) => Math.round(v * scale)),
5719
- ItalicAngle: 0,
5720
- Ascent: Math.round(subset.ascent * scale),
5721
- Descent: Math.round(subset.descent * scale),
5722
- CapHeight: Math.round(subset.ascent * scale),
5723
- StemV: 80,
5724
- FontFile2: fontFileRef
5725
- })
5726
- );
5727
- const cidFontRef2 = pdfDoc.context.register(
5728
- pdfDoc.context.obj({
5729
- Type: "Font",
5730
- Subtype: "CIDFontType2",
5731
- BaseFont: "UNVPDF+SubsetTTF",
5732
- CIDSystemInfo: {
5733
- Registry: import_pdf_lib3.PDFString.of("Adobe"),
5734
- Ordering: import_pdf_lib3.PDFString.of("Identity"),
5735
- Supplement: 0
5736
- },
5737
- FontDescriptor: fontDescriptorRef2,
5738
- DW: 1e3,
5739
- W: [0, scaledWidths],
5740
- CIDToGIDMap: "Identity"
5741
- })
5952
+ const { type0FontRef: type0FontRef2, subset } = registerSubsetType0FontInDoc(
5953
+ pdfDoc,
5954
+ resolvedFontBytes,
5955
+ usedCodePoints,
5956
+ "UNVPDF+SubsetTTF"
5742
5957
  );
5743
- const toUnicodeCmap = buildToUnicodeCmapString(subset.codePointToGid);
5744
- const toUnicodeRef = pdfDoc.context.register(pdfDoc.context.flateStream(toUnicodeCmap));
5745
- const type0FontRef2 = pdfDoc.context.register(
5746
- pdfDoc.context.obj({
5747
- Type: "Font",
5748
- Subtype: "Type0",
5749
- BaseFont: "UNVPDF+SubsetTTF",
5750
- Encoding: "Identity-H",
5751
- DescendantFonts: [cidFontRef2],
5752
- ToUnicode: toUnicodeRef
5753
- })
5958
+ const missingItems = collectMissingGlyphsFromPdfUnit(
5959
+ snapshot,
5960
+ (cp) => (subset.codePointToGid[cp] ?? 0) > 0,
5961
+ effectiveData,
5962
+ formatPdfTableCell
5754
5963
  );
5964
+ if (missingItems.length > 0) {
5965
+ const missingPolicy = options?.render?.missingGlyph ?? "warn";
5966
+ if (missingPolicy === "error") {
5967
+ const desc = missingItems.map(
5968
+ (m) => `${m.pageId ? `${m.pageId}/` : ""}${m.elementId}: ${m.chars.map((c, idx) => `'${c}' (${m.codePoints[idx]})`).join(", ")}`
5969
+ ).join("; ");
5970
+ throw new PdfRenderError(
5971
+ "MISSING_GLYPH",
5972
+ `PDF \u5B50\u96C6\u5B57\u4F53\u7F3A\u5C11\u6587\u6863\u6240\u9700\u5B57\u5F62\uFF1A${desc}`,
5973
+ { missingGlyphs: missingItems }
5974
+ );
5975
+ }
5976
+ if (options?.render?.onWarning) {
5977
+ for (const item of missingItems) {
5978
+ options.render.onWarning({
5979
+ code: "MISSING_GLYPH",
5980
+ pageId: item.pageId,
5981
+ elementId: item.elementId,
5982
+ message: `\u5143\u7D20 ${item.elementId} \u542B\u5F53\u524D\u5B57\u4F53\u7F3A\u5931\u7684\u5B57\u5F62\uFF1A${item.chars.map((c, idx) => `'${c}' (${item.codePoints[idx]})`).join(", ")}`,
5983
+ details: { chars: item.chars, codePoints: item.codePoints }
5984
+ });
5985
+ }
5986
+ }
5987
+ }
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
+ }
5755
6001
  return {
5756
6002
  mode: "subset-ttf",
5757
6003
  type0FontRef: type0FontRef2,
5758
6004
  subset,
5759
- pageFontKeys: /* @__PURE__ */ new WeakMap()
6005
+ pageFontKeys: /* @__PURE__ */ new WeakMap(),
6006
+ ...boldType0FontRef ? { boldType0FontRef, boldSubset, boldPageFontKeys: /* @__PURE__ */ new WeakMap() } : {}
5760
6007
  };
5761
6008
  }
5762
6009
  const fontDescriptorRef = pdfDoc.context.register(
@@ -5801,24 +6048,127 @@ function initVectorCjkEmbedState(pdfDoc, snapshot, effectiveData, options) {
5801
6048
  pageFontKeys: /* @__PURE__ */ new WeakMap()
5802
6049
  };
5803
6050
  }
5804
- function getOrRegisterPageCjkFontKey(page, state) {
6051
+ function getOrRegisterPageCjkFontKey(page, state, wantBold = false) {
6052
+ if (wantBold && state.boldType0FontRef && state.boldSubset && state.boldPageFontKeys) {
6053
+ const existingBold = state.boldPageFontKeys.get(page);
6054
+ if (existingBold) {
6055
+ return { fontKey: existingBold, activeSubset: state.boldSubset, usedDedicatedBold: true };
6056
+ }
6057
+ const boldKey = page.node.newFontDictionary("FSubB", state.boldType0FontRef);
6058
+ state.boldPageFontKeys.set(page, boldKey);
6059
+ return { fontKey: boldKey, activeSubset: state.boldSubset, usedDedicatedBold: true };
6060
+ }
5805
6061
  const existing = state.pageFontKeys.get(page);
5806
- if (existing) return existing;
6062
+ if (existing) {
6063
+ return { fontKey: existing, activeSubset: state.subset, usedDedicatedBold: false };
6064
+ }
5807
6065
  const key = page.node.newFontDictionary(state.mode === "subset-ttf" ? "FSub" : "FCid", state.type0FontRef);
5808
6066
  state.pageFontKeys.set(page, key);
5809
- return key;
6067
+ return { fontKey: key, activeSubset: state.subset, usedDedicatedBold: false };
5810
6068
  }
5811
- function measureVectorCjkLine(line, fontSize, state, characterSpacing = 0) {
6069
+ function isIdeographOrFullwidthCodePoint(cp) {
6070
+ return cp >= 11904 && cp <= 40959 || cp >= 44032 && cp <= 55215 || cp >= 63744 && cp <= 64255 || cp >= 65072 && cp <= 65135 || cp >= 65280 && cp <= 65519 || cp >= 126976;
6071
+ }
6072
+ function wrapMixedCjkAndLatinLines(rawText, maxWidthPt, measureFn) {
6073
+ const normalized = rawText.replace(/\r\n?/g, "\n");
6074
+ const limit = Math.max(1, maxWidthPt);
6075
+ const out = [];
6076
+ const tokenizeParagraph = (para) => {
6077
+ const tokens = [];
6078
+ let buf = "";
6079
+ let bufKind = null;
6080
+ for (const ch of para) {
6081
+ const cp = ch.codePointAt(0) ?? 32;
6082
+ if (ch === " " || ch === " ") {
6083
+ if (bufKind === "space") {
6084
+ buf += ch;
6085
+ } else {
6086
+ if (buf) tokens.push({ kind: bufKind, text: buf });
6087
+ buf = ch;
6088
+ bufKind = "space";
6089
+ }
6090
+ } else if (isIdeographOrFullwidthCodePoint(cp)) {
6091
+ if (buf) {
6092
+ tokens.push({ kind: bufKind, text: buf });
6093
+ buf = "";
6094
+ bufKind = null;
6095
+ }
6096
+ tokens.push({ kind: "cjk", text: ch });
6097
+ } else {
6098
+ if (bufKind === "word") {
6099
+ buf += ch;
6100
+ } else {
6101
+ if (buf) tokens.push({ kind: bufKind, text: buf });
6102
+ buf = ch;
6103
+ bufKind = "word";
6104
+ }
6105
+ }
6106
+ }
6107
+ if (buf && bufKind) {
6108
+ tokens.push({ kind: bufKind, text: buf });
6109
+ }
6110
+ return tokens;
6111
+ };
6112
+ for (const para of normalized.split("\n")) {
6113
+ if (!para) {
6114
+ out.push({ text: "", isLastInParagraph: true });
6115
+ continue;
6116
+ }
6117
+ const tokens = tokenizeParagraph(para);
6118
+ let current = "";
6119
+ for (const tok of tokens) {
6120
+ if (tok.kind === "space") {
6121
+ if (!current) continue;
6122
+ const candidate2 = current + tok.text;
6123
+ if (measureFn(candidate2) <= limit) {
6124
+ current = candidate2;
6125
+ } else {
6126
+ out.push({ text: current.replace(/[ \t]+$/g, ""), isLastInParagraph: false });
6127
+ current = "";
6128
+ }
6129
+ continue;
6130
+ }
6131
+ const candidate = current + tok.text;
6132
+ if (measureFn(candidate) <= limit) {
6133
+ current = candidate;
6134
+ continue;
6135
+ }
6136
+ if (current) {
6137
+ out.push({ text: current.replace(/[ \t]+$/g, ""), isLastInParagraph: false });
6138
+ current = "";
6139
+ }
6140
+ if (measureFn(tok.text) <= limit || Array.from(tok.text).length <= 1) {
6141
+ current = tok.text;
6142
+ } else {
6143
+ let charBuf = "";
6144
+ for (const ch of tok.text) {
6145
+ const nextBuf = charBuf + ch;
6146
+ if (measureFn(nextBuf) > limit && charBuf.length > 0) {
6147
+ out.push({ text: charBuf, isLastInParagraph: false });
6148
+ charBuf = ch;
6149
+ } else {
6150
+ charBuf = nextBuf;
6151
+ }
6152
+ }
6153
+ current = charBuf;
6154
+ }
6155
+ }
6156
+ out.push({ text: current.replace(/[ \t]+$/g, ""), isLastInParagraph: true });
6157
+ }
6158
+ return out;
6159
+ }
6160
+ function measureVectorCjkLine(line, fontSize, state, characterSpacing = 0, overrideSubset) {
5812
6161
  if (!line) return 0;
5813
6162
  const glyphCount = Array.from(line).length;
5814
6163
  const extraTc = glyphCount > 1 ? (glyphCount - 1) * characterSpacing : 0;
5815
- if (state.mode === "subset-ttf" && state.subset) {
5816
- const upem = state.subset.unitsPerEm || 1e3;
6164
+ const sub = overrideSubset ?? state.subset;
6165
+ if (state.mode === "subset-ttf" && sub) {
6166
+ const upem = sub.unitsPerEm || 1e3;
5817
6167
  let totalUnits = 0;
5818
6168
  for (const ch of line) {
5819
6169
  const cp = ch.codePointAt(0) ?? 63;
5820
- const gid = state.subset.codePointToGid[cp] ?? 0;
5821
- totalUnits += state.subset.gidAdvanceWidths[gid] ?? upem;
6170
+ const gid = sub.codePointToGid[cp] ?? 0;
6171
+ totalUnits += sub.gidAdvanceWidths[gid] ?? upem;
5822
6172
  }
5823
6173
  return totalUnits * fontSize / upem + extraTc;
5824
6174
  }
@@ -5829,12 +6179,13 @@ function measureVectorCjkLine(line, fontSize, state, characterSpacing = 0) {
5829
6179
  }
5830
6180
  return width + extraTc;
5831
6181
  }
5832
- function encodeVectorCjkLineHex(line, state) {
5833
- if (state.mode === "subset-ttf" && state.subset) {
6182
+ function encodeVectorCjkLineHex(line, state, overrideSubset) {
6183
+ const sub = overrideSubset ?? state.subset;
6184
+ if (state.mode === "subset-ttf" && sub) {
5834
6185
  let hex = "";
5835
6186
  for (const ch of line) {
5836
6187
  const cp = ch.codePointAt(0) ?? 63;
5837
- const gid = state.subset.codePointToGid[cp] ?? 0;
6188
+ const gid = sub.codePointToGid[cp] ?? 0;
5838
6189
  hex += gid.toString(16).padStart(4, "0").toUpperCase();
5839
6190
  }
5840
6191
  return hex;
@@ -5842,38 +6193,21 @@ function encodeVectorCjkLineHex(line, state) {
5842
6193
  return toUtf16BeHex(line, true);
5843
6194
  }
5844
6195
  function drawVectorCjkTextBox(page, pageHeight, text, left, top, width, height, style, state, noWrapSingleLine = false, colorType, overrideCharacterSpacing) {
5845
- const fontKey = getOrRegisterPageCjkFontKey(page, state);
6196
+ const wantBold = style?.fontWeight === "bold";
6197
+ const { fontKey, activeSubset, usedDedicatedBold } = getOrRegisterPageCjkFontKey(page, state, wantBold);
5846
6198
  const fontSize = style?.fontSize ?? 12;
5847
6199
  const pad = style?.padding ?? 4;
5848
- const maxWidth = Math.max(8, width - pad * 2);
6200
+ const maxWidth = Math.max(1, width - pad * 2);
5849
6201
  const lineHeight = fontSize * (style?.lineHeight ?? 1.38);
5850
6202
  const color = parseHexColor(style?.color) ?? { r: 0.12, g: 0.14, b: 0.16, a: 1 };
5851
6203
  const charSpacing = overrideCharacterSpacing ?? style?.characterSpacing ?? 0;
5852
6204
  const pdfY = pageHeight - top - height;
5853
- const lines = [];
5854
- if (noWrapSingleLine) {
5855
- for (const para of text.split("\n")) {
5856
- lines.push({ text: para, isLastInParagraph: true });
5857
- }
5858
- } else {
5859
- for (const para of text.split("\n")) {
5860
- if (!para) {
5861
- lines.push({ text: "", isLastInParagraph: true });
5862
- continue;
5863
- }
5864
- let current = "";
5865
- for (const ch of para) {
5866
- const candidate = current + ch;
5867
- if (measureVectorCjkLine(candidate, fontSize, state, charSpacing) > maxWidth && current.length > 0) {
5868
- lines.push({ text: current, isLastInParagraph: false });
5869
- current = ch;
5870
- } else {
5871
- current = candidate;
5872
- }
5873
- }
5874
- if (current) lines.push({ text: current, isLastInParagraph: true });
5875
- }
5876
- }
6205
+ const normalized = text.replace(/\r\n?/g, "\n");
6206
+ const lines = noWrapSingleLine ? normalized.split("\n").map((para) => ({ text: para, isLastInParagraph: true })) : wrapMixedCjkAndLatinLines(
6207
+ normalized,
6208
+ maxWidth,
6209
+ (s) => measureVectorCjkLine(s, fontSize, state, charSpacing, activeSubset)
6210
+ );
5877
6211
  const totalH = lines.length * lineHeight;
5878
6212
  let firstBaselineFromTop = pad + fontSize * 0.85;
5879
6213
  if (style?.verticalAlign === "middle") {
@@ -5885,12 +6219,34 @@ function drawVectorCjkTextBox(page, pageHeight, text, left, top, width, height,
5885
6219
  const cm = rgbToCmyk(color.r, color.g, color.b);
5886
6220
  return (0, import_pdf_lib3.setFillingCmykColor)(cm.c, cm.m, cm.y, cm.k);
5887
6221
  })() : (0, import_pdf_lib3.setFillingRgbColor)(color.r, color.g, color.b);
6222
+ const syntheticBoldOps = wantBold && !usedDedicatedBold ? [
6223
+ import_pdf_lib3.PDFOperator.of("Tr", [import_pdf_lib3.PDFNumber.of(2)]),
6224
+ (0, import_pdf_lib3.setLineWidth)(Math.max(0.25, fontSize * 0.032)),
6225
+ colorType === "cmyk" ? (() => {
6226
+ const cm = rgbToCmyk(color.r, color.g, color.b);
6227
+ return (0, import_pdf_lib3.setStrokingCmykColor)(cm.c, cm.m, cm.y, cm.k);
6228
+ })() : (0, import_pdf_lib3.setStrokingRgbColor)(color.r, color.g, color.b)
6229
+ ] : [];
5888
6230
  const decoCol = toPdfLibColor(color, colorType);
5889
6231
  const decoThickness = Math.max(0.6, fontSize * 0.065);
6232
+ const applyClip = !noWrapSingleLine && width > 0 && height > 0;
6233
+ if (applyClip) {
6234
+ page.pushOperators(
6235
+ (0, import_pdf_lib3.pushGraphicsState)(),
6236
+ (0, import_pdf_lib3.rectangle)(left, pdfY, width, height),
6237
+ (0, import_pdf_lib3.clip)(),
6238
+ (0, import_pdf_lib3.endPath)()
6239
+ );
6240
+ }
5890
6241
  for (let i = 0; i < lines.length; i++) {
5891
6242
  const { text: line, isLastInParagraph } = lines[i];
5892
6243
  if (!line) continue;
5893
- const lineW = measureVectorCjkLine(line, fontSize, state, charSpacing);
6244
+ const drawY = pageHeight - top - (firstBaselineFromTop + i * lineHeight);
6245
+ if (!noWrapSingleLine) {
6246
+ if (i === 0 && height < fontSize * 0.55) break;
6247
+ if (i > 0 && drawY - fontSize * 0.14 < pdfY) break;
6248
+ }
6249
+ const lineW = measureVectorCjkLine(line, fontSize, state, charSpacing, activeSubset);
5894
6250
  let drawX = left + pad;
5895
6251
  let effectiveLineW = lineW;
5896
6252
  let extraJustifyTc = 0;
@@ -5905,9 +6261,7 @@ function drawVectorCjkTextBox(page, pageHeight, text, left, top, width, height,
5905
6261
  effectiveLineW = maxWidth;
5906
6262
  }
5907
6263
  }
5908
- const drawY = pageHeight - top - (firstBaselineFromTop + i * lineHeight);
5909
- if (drawY < pdfY - 2 && !noWrapSingleLine) break;
5910
- const hexStr = encodeVectorCjkLineHex(line, state);
6264
+ const hexStr = encodeVectorCjkLineHex(line, state, activeSubset);
5911
6265
  const totalTc = charSpacing + extraJustifyTc;
5912
6266
  const posOp = style?.italic ? import_pdf_lib3.PDFOperator.of("Tm", [
5913
6267
  import_pdf_lib3.PDFNumber.of(1),
@@ -5921,6 +6275,7 @@ function drawVectorCjkTextBox(page, pageHeight, text, left, top, width, height,
5921
6275
  (0, import_pdf_lib3.pushGraphicsState)(),
5922
6276
  (0, import_pdf_lib3.beginText)(),
5923
6277
  fillOp,
6278
+ ...syntheticBoldOps,
5924
6279
  (0, import_pdf_lib3.setFontAndSize)(fontKey, fontSize),
5925
6280
  ...totalTc !== 0 ? [(0, import_pdf_lib3.setCharacterSpacing)(totalTc)] : [],
5926
6281
  posOp,
@@ -5949,6 +6304,9 @@ function drawVectorCjkTextBox(page, pageHeight, text, left, top, width, height,
5949
6304
  });
5950
6305
  }
5951
6306
  }
6307
+ if (applyClip) {
6308
+ page.pushOperators((0, import_pdf_lib3.popGraphicsState)());
6309
+ }
5952
6310
  }
5953
6311
  function renderTextToPngBytesInBrowser(text, widthPt, heightPt, style) {
5954
6312
  if (typeof document === "undefined") return null;
@@ -5967,27 +6325,10 @@ function renderTextToPngBytesInBrowser(text, widthPt, heightPt, style) {
5967
6325
  ctx.fillStyle = style?.color ?? "#1f2329";
5968
6326
  ctx.textBaseline = "top";
5969
6327
  const pad = style?.padding ?? 4;
5970
- const maxWidth = Math.max(4, widthPt - pad * 2);
5971
- const lineHeight = fontSize * (style?.lineHeight ?? 1.4);
5972
- const paragraphs = text.split("\n");
5973
- const lines = [];
5974
- for (const para of paragraphs) {
5975
- if (!para) {
5976
- lines.push("");
5977
- continue;
5978
- }
5979
- let current = "";
5980
- for (const ch of para) {
5981
- const test = current + ch;
5982
- if (ctx.measureText(test).width > maxWidth && current.length > 0) {
5983
- lines.push(current);
5984
- current = ch;
5985
- } else {
5986
- current = test;
5987
- }
5988
- }
5989
- if (current) lines.push(current);
5990
- }
6328
+ const maxWidth = Math.max(1, widthPt - pad * 2);
6329
+ const lineHeight = fontSize * (style?.lineHeight ?? 1.38);
6330
+ const wrapped = wrapMixedCjkAndLatinLines(text, maxWidth, (s) => ctx.measureText(s).width);
6331
+ const lines = wrapped.map((w) => w.text);
5991
6332
  const totalTextHeight = lines.length * lineHeight;
5992
6333
  let startY = pad;
5993
6334
  if (style?.verticalAlign === "middle") {
@@ -5997,15 +6338,17 @@ function renderTextToPngBytesInBrowser(text, widthPt, heightPt, style) {
5997
6338
  }
5998
6339
  for (let i = 0; i < lines.length; i++) {
5999
6340
  const line = lines[i];
6341
+ if (!line) continue;
6342
+ const y = startY + i * lineHeight;
6343
+ if (i === 0 && heightPt < fontSize * 0.55) break;
6344
+ if (i > 0 && y + fontSize > heightPt + 1) break;
6000
6345
  const lineWidth = ctx.measureText(line).width;
6001
6346
  let x = pad;
6002
6347
  if (style?.textAlign === "center") {
6003
- x = (widthPt - lineWidth) / 2;
6348
+ x = Math.max(pad, (widthPt - lineWidth) / 2);
6004
6349
  } else if (style?.textAlign === "right") {
6005
- x = widthPt - pad - lineWidth;
6350
+ x = Math.max(pad, widthPt - pad - lineWidth);
6006
6351
  }
6007
- const y = startY + i * lineHeight;
6008
- if (y + fontSize > heightPt + 2) break;
6009
6352
  ctx.fillText(line, x, y);
6010
6353
  if (style?.underline) {
6011
6354
  ctx.beginPath();
@@ -6412,57 +6755,14 @@ async function drawTextBox(pdfDoc, page, pageHeight, text, left, top, width, hei
6412
6755
  const pad = style?.padding ?? 4;
6413
6756
  const color = parseHexColor(style?.color) ?? { r: 0.12, g: 0.14, b: 0.16, a: 1 };
6414
6757
  const pdfCol = toPdfLibColor(color, colorType);
6415
- const maxLineW = Math.max(10, bgWidth - pad * 2);
6416
- const lineHeight = fontSize * (style?.lineHeight ?? 1.35);
6758
+ const maxLineW = Math.max(1, bgWidth - pad * 2);
6759
+ const lineHeight = fontSize * (style?.lineHeight ?? 1.38);
6760
+ const normalizedText = text.replace(/\r\n?/g, "\n");
6417
6761
  const measureAscii = (s) => {
6418
6762
  if (!s) return 0;
6419
6763
  return font.widthOfTextAtSize(s, fontSize) + (s.length > 1 ? (s.length - 1) * charSpacing : 0);
6420
6764
  };
6421
- const wrappedLines = [];
6422
- if (extraOpts?.noWrapSingleLine) {
6423
- for (const para of text.split("\n")) {
6424
- wrappedLines.push({ text: para, isLastInParagraph: true });
6425
- }
6426
- } else {
6427
- for (const para of text.split("\n")) {
6428
- if (!para) {
6429
- wrappedLines.push({ text: "", isLastInParagraph: true });
6430
- continue;
6431
- }
6432
- const tokens = para.split(/( +)/).filter((t) => t.length > 0);
6433
- let current = "";
6434
- for (const tok of tokens) {
6435
- const candidate = current ? current + tok : tok.replace(/^ +/, "");
6436
- if (!candidate) continue;
6437
- if (measureAscii(candidate) <= maxLineW) {
6438
- current = candidate;
6439
- continue;
6440
- }
6441
- if (current) {
6442
- wrappedLines.push({ text: current.trimEnd(), isLastInParagraph: false });
6443
- current = "";
6444
- }
6445
- const trimmedTok = tok.replace(/^ +/, "");
6446
- if (!trimmedTok) continue;
6447
- if (measureAscii(trimmedTok) <= maxLineW) {
6448
- current = trimmedTok;
6449
- } else {
6450
- let charBuf = "";
6451
- for (const ch of trimmedTok) {
6452
- const nextBuf = charBuf + ch;
6453
- if (measureAscii(nextBuf) > maxLineW && charBuf.length > 0) {
6454
- wrappedLines.push({ text: charBuf, isLastInParagraph: false });
6455
- charBuf = ch;
6456
- } else {
6457
- charBuf = nextBuf;
6458
- }
6459
- }
6460
- current = charBuf;
6461
- }
6462
- }
6463
- wrappedLines.push({ text: current.trimEnd(), isLastInParagraph: true });
6464
- }
6465
- }
6765
+ const wrappedLines = extraOpts?.noWrapSingleLine ? normalizedText.split("\n").map((para) => ({ text: para, isLastInParagraph: true })) : wrapMixedCjkAndLatinLines(normalizedText, maxLineW, measureAscii);
6466
6766
  let singleLineDrawY = pageHeight - top - pad - fontSize * 0.85;
6467
6767
  if (style?.verticalAlign === "middle") {
6468
6768
  singleLineDrawY = pdfY + (height - fontSize * 0.75) / 2;
@@ -6477,12 +6777,22 @@ async function drawTextBox(pdfDoc, page, pageHeight, text, left, top, width, hei
6477
6777
  firstBaselineFromTop = Math.max(pad + fontSize * 0.78, height - pad - totalH + fontSize * 0.85);
6478
6778
  }
6479
6779
  const decoThickness = Math.max(0.6, fontSize * 0.065);
6780
+ const applyAsciiClip = !extraOpts?.noWrapSingleLine && bgWidth > 0 && height > 0;
6781
+ if (applyAsciiClip) {
6782
+ page.pushOperators(
6783
+ (0, import_pdf_lib3.pushGraphicsState)(),
6784
+ (0, import_pdf_lib3.rectangle)(left, pdfY, bgWidth, height),
6785
+ (0, import_pdf_lib3.clip)(),
6786
+ (0, import_pdf_lib3.endPath)()
6787
+ );
6788
+ }
6480
6789
  for (let i = 0; i < wrappedLines.length; i++) {
6481
6790
  const { text: lineText, isLastInParagraph } = wrappedLines[i];
6482
6791
  if (!lineText) continue;
6483
6792
  const baselineY = wrappedLines.length === 1 ? singleLineDrawY : pageHeight - top - (firstBaselineFromTop + i * lineHeight);
6484
- if (wrappedLines.length > 1 && !extraOpts?.noWrapSingleLine && baselineY < pdfY - 2) {
6485
- break;
6793
+ if (!extraOpts?.noWrapSingleLine) {
6794
+ if (i === 0 && height < fontSize * 0.55) break;
6795
+ if (i > 0 && baselineY - fontSize * 0.14 < pdfY) break;
6486
6796
  }
6487
6797
  const rawLineW = measureAscii(lineText);
6488
6798
  let drawX = left + pad;
@@ -6552,6 +6862,9 @@ async function drawTextBox(pdfDoc, page, pageHeight, text, left, top, width, hei
6552
6862
  });
6553
6863
  }
6554
6864
  }
6865
+ if (applyAsciiClip) {
6866
+ page.pushOperators((0, import_pdf_lib3.popGraphicsState)());
6867
+ }
6555
6868
  }
6556
6869
  function parseNumericCellValue(rawValue) {
6557
6870
  if (typeof rawValue === "number") {
@@ -6654,19 +6967,23 @@ function resolveDynamicTableRawRows(el, data) {
6654
6967
  }
6655
6968
  return el.rows ?? [];
6656
6969
  }
6657
- function paginatePdfTableRows(el, rawRows, pageHeight) {
6970
+ function paginatePdfTableRows(el, rawRows, pageHeight, paginationOpts) {
6658
6971
  const showHead = el.showHead !== false;
6972
+ const repeatHeader = paginationOpts?.repeatHeader ?? el.repeatHeader ?? true;
6973
+ const tablePagination = paginationOpts?.tablePagination ?? el.pagination ?? "auto";
6659
6974
  const headerH = showHead ? el.headerHeight ?? 26 : 0;
6660
6975
  const rowH = el.rowHeight ?? 24;
6661
6976
  const subtotalLabel = el.pageSubtotalLabel || "\u672C\u9875\u5C0F\u8BA1";
6662
6977
  const grandTotalLabel = el.grandTotalLabel || "\u603B\u8BA1";
6663
6978
  const subtotalSlot = el.showPageSubtotal ? 1 : 0;
6664
6979
  const grandTotalSlot = el.showGrandTotal ? 1 : 0;
6665
- const remainingOnStartPage = pageHeight - el.transform.top - 4;
6980
+ const marginTopGuard = Math.max(36, paginationOpts?.marginTopPt ?? 0);
6981
+ const bottomGuard = Math.max(8, paginationOpts?.marginBottomPt ?? 0);
6982
+ const remainingOnStartPage = pageHeight - el.transform.top - Math.max(4, paginationOpts?.marginBottomPt ?? 0);
6666
6983
  const minRequiredForHeaderPlusOneRow = headerH + rowH * (1 + subtotalSlot);
6667
- const shouldDeferOrphanHeader = showHead && el.avoidOrphanHeader !== false && rawRows.length > 0 && el.transform.top > 36 && (remainingOnStartPage < headerH + rowH || el.avoidOrphanHeader === true && remainingOnStartPage < minRequiredForHeaderPlusOneRow);
6668
- const effectiveTop = shouldDeferOrphanHeader ? 36 : el.transform.top;
6669
- const maxPageSpan = Math.max(headerH + rowH, pageHeight - effectiveTop - 8);
6984
+ const shouldDeferOrphanHeader = tablePagination !== "none" && showHead && el.avoidOrphanHeader !== false && rawRows.length > 0 && el.transform.top > marginTopGuard && (remainingOnStartPage < headerH + rowH || el.avoidOrphanHeader === true && remainingOnStartPage < minRequiredForHeaderPlusOneRow);
6985
+ const effectiveTop = shouldDeferOrphanHeader ? marginTopGuard : el.transform.top;
6986
+ const maxPageSpan = Math.max(headerH + rowH, pageHeight - effectiveTop - bottomGuard);
6670
6987
  const availableHeight = !shouldDeferOrphanHeader && el.transform.height > 0 ? Math.min(el.transform.height, maxPageSpan) : maxPageSpan;
6671
6988
  const totalBodySlots = Math.max(
6672
6989
  1 + subtotalSlot + grandTotalSlot,
@@ -6674,23 +6991,46 @@ function paginatePdfTableRows(el, rawRows, pageHeight) {
6674
6991
  );
6675
6992
  const maxDataRegular = Math.max(1, totalBodySlots - subtotalSlot);
6676
6993
  const maxDataFinal = Math.max(1, totalBodySlots - subtotalSlot - grandTotalSlot);
6994
+ const contHeaderH = showHead && repeatHeader ? headerH : 0;
6995
+ const contBodySlots = Math.max(
6996
+ totalBodySlots,
6997
+ Math.floor((availableHeight - contHeaderH) / rowH)
6998
+ );
6999
+ const maxContRegular = Math.max(1, contBodySlots - subtotalSlot);
7000
+ const maxContFinal = Math.max(1, contBodySlots - subtotalSlot - grandTotalSlot);
6677
7001
  const slices = [];
6678
- if (shouldDeferOrphanHeader) {
6679
- slices.push({ startRowIndex: 0, rows: [], deferred: true });
6680
- }
6681
- if (rawRows.length === 0) {
6682
- slices.push({ startRowIndex: 0, rows: [] });
7002
+ if (tablePagination === "none") {
7003
+ const cap = maxDataFinal;
7004
+ if (rawRows.length > cap) {
7005
+ paginationOpts?.onOverflow?.({
7006
+ capacityRows: cap,
7007
+ actualRows: rawRows.length,
7008
+ overflowRows: rawRows.length - cap
7009
+ });
7010
+ }
7011
+ slices.push({ startRowIndex: 0, rows: rawRows.slice(0, cap) });
6683
7012
  } else {
6684
- let cursor = 0;
6685
- while (cursor < rawRows.length) {
6686
- const remaining = rawRows.length - cursor;
6687
- if (remaining <= maxDataFinal) {
6688
- slices.push({ startRowIndex: cursor, rows: rawRows.slice(cursor) });
6689
- break;
7013
+ if (shouldDeferOrphanHeader) {
7014
+ slices.push({ startRowIndex: 0, rows: [], deferred: true });
7015
+ }
7016
+ if (rawRows.length === 0) {
7017
+ slices.push({ startRowIndex: 0, rows: [] });
7018
+ } else {
7019
+ let cursor = 0;
7020
+ let isFirstDataChunk = true;
7021
+ while (cursor < rawRows.length) {
7022
+ const remaining = rawRows.length - cursor;
7023
+ const activeFinalCap = isFirstDataChunk ? maxDataFinal : maxContFinal;
7024
+ const activeRegularCap = isFirstDataChunk ? maxDataRegular : maxContRegular;
7025
+ if (remaining <= activeFinalCap) {
7026
+ slices.push({ startRowIndex: cursor, rows: rawRows.slice(cursor) });
7027
+ break;
7028
+ }
7029
+ const takeCount = remaining <= activeRegularCap ? Math.max(1, Math.min(activeRegularCap, remaining - 1)) : activeRegularCap;
7030
+ slices.push({ startRowIndex: cursor, rows: rawRows.slice(cursor, cursor + takeCount) });
7031
+ cursor += takeCount;
7032
+ isFirstDataChunk = false;
6690
7033
  }
6691
- const takeCount = remaining <= maxDataRegular ? Math.max(1, Math.min(maxDataRegular, remaining - 1)) : maxDataRegular;
6692
- slices.push({ startRowIndex: cursor, rows: rawRows.slice(cursor, cursor + takeCount) });
6693
- cursor += takeCount;
6694
7034
  }
6695
7035
  }
6696
7036
  const grandTotalRow = el.showGrandTotal ? computePdfTableSummaryRow(rawRows, el.columns, grandTotalLabel) : void 0;
@@ -6730,7 +7070,40 @@ function resolveBorderDashArray(borderStyle, thickness) {
6730
7070
  }
6731
7071
  return void 0;
6732
7072
  }
6733
- async function drawTableCellWithBorders(pdfDoc, page, pageHeight, text, left, top, width, height, style, borderOpts, cjkState, colorType) {
7073
+ function computeShrunkCellFontSize(text, width, height, baseStyle, minFontSizePt, cjkState) {
7074
+ const maxFs = baseStyle.fontSize ?? 9.5;
7075
+ const minFs = Math.max(4, Math.min(maxFs, minFontSizePt));
7076
+ if (!text || maxFs <= minFs) return maxFs;
7077
+ const pad = baseStyle.padding ?? 5;
7078
+ const innerW = Math.max(1, width - pad * 2);
7079
+ const innerH = Math.max(1, height - pad * 2);
7080
+ const lhMul = baseStyle.lineHeight ?? 1.38;
7081
+ const charSp = baseStyle.characterSpacing ?? 0;
7082
+ let candidate = maxFs;
7083
+ while (candidate > minFs) {
7084
+ const measureFn = (s) => {
7085
+ if (cjkState) {
7086
+ return measureVectorCjkLine(s, candidate, cjkState, charSp);
7087
+ }
7088
+ let w = 0;
7089
+ for (const ch of s) {
7090
+ const cp = ch.codePointAt(0) ?? 32;
7091
+ w += cp > 127 ? candidate : candidate * 0.56;
7092
+ }
7093
+ const len = Array.from(s).length;
7094
+ return w + (len > 1 ? (len - 1) * charSp : 0);
7095
+ };
7096
+ const wrapped = wrapMixedCjkAndLatinLines(text, innerW, measureFn);
7097
+ const totalH = wrapped.length * candidate * lhMul;
7098
+ const anyWider = wrapped.some((ln) => ln.text.length > 0 && measureFn(ln.text) > innerW + 0.5);
7099
+ if (totalH <= innerH + 1.5 && !anyWider) {
7100
+ return Math.round(candidate * 100) / 100;
7101
+ }
7102
+ candidate = Math.max(minFs, Math.round((candidate - 0.5) * 100) / 100);
7103
+ }
7104
+ return minFs;
7105
+ }
7106
+ async function drawTableCellWithBorders(pdfDoc, page, pageHeight, text, left, top, width, height, style, borderOpts, cjkState, colorType, autoFitOpts) {
6734
7107
  const pdfY = pageHeight - top - height;
6735
7108
  const bg = parseHexColor(style.backgroundColor);
6736
7109
  if (bg && bg.a > 0) {
@@ -6744,6 +7117,7 @@ async function drawTableCellWithBorders(pdfDoc, page, pageHeight, text, left, to
6744
7117
  borderWidth: 0
6745
7118
  });
6746
7119
  }
7120
+ const effectiveFontSize = autoFitOpts?.enabled ? computeShrunkCellFontSize(text, width, height, style, autoFitOpts.minFontSize ?? 6, cjkState) : style.fontSize;
6747
7121
  await drawTextBox(
6748
7122
  pdfDoc,
6749
7123
  page,
@@ -6755,6 +7129,7 @@ async function drawTableCellWithBorders(pdfDoc, page, pageHeight, text, left, to
6755
7129
  height,
6756
7130
  {
6757
7131
  ...style,
7132
+ fontSize: effectiveFontSize,
6758
7133
  backgroundColor: void 0,
6759
7134
  borderWidth: 0,
6760
7135
  borderColor: void 0
@@ -6819,11 +7194,12 @@ async function drawTableCellWithBorders(pdfDoc, page, pageHeight, text, left, to
6819
7194
  });
6820
7195
  }
6821
7196
  }
6822
- async function drawTableChunk(pdfDoc, page, pageHeight, el, chunk, cjkState, colorType) {
7197
+ async function drawTableChunk(pdfDoc, page, pageHeight, el, chunk, cjkState, colorType, tableRenderOpts) {
6823
7198
  if (chunk.deferredOrphanHeader) return;
6824
7199
  const { left, top, width } = el.transform;
6825
- const showHead = el.showHead !== false;
6826
- const headerH = showHead ? el.headerHeight ?? 26 : 0;
7200
+ const repeatHeader = tableRenderOpts?.repeatHeader ?? el.repeatHeader ?? true;
7201
+ const showHeadOnThisChunk = el.showHead !== false && (chunk.chunkIndex === 0 || repeatHeader);
7202
+ const headerH = showHeadOnThisChunk ? el.headerHeight ?? 26 : 0;
6827
7203
  const rowH = el.rowHeight ?? 24;
6828
7204
  const colCount = el.columns.length;
6829
7205
  const totalRatio = el.columns.reduce((s, c) => s + (c.widthRatio || 1), 0) || 1;
@@ -6837,9 +7213,10 @@ async function drawTableChunk(pdfDoc, page, pageHeight, el, chunk, cjkState, col
6837
7213
  }
6838
7214
  }
6839
7215
  const stripeBg = el.zebraStripeColor ?? el.stripedColor;
7216
+ const zebraParity = tableRenderOpts?.zebraParity ?? el.zebraParity ?? "continuous";
6840
7217
  const defaultBorderW = el.borderWidth ?? 0.75;
6841
7218
  const defaultBorderCol = el.borderColor ?? "#cbd5e1";
6842
- if (showHead && headerH > 0) {
7219
+ if (showHeadOnThisChunk && headerH > 0) {
6843
7220
  for (let c = 0; c < colCount; c++) {
6844
7221
  const col = el.columns[c];
6845
7222
  const cw = colWidths[c];
@@ -6925,8 +7302,8 @@ async function drawTableChunk(pdfDoc, page, pageHeight, el, chunk, cjkState, col
6925
7302
  for (let r = 0; r < visibleBodyRows; r++) {
6926
7303
  const rowY = top + headerH + r * rowH;
6927
7304
  const rowCells = chunk.formattedRows[r];
6928
- const isZebra = r % 2 === 1;
6929
7305
  const globalR = chunk.startRowIndex + r;
7306
+ const isZebra = (zebraParity === "chunk" ? r : globalR) % 2 === 1;
6930
7307
  for (let c = 0; c < colCount; c++) {
6931
7308
  const localKey = `${r}:${c}`;
6932
7309
  if (coveredCells.has(localKey)) continue;
@@ -6945,6 +7322,9 @@ async function drawTableChunk(pdfDoc, page, pageHeight, el, chunk, cjkState, col
6945
7322
  const vAlign = cellStyle?.verticalAlign ?? metaVertAligns[globalCellKey] ?? metaVertAligns[localKey] ?? col.verticalAlign ?? el.bodyStyle?.verticalAlign ?? "middle";
6946
7323
  const hAlign = cellStyle?.textAlign ?? col.align ?? el.bodyStyle?.textAlign ?? "left";
6947
7324
  const cellText = mergeInfo && mergeInfo.sourceGlobalRow < chunk.startRowIndex ? "" : rowCells[c] ?? "";
7325
+ const resolvedCellBg = cellStyle?.backgroundColor ?? (isZebra && stripeBg ? stripeBg : el.bodyStyle?.backgroundColor ?? "#ffffff");
7326
+ const autoFitEnabled = Boolean(col.autoFitFontSize ?? el.autoFitFontSize);
7327
+ const autoFitMinFs = col.minFontSize ?? el.minFontSize ?? 6;
6948
7328
  await drawTableCellWithBorders(
6949
7329
  pdfDoc,
6950
7330
  page,
@@ -6956,10 +7336,10 @@ async function drawTableChunk(pdfDoc, page, pageHeight, el, chunk, cjkState, col
6956
7336
  mergedH,
6957
7337
  {
6958
7338
  fontSize: 9.5,
6959
- backgroundColor: isZebra && stripeBg ? stripeBg : "#ffffff",
6960
7339
  padding: 5,
6961
7340
  ...el.bodyStyle,
6962
7341
  ...cellStyle,
7342
+ backgroundColor: resolvedCellBg,
6963
7343
  textAlign: hAlign,
6964
7344
  verticalAlign: vAlign
6965
7345
  },
@@ -6970,7 +7350,8 @@ async function drawTableChunk(pdfDoc, page, pageHeight, el, chunk, cjkState, col
6970
7350
  borderStyle: cellStyle?.borderStyle ?? el.borderStyle
6971
7351
  },
6972
7352
  cjkState,
6973
- colorType
7353
+ colorType,
7354
+ autoFitEnabled ? { enabled: true, minFontSize: autoFitMinFs } : void 0
6974
7355
  );
6975
7356
  }
6976
7357
  currentRowSlot += 1;
@@ -7239,18 +7620,39 @@ async function drawRichOrColumnTextBox(pdfDoc, page, pageHeight, spans, left, to
7239
7620
  const col = parseHexColor(seg.colorHex) ?? { r: 0.12, g: 0.14, b: 0.16, a: 1 };
7240
7621
  const pdfCol = toPdfLibColor(col, colorType);
7241
7622
  if (hasNonAscii(seg.text) && cjkState || cjkState?.mode === "subset-ttf") {
7242
- const fontKey = getOrRegisterPageCjkFontKey(page, cjkState);
7243
- const hexStr = encodeVectorCjkLineHex(seg.text, cjkState);
7623
+ const { fontKey, activeSubset, usedDedicatedBold } = getOrRegisterPageCjkFontKey(
7624
+ page,
7625
+ cjkState,
7626
+ Boolean(seg.bold)
7627
+ );
7628
+ const hexStr = encodeVectorCjkLineHex(seg.text, cjkState, activeSubset);
7244
7629
  const fillOp = colorType === "cmyk" ? (() => {
7245
7630
  const cm = rgbToCmyk(col.r, col.g, col.b);
7246
7631
  return (0, import_pdf_lib3.setFillingCmykColor)(cm.c, cm.m, cm.y, cm.k);
7247
7632
  })() : (0, import_pdf_lib3.setFillingRgbColor)(col.r, col.g, col.b);
7633
+ const boldOps = seg.bold && !usedDedicatedBold ? [
7634
+ import_pdf_lib3.PDFOperator.of("Tr", [import_pdf_lib3.PDFNumber.of(2)]),
7635
+ (0, import_pdf_lib3.setLineWidth)(Math.max(0.25, seg.fontSize * 0.032)),
7636
+ colorType === "cmyk" ? (() => {
7637
+ const cm = rgbToCmyk(col.r, col.g, col.b);
7638
+ return (0, import_pdf_lib3.setStrokingCmykColor)(cm.c, cm.m, cm.y, cm.k);
7639
+ })() : (0, import_pdf_lib3.setStrokingRgbColor)(col.r, col.g, col.b)
7640
+ ] : [];
7641
+ const posOp = seg.italic ? import_pdf_lib3.PDFOperator.of("Tm", [
7642
+ import_pdf_lib3.PDFNumber.of(1),
7643
+ import_pdf_lib3.PDFNumber.of(0),
7644
+ import_pdf_lib3.PDFNumber.of(0.2126),
7645
+ import_pdf_lib3.PDFNumber.of(1),
7646
+ import_pdf_lib3.PDFNumber.of(segX),
7647
+ import_pdf_lib3.PDFNumber.of(baselineY)
7648
+ ]) : (0, import_pdf_lib3.moveText)(segX, baselineY);
7248
7649
  page.pushOperators(
7249
7650
  (0, import_pdf_lib3.pushGraphicsState)(),
7250
7651
  (0, import_pdf_lib3.beginText)(),
7251
7652
  fillOp,
7653
+ ...boldOps,
7252
7654
  (0, import_pdf_lib3.setFontAndSize)(fontKey, seg.fontSize),
7253
- (0, import_pdf_lib3.moveText)(segX, baselineY),
7655
+ posOp,
7254
7656
  (0, import_pdf_lib3.showText)(import_pdf_lib3.PDFHexString.of(hexStr)),
7255
7657
  (0, import_pdf_lib3.endText)(),
7256
7658
  (0, import_pdf_lib3.popGraphicsState)()
@@ -7748,7 +8150,7 @@ async function drawInvisibleSearchableOcrSpans(pdfDoc, pdfPage, pageHeight, span
7748
8150
  cjkTextMode: "cid-vector"
7749
8151
  });
7750
8152
  }
7751
- const fontKey = getOrRegisterPageCjkFontKey(pdfPage, localCjkState);
8153
+ const { fontKey } = getOrRegisterPageCjkFontKey(pdfPage, localCjkState);
7752
8154
  const hexStr = encodeVectorCjkLineHex(txt, localCjkState);
7753
8155
  pdfPage.pushOperators(
7754
8156
  (0, import_pdf_lib3.pushGraphicsState)(),
@@ -7835,6 +8237,7 @@ async function exportPdfBytes(snapshot, runtimeData, options) {
7835
8237
  options?.accessibilityTagged ?? snapshot.accessibilityTagged ?? snapshot.metadata?.accessibilityTagged
7836
8238
  );
7837
8239
  const optimizeSize = Boolean(options?.optimizeSize);
8240
+ const preResolvedFonts = await resolveRenderFontsForExport(snapshot, options);
7838
8241
  const pdfDoc = await import_pdf_lib3.PDFDocument.create();
7839
8242
  if (snapshot.metadata?.sanitized) {
7840
8243
  pdfDoc.setTitle("");
@@ -7843,8 +8246,19 @@ async function exportPdfBytes(snapshot, runtimeData, options) {
7843
8246
  pdfDoc.setKeywords([]);
7844
8247
  pdfDoc.setCreator("");
7845
8248
  pdfDoc.setProducer("");
8249
+ } else {
8250
+ pdfDoc.setProducer("Univer PDF Engine (@yudaocode/univer-pdfs)");
8251
+ pdfDoc.setCreator("Univer PDF Engine (@yudaocode/univer-pdfs)");
8252
+ }
8253
+ const fixedDateRaw = options?.render?.creationDate;
8254
+ if (fixedDateRaw !== void 0) {
8255
+ const fixedDate = fixedDateRaw instanceof Date ? fixedDateRaw : new Date(fixedDateRaw);
8256
+ if (!Number.isNaN(fixedDate.getTime())) {
8257
+ pdfDoc.setCreationDate(fixedDate);
8258
+ pdfDoc.setModificationDate(fixedDate);
8259
+ }
7846
8260
  }
7847
- const cjkState = initVectorCjkEmbedState(pdfDoc, snapshot, effectiveData, options);
8261
+ const cjkState = initVectorCjkEmbedState(pdfDoc, snapshot, effectiveData, options, preResolvedFonts);
7848
8262
  const ocgLayerMap = attachOptionalContentLayers(pdfDoc, snapshot.layers ?? []);
7849
8263
  const taggedStructItems = [];
7850
8264
  const usedAcroFieldNames = /* @__PURE__ */ new Set();
@@ -8045,6 +8459,7 @@ async function exportPdfBytes(snapshot, runtimeData, options) {
8045
8459
  const tableChunksByElementId = {};
8046
8460
  const listChunksByElementId = {};
8047
8461
  let maxChunksOnPage = 1;
8462
+ let primaryPaginatedTable = null;
8048
8463
  const visibleElements = [];
8049
8464
  let hasExpandText = false;
8050
8465
  for (const elementId of order) {
@@ -8056,11 +8471,34 @@ async function exportPdfBytes(snapshot, runtimeData, options) {
8056
8471
  }
8057
8472
  if (el.type === "table" /* TABLE */) {
8058
8473
  const rawRows = resolveDynamicTableRawRows(el, effectiveData);
8059
- const chunks = paginatePdfTableRows(el, rawRows, estSize.height);
8474
+ const chunks = paginatePdfTableRows(el, rawRows, estSize.height, {
8475
+ marginTopPt,
8476
+ marginBottomPt,
8477
+ tablePagination: options?.render?.tablePagination ?? el.pagination,
8478
+ repeatHeader: options?.render?.repeatHeader ?? el.repeatHeader,
8479
+ onOverflow: ({ capacityRows, actualRows, overflowRows }) => {
8480
+ options?.render?.onWarning?.({
8481
+ code: "TABLE_OVERFLOW",
8482
+ pageId,
8483
+ elementId,
8484
+ message: `\u8868\u683C ${elementId} \u6570\u636E\u884C\u6570\uFF08${actualRows}\uFF09\u8D85\u51FA\u5355\u9875\u53EF\u5BB9\u7EB3\u884C\u6570\uFF08${capacityRows}\uFF09\uFF0C\u5DF2\u622A\u65AD\u8D85\u51FA ${overflowRows} \u884C`,
8485
+ details: {
8486
+ pageId,
8487
+ elementId,
8488
+ capacityRows,
8489
+ actualRows,
8490
+ overflowRows
8491
+ }
8492
+ });
8493
+ }
8494
+ });
8060
8495
  tableChunksByElementId[elementId] = chunks;
8061
8496
  if (chunks.length > maxChunksOnPage) {
8062
8497
  maxChunksOnPage = chunks.length;
8063
8498
  }
8499
+ if (chunks.length > 1 && !primaryPaginatedTable) {
8500
+ primaryPaginatedTable = el;
8501
+ }
8064
8502
  }
8065
8503
  if (el.type === "list" /* LIST */ && el.overflow !== "clip") {
8066
8504
  const preResolvedItems = (el.items ?? []).map(
@@ -8097,13 +8535,82 @@ async function exportPdfBytes(snapshot, runtimeData, options) {
8097
8535
  maxChunksOnPage = dynamicSplitRanges.length;
8098
8536
  }
8099
8537
  }
8538
+ let tableFlowPlan;
8539
+ if (primaryPaginatedTable && !hasExpandText) {
8540
+ const tChunks = tableChunksByElementId[primaryPaginatedTable.id] ?? [];
8541
+ if (tChunks.length > 1) {
8542
+ const origTop = primaryPaginatedTable.transform.top;
8543
+ const origBot = origTop + primaryPaginatedTable.transform.height;
8544
+ const aboveOnceIds = /* @__PURE__ */ new Set();
8545
+ const trailingEls = [];
8546
+ let hasRepeatingAbove = false;
8547
+ for (const other of visibleElements) {
8548
+ if (other.id === primaryPaginatedTable.id) continue;
8549
+ if (other.type === "table" /* TABLE */ || other.type === "list" /* LIST */) continue;
8550
+ const isPageTokenBanner = other.type === "text" /* TEXT */ && /\{\{\s*(?:page|totalPages)\s*\}\}/.test(other.content || "");
8551
+ if (isPageTokenBanner) {
8552
+ if (other.transform.top < origTop) {
8553
+ hasRepeatingAbove = true;
8554
+ }
8555
+ continue;
8556
+ }
8557
+ if (other.transform.top < origTop) {
8558
+ aboveOnceIds.add(other.id);
8559
+ } else {
8560
+ trailingEls.push(other);
8561
+ }
8562
+ }
8563
+ const continuationTableTop = hasRepeatingAbove ? origTop : Math.max(24, marginTopPt || 36);
8564
+ const lastTableChunkIdx = tChunks.length - 1;
8565
+ const lastChunk = tChunks[lastTableChunkIdx];
8566
+ const effRepeatHdr = options?.render?.repeatHeader ?? primaryPaginatedTable.repeatHeader ?? true;
8567
+ const lastShowHead = primaryPaginatedTable.showHead !== false && (lastTableChunkIdx === 0 || effRepeatHdr);
8568
+ const lastHdrH = lastShowHead ? primaryPaginatedTable.headerHeight ?? 26 : 0;
8569
+ const lastSlots = lastChunk.formattedRows.length + (lastChunk.subtotalRow ? 1 : 0) + (lastChunk.grandTotalRow ? 1 : 0);
8570
+ const lastTableStart = lastTableChunkIdx === 0 ? origTop : continuationTableTop;
8571
+ const lastTableBottom = lastTableStart + lastHdrH + lastSlots * (primaryPaginatedTable.rowHeight ?? 24);
8572
+ const trailingIds = /* @__PURE__ */ new Set();
8573
+ const topOverrides = {};
8574
+ let trailingTargetChunk = lastTableChunkIdx;
8575
+ if (trailingEls.length > 0) {
8576
+ const gapFor = (o) => o.transform.top >= origBot ? o.transform.top - origBot : Math.max(12, o.transform.top - origTop);
8577
+ const bottomLimit = estSize.height - Math.max(8, marginBottomPt);
8578
+ const fitsOnLastTablePage = trailingEls.every(
8579
+ (o) => lastTableBottom + gapFor(o) + o.transform.height <= bottomLimit
8580
+ );
8581
+ if (fitsOnLastTablePage) {
8582
+ for (const o of trailingEls) {
8583
+ trailingIds.add(o.id);
8584
+ topOverrides[o.id] = lastTableBottom + gapFor(o);
8585
+ }
8586
+ } else {
8587
+ trailingTargetChunk = maxChunksOnPage;
8588
+ maxChunksOnPage += 1;
8589
+ const minTop = Math.min(...trailingEls.map((o) => o.transform.top));
8590
+ const baseStart = Math.max(24, marginTopPt || 36);
8591
+ for (const o of trailingEls) {
8592
+ trailingIds.add(o.id);
8593
+ topOverrides[o.id] = baseStart + (o.transform.top - minTop);
8594
+ }
8595
+ }
8596
+ }
8597
+ tableFlowPlan = {
8598
+ aboveOnceIds,
8599
+ trailingIds,
8600
+ trailingTargetChunk,
8601
+ topOverrides,
8602
+ continuationTableTop
8603
+ };
8604
+ }
8605
+ }
8100
8606
  for (let cIdx = 0; cIdx < maxChunksOnPage; cIdx++) {
8101
8607
  physicalPlan.push({
8102
8608
  pageId,
8103
8609
  chunkIndex: cIdx,
8104
8610
  tableChunksByElementId,
8105
8611
  listChunksByElementId,
8106
- dynamicSplitRanges
8612
+ dynamicSplitRanges,
8613
+ tableFlowPlan
8107
8614
  });
8108
8615
  }
8109
8616
  }
@@ -8232,6 +8739,20 @@ async function exportPdfBytes(snapshot, runtimeData, options) {
8232
8739
  }
8233
8740
  }
8234
8741
  for (const { elementId, el, isStaticSchema } of renderQueue) {
8742
+ if (!isStaticSchema && planItem.tableFlowPlan && el.type !== "table" /* TABLE */ && el.type !== "list" /* LIST */) {
8743
+ if (planItem.tableFlowPlan.aboveOnceIds.has(elementId) && chunkIndex !== 0) {
8744
+ continue;
8745
+ }
8746
+ if (planItem.tableFlowPlan.trailingIds.has(elementId) && chunkIndex !== planItem.tableFlowPlan.trailingTargetChunk) {
8747
+ continue;
8748
+ }
8749
+ }
8750
+ if (!isStaticSchema && el.type === "table" /* TABLE */ && tableChunksByElementId[elementId]) {
8751
+ const tChunk = tableChunksByElementId[elementId][chunkIndex];
8752
+ if (!tChunk || tChunk.deferredOrphanHeader) {
8753
+ continue;
8754
+ }
8755
+ }
8235
8756
  if (!isStaticSchema && planItem.dynamicSplitRanges && planItem.dynamicSplitRanges.length > 1 && el.type !== "table" /* TABLE */ && el.type !== "list" /* LIST */ && (!activeDynamicRange || !activeDynamicRange.elementIds.includes(elementId))) {
8236
8757
  continue;
8237
8758
  }
@@ -8284,7 +8805,7 @@ async function exportPdfBytes(snapshot, runtimeData, options) {
8284
8805
  try {
8285
8806
  const elColorType = options?.colorType ?? el.colorType ?? snapshot.metadata?.colorType;
8286
8807
  const placement = !isStaticSchema ? activeDynamicRange?.placements.find((p) => p.id === elementId) : void 0;
8287
- let top = el.transform.top + offsetYPt;
8808
+ let top = (!isStaticSchema && planItem.tableFlowPlan && planItem.tableFlowPlan.topOverrides[elementId] !== void 0 && chunkIndex === planItem.tableFlowPlan.trailingTargetChunk ? planItem.tableFlowPlan.topOverrides[elementId] : el.transform.top) + offsetYPt;
8288
8809
  let height = el.transform.height;
8289
8810
  const left = el.transform.left + offsetXPt;
8290
8811
  const width = el.transform.width;
@@ -9473,10 +9994,15 @@ async function exportPdfBytes(snapshot, runtimeData, options) {
9473
9994
  elColorType
9474
9995
  );
9475
9996
  } else if (el.type === "table" /* TABLE */) {
9476
- const chunks = tableChunksByElementId[elementId] ?? paginatePdfTableRows(el, resolveDynamicTableRawRows(el, effectiveData), pageHeight);
9997
+ const chunks = tableChunksByElementId[elementId] ?? paginatePdfTableRows(el, resolveDynamicTableRawRows(el, effectiveData), pageHeight, {
9998
+ marginTopPt,
9999
+ marginBottomPt,
10000
+ tablePagination: options?.render?.tablePagination ?? el.pagination,
10001
+ repeatHeader: options?.render?.repeatHeader ?? el.repeatHeader
10002
+ });
9477
10003
  const activeChunk = chunks[chunkIndex];
9478
10004
  if (activeChunk && !activeChunk.deferredOrphanHeader) {
9479
- const tableTop = chunkIndex > 0 && chunks[0]?.deferredOrphanHeader ? Math.max(24, marginTopPt || 36) + offsetYPt : top;
10005
+ const tableTop = chunkIndex > 0 && planItem.tableFlowPlan ? planItem.tableFlowPlan.continuationTableTop + offsetYPt : chunkIndex > 0 && chunks[0]?.deferredOrphanHeader ? Math.max(24, marginTopPt || 36) + offsetYPt : top;
9480
10006
  const shiftedTableEl = {
9481
10007
  ...el,
9482
10008
  transform: { ...el.transform, left, top: tableTop }
@@ -9488,7 +10014,11 @@ async function exportPdfBytes(snapshot, runtimeData, options) {
9488
10014
  shiftedTableEl,
9489
10015
  activeChunk,
9490
10016
  cjkState,
9491
- elColorType
10017
+ elColorType,
10018
+ {
10019
+ repeatHeader: options?.render?.repeatHeader,
10020
+ zebraParity: options?.render?.zebraParity
10021
+ }
9492
10022
  );
9493
10023
  }
9494
10024
  } else if (el.type === "annotation" /* ANNOTATION */) {
@@ -9742,7 +10272,7 @@ async function exportPdfBytes(snapshot, runtimeData, options) {
9742
10272
  });
9743
10273
  }
9744
10274
  } else if (cjkState) {
9745
- const fontKey = getOrRegisterPageCjkFontKey(pdfPage, cjkState);
10275
+ const { fontKey } = getOrRegisterPageCjkFontKey(pdfPage, cjkState);
9746
10276
  const hexWm = encodeVectorCjkLineHex(watermarkText, cjkState);
9747
10277
  for (let wy = 90; wy < pageHeight - 40; wy += isTiled ? 185 : pageHeight) {
9748
10278
  for (let wx = 45; wx < pageWidth2 - 50; wx += isTiled ? 225 : pageWidth2) {
@@ -10276,6 +10806,111 @@ function collectUsedCodePointsFromPdfUnit(unitData, data) {
10276
10806
  });
10277
10807
  return Array.from(codePoints).sort((a, b) => a - b);
10278
10808
  }
10809
+ function collectMissingGlyphsFromPdfUnit(unitData, hasGlyph, data, formatTableCell) {
10810
+ const effectiveData = data ?? unitData.metadata?.sampleData;
10811
+ const results = [];
10812
+ const checkStrings = (pageId, elementId, strings) => {
10813
+ const missingSet = /* @__PURE__ */ new Set();
10814
+ for (const s of strings) {
10815
+ if (!s) continue;
10816
+ for (const ch of s) {
10817
+ const cp = ch.codePointAt(0);
10818
+ if (cp === void 0 || cp < 32 || cp === 127) continue;
10819
+ if (!hasGlyph(cp)) {
10820
+ missingSet.add(cp);
10821
+ }
10822
+ }
10823
+ }
10824
+ if (missingSet.size > 0) {
10825
+ const sorted = Array.from(missingSet).sort((a, b) => a - b);
10826
+ results.push({
10827
+ ...pageId ? { pageId } : {},
10828
+ elementId,
10829
+ chars: sorted.map((cp) => String.fromCodePoint(cp)),
10830
+ codePoints: sorted.map((cp) => `U+${cp.toString(16).toUpperCase().padStart(4, "0")}`)
10831
+ });
10832
+ }
10833
+ };
10834
+ if (unitData.metadata?.watermarkText && unitData.metadata?.watermarkConfig?.enabled !== false) {
10835
+ checkStrings(void 0, "__watermark__", [String(unitData.metadata.watermarkText)]);
10836
+ }
10837
+ const totalPages = unitData.document.pageOrder.length;
10838
+ const startPageOffset = Math.max(1, Number(unitData.metadata?.startPageNumber ?? 1) || 1);
10839
+ unitData.document.pageOrder.forEach((pageId, pIdx) => {
10840
+ const pageCtx = { pageNumber: startPageOffset + pIdx, totalPages: startPageOffset + totalPages - 1 };
10841
+ const map = unitData.editState.elementsByPage[pageId] ?? {};
10842
+ const order = unitData.editState.elementOrderByPage[pageId] ?? Object.keys(map);
10843
+ for (const id of order) {
10844
+ const el = map[id];
10845
+ if (!el || el.hidden) continue;
10846
+ if (el.type === "text" /* TEXT */) {
10847
+ const texts = [
10848
+ resolveTemplateString(el.content, el.fieldKey || el.bindingField, effectiveData, pageCtx)
10849
+ ];
10850
+ if (el.richSpans?.length) {
10851
+ for (const span of el.richSpans) {
10852
+ texts.push(resolveTemplateString(span.text, void 0, effectiveData, pageCtx));
10853
+ }
10854
+ }
10855
+ checkStrings(pageId, id, texts);
10856
+ } else if (el.type === "list" /* LIST */) {
10857
+ checkStrings(
10858
+ pageId,
10859
+ id,
10860
+ el.items.map((item) => resolveTemplateString(item, void 0, effectiveData, pageCtx))
10861
+ );
10862
+ } else if (el.type === "stamp" /* STAMP */) {
10863
+ checkStrings(pageId, id, [el.primaryText, el.secondaryText]);
10864
+ } else if (el.type === "table" /* TABLE */) {
10865
+ const texts = [];
10866
+ if (el.showHead !== false) {
10867
+ for (const col of el.columns) {
10868
+ texts.push(col.header);
10869
+ }
10870
+ }
10871
+ if (el.showPageSubtotal) texts.push(el.pageSubtotalLabel || "\u672C\u9875\u5C0F\u8BA1");
10872
+ if (el.showGrandTotal) texts.push(el.grandTotalLabel || "\u603B\u8BA1");
10873
+ const rawRows = [];
10874
+ if (effectiveData && el.bindingField) {
10875
+ const bound = getByPathLocal(effectiveData, el.bindingField);
10876
+ if (Array.isArray(bound)) {
10877
+ for (const rowObj of bound) {
10878
+ if (Array.isArray(rowObj)) {
10879
+ rawRows.push(rowObj);
10880
+ } else if (rowObj && typeof rowObj === "object") {
10881
+ rawRows.push(el.columns.map((col) => rowObj[col.field]));
10882
+ }
10883
+ }
10884
+ }
10885
+ }
10886
+ const effectiveRows = rawRows.length > 0 ? rawRows : el.rows ?? [];
10887
+ for (const row of effectiveRows) {
10888
+ el.columns.forEach((col, cIdx) => {
10889
+ const rawVal = row[cIdx];
10890
+ texts.push(formatTableCell ? formatTableCell(rawVal, col) : String(rawVal ?? ""));
10891
+ });
10892
+ }
10893
+ checkStrings(pageId, id, texts);
10894
+ } else if (el.type === "checkbox" /* CHECKBOX */) {
10895
+ checkStrings(pageId, id, [el.label]);
10896
+ } else if (el.type === "radioGroup" /* RADIO_GROUP */) {
10897
+ checkStrings(pageId, id, [...el.options, el.value]);
10898
+ } else if (el.type === "select" /* SELECT */) {
10899
+ checkStrings(pageId, id, [...el.options, el.value, el.placeholder]);
10900
+ } else if (el.type === "dateTime" /* DATE_TIME */) {
10901
+ const key = el.formFieldName || el.fieldKey || el.bindingField;
10902
+ const bound = key ? getByPathLocal(effectiveData, key) : void 0;
10903
+ const rawVal = bound !== void 0 && bound !== null ? String(bound) : el.value ?? "";
10904
+ checkStrings(pageId, id, [formatPdfDateTimeValue(rawVal, el.format, el.dateKind, el.locale)]);
10905
+ } else if (el.type === "redaction" /* REDACTION */) {
10906
+ checkStrings(pageId, id, [el.overlayLabel]);
10907
+ } else if (el.type === "annotation" /* ANNOTATION */) {
10908
+ checkStrings(pageId, id, [el.author, el.comment]);
10909
+ }
10910
+ }
10911
+ });
10912
+ return results;
10913
+ }
10279
10914
  function readTag(bytes, offset) {
10280
10915
  return String.fromCharCode(
10281
10916
  bytes[offset],
@@ -10409,6 +11044,9 @@ function parseTrueTypeInternal(ttfBytes) {
10409
11044
  }
10410
11045
  }
10411
11046
  const head = tableSlices.get("head");
11047
+ if (head.byteLength < 54) {
11048
+ throw new Error("[UniverPdfs] Invalid TrueType font: truncated head table.");
11049
+ }
10412
11050
  const headView = new DataView(head.buffer, head.byteOffset, head.byteLength);
10413
11051
  const unitsPerEm = headView.getUint16(18, false) || 1e3;
10414
11052
  const xMin = headView.getInt16(36, false);
@@ -10417,9 +11055,18 @@ function parseTrueTypeInternal(ttfBytes) {
10417
11055
  const yMax = headView.getInt16(42, false);
10418
11056
  const indexToLocFormat = headView.getInt16(50, false) === 1 ? 1 : 0;
10419
11057
  const maxp = tableSlices.get("maxp");
11058
+ if (maxp.byteLength < 6) {
11059
+ throw new Error("[UniverPdfs] Invalid TrueType font: truncated maxp table.");
11060
+ }
10420
11061
  const maxpView = new DataView(maxp.buffer, maxp.byteOffset, maxp.byteLength);
10421
11062
  const numGlyphs = maxpView.getUint16(4, false);
11063
+ if (numGlyphs <= 0) {
11064
+ throw new Error("[UniverPdfs] Invalid TrueType font: numGlyphs is 0.");
11065
+ }
10422
11066
  const hhea = tableSlices.get("hhea");
11067
+ if (hhea.byteLength < 36) {
11068
+ throw new Error("[UniverPdfs] Invalid TrueType font: truncated hhea table.");
11069
+ }
10423
11070
  const hheaView = new DataView(hhea.buffer, hhea.byteOffset, hhea.byteLength);
10424
11071
  const ascent = hheaView.getInt16(4, false);
10425
11072
  const descent = hheaView.getInt16(6, false);
@@ -10460,6 +11107,9 @@ function parseTrueTypeInternal(ttfBytes) {
10460
11107
  }
10461
11108
  }
10462
11109
  const cmapMap = parseCmapTable(tableSlices.get("cmap"));
11110
+ if (cmapMap.size === 0) {
11111
+ throw new Error("[UniverPdfs] Invalid TrueType font: empty or unreadable cmap table.");
11112
+ }
10463
11113
  return {
10464
11114
  inspection: {
10465
11115
  sfntVersion,
@@ -10481,6 +11131,9 @@ function parseTrueTypeInternal(ttfBytes) {
10481
11131
  glyfTable
10482
11132
  };
10483
11133
  }
11134
+ function inspectTrueTypeFont(ttfBytes) {
11135
+ return parseTrueTypeInternal(ttfBytes).inspection;
11136
+ }
10484
11137
  function getCompositeComponentGids(glyphSlice) {
10485
11138
  if (glyphSlice.byteLength < 10) return [];
10486
11139
  const view = new DataView(glyphSlice.buffer, glyphSlice.byteOffset, glyphSlice.byteLength);
@@ -10761,7 +11414,7 @@ function subsetTrueTypeFont(ttfBytes, codePoints) {
10761
11414
  const cmapPairs = [];
10762
11415
  for (const cp of uniqueCps) {
10763
11416
  const oldGid = cmapMap.get(cp);
10764
- if (oldGid !== void 0 && oldGid > 0) {
11417
+ if (oldGid !== void 0 && oldGid > 0 && oldGid < inspection.numGlyphs) {
10765
11418
  const newGid = enqueueOldGid(oldGid);
10766
11419
  codePointToGid[cp] = newGid;
10767
11420
  cmapPairs.push({ cp, gid: newGid });