@yudaocode/univer-pdfs 1.6.212 → 1.6.214

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.
@@ -6617,6 +6617,94 @@ function drawVectorSvgOnPdfPage(pdfPage, pageHeight, left, top, width, height, s
6617
6617
  }
6618
6618
 
6619
6619
  // src/exporter/pdf-exporter.ts
6620
+ var PdfRenderError = class extends Error {
6621
+ constructor(code, message, extra) {
6622
+ super(message);
6623
+ this.name = "PdfRenderError";
6624
+ this.code = code;
6625
+ if (extra?.failedFonts) this.failedFonts = extra.failedFonts;
6626
+ if (extra?.missingGlyphs) this.missingGlyphs = extra.missingGlyphs;
6627
+ }
6628
+ };
6629
+ var pdfFontUrlByteCache = /* @__PURE__ */ new Map();
6630
+ function clearPdfFontUrlCache() {
6631
+ pdfFontUrlByteCache.clear();
6632
+ }
6633
+ function bytesToBase64Standard(bytes) {
6634
+ if (typeof Buffer !== "undefined") {
6635
+ return Buffer.from(bytes).toString("base64");
6636
+ }
6637
+ let bin = "";
6638
+ for (let i = 0; i < bytes.byteLength; i++) {
6639
+ bin += String.fromCharCode(bytes[i]);
6640
+ }
6641
+ return btoa(bin);
6642
+ }
6643
+ async function verifyFontSubresourceIntegrity(bytes, integrity) {
6644
+ const trimmed = integrity.trim();
6645
+ if (!trimmed) return;
6646
+ const m = trimmed.match(/^(sha256|sha384|sha512)-([A-Za-z0-9+/=_-]+)$/i);
6647
+ if (!m) {
6648
+ throw new Error(`Unsupported integrity format '${trimmed}' (expected sha256-/sha384-/sha512-).`);
6649
+ }
6650
+ const algoMap = {
6651
+ sha256: "SHA-256",
6652
+ sha384: "SHA-384",
6653
+ sha512: "SHA-512"
6654
+ };
6655
+ const algo = algoMap[m[1].toLowerCase()];
6656
+ const expectedB64 = m[2].replace(/-/g, "+").replace(/_/g, "/");
6657
+ const subtle = globalThis.crypto?.subtle;
6658
+ if (!subtle) {
6659
+ throw new Error("Web Crypto API is unavailable to verify font integrity.");
6660
+ }
6661
+ const digestBuf = await subtle.digest(
6662
+ algo,
6663
+ bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength)
6664
+ );
6665
+ const actualB64 = bytesToBase64Standard(new Uint8Array(digestBuf)).replace(/=+$/, "");
6666
+ const normExpected = expectedB64.replace(/=+$/, "");
6667
+ if (actualB64 !== normExpected) {
6668
+ throw new Error(`Font SRI integrity mismatch (${m[1]}).`);
6669
+ }
6670
+ }
6671
+ async function loadSingleFontCandidate(src) {
6672
+ let rawBytes;
6673
+ if (src.bytes != null) {
6674
+ rawBytes = src.bytes instanceof Uint8Array ? src.bytes : new Uint8Array(src.bytes);
6675
+ if (src.integrity) {
6676
+ await verifyFontSubresourceIntegrity(rawBytes, src.integrity);
6677
+ }
6678
+ } else if (src.url) {
6679
+ const cacheKey = `${src.url}|${src.integrity ?? ""}`;
6680
+ const cached = pdfFontUrlByteCache.get(cacheKey);
6681
+ if (cached) {
6682
+ rawBytes = cached;
6683
+ } else {
6684
+ let resp;
6685
+ try {
6686
+ resp = await fetch(src.url);
6687
+ } catch (err) {
6688
+ throw new Error(`Network error fetching '${src.url}': ${err?.message || String(err)}`);
6689
+ }
6690
+ if (!resp.ok) {
6691
+ throw new Error(`HTTP ${resp.status} fetching '${src.url}'.`);
6692
+ }
6693
+ const ab = await resp.arrayBuffer();
6694
+ rawBytes = new Uint8Array(ab);
6695
+ if (src.integrity) {
6696
+ await verifyFontSubresourceIntegrity(rawBytes, src.integrity);
6697
+ }
6698
+ inspectTrueTypeFont(rawBytes);
6699
+ pdfFontUrlByteCache.set(cacheKey, rawBytes);
6700
+ return rawBytes;
6701
+ }
6702
+ } else {
6703
+ throw new Error("Font source has neither bytes nor url.");
6704
+ }
6705
+ inspectTrueTypeFont(rawBytes);
6706
+ return rawBytes;
6707
+ }
6620
6708
  function getByPath(data, path) {
6621
6709
  if (!data || !path) return void 0;
6622
6710
  return safeLookupVariablePath(data, path);
@@ -6821,11 +6909,166 @@ endbfchar`);
6821
6909
  "end"
6822
6910
  ].join("\n");
6823
6911
  }
6824
- function initVectorCjkEmbedState(pdfDoc, snapshot, effectiveData, options) {
6825
- const requested = options?.cjkTextMode ?? "raster-hd";
6912
+ function registerSubsetType0FontInDoc(pdfDoc, fontBytes, usedCodePoints, fontTag) {
6913
+ const subset = subsetTrueTypeFont(fontBytes, usedCodePoints);
6914
+ const scale = 1e3 / (subset.unitsPerEm || 1e3);
6915
+ const fontFileStream = pdfDoc.context.flateStream(subset.subsetBytes, {
6916
+ Length1: subset.subsetBytes.byteLength
6917
+ });
6918
+ const fontFileRef = pdfDoc.context.register(fontFileStream);
6919
+ const scaledWidths = subset.gidAdvanceWidths.map((w) => Math.round(w * scale));
6920
+ const fontDescriptorRef = pdfDoc.context.register(
6921
+ pdfDoc.context.obj({
6922
+ Type: "FontDescriptor",
6923
+ FontName: fontTag,
6924
+ Flags: 32,
6925
+ FontBBox: subset.bbox.map((v) => Math.round(v * scale)),
6926
+ ItalicAngle: 0,
6927
+ Ascent: Math.round(subset.ascent * scale),
6928
+ Descent: Math.round(subset.descent * scale),
6929
+ CapHeight: Math.round(subset.ascent * scale),
6930
+ StemV: fontTag.includes("Bold") ? 140 : 80,
6931
+ FontFile2: fontFileRef
6932
+ })
6933
+ );
6934
+ const cidFontRef = pdfDoc.context.register(
6935
+ pdfDoc.context.obj({
6936
+ Type: "Font",
6937
+ Subtype: "CIDFontType2",
6938
+ BaseFont: fontTag,
6939
+ CIDSystemInfo: {
6940
+ Registry: PDFString.of("Adobe"),
6941
+ Ordering: PDFString.of("Identity"),
6942
+ Supplement: 0
6943
+ },
6944
+ FontDescriptor: fontDescriptorRef,
6945
+ DW: 1e3,
6946
+ W: [0, scaledWidths],
6947
+ CIDToGIDMap: "Identity"
6948
+ })
6949
+ );
6950
+ const toUnicodeCmap = buildToUnicodeCmapString(subset.codePointToGid);
6951
+ const toUnicodeRef = pdfDoc.context.register(pdfDoc.context.flateStream(toUnicodeCmap));
6952
+ const type0FontRef = pdfDoc.context.register(
6953
+ pdfDoc.context.obj({
6954
+ Type: "Font",
6955
+ Subtype: "Type0",
6956
+ BaseFont: fontTag,
6957
+ Encoding: "Identity-H",
6958
+ DescendantFonts: [cidFontRef],
6959
+ ToUnicode: toUnicodeRef
6960
+ })
6961
+ );
6962
+ return { type0FontRef, subset };
6963
+ }
6964
+ async function resolveRenderFontsForExport(snapshot, options) {
6965
+ const renderCfg = options?.render;
6966
+ const hasHostFonts = Boolean(renderCfg?.fonts && renderCfg.fonts.length > 0);
6967
+ const explicitMode = renderCfg?.cjkTextMode ?? options?.cjkTextMode;
6968
+ const requestedMode = explicitMode ?? (hasHostFonts ? "subset-ttf" : "raster-hd");
6969
+ if (requestedMode === "raster-hd" || requestedMode === "cid-vector") {
6970
+ return { effectiveMode: requestedMode };
6971
+ }
6972
+ const failedFonts = [];
6973
+ let normalFontBytes;
6974
+ let boldFontBytes = options?.customBoldFontBytes;
6975
+ if (hasHostFonts && renderCfg?.fonts) {
6976
+ const normalCandidates = renderCfg.fonts.map((f, index) => ({ f, index })).filter(({ f }) => f.weight !== "bold");
6977
+ const boldCandidates = renderCfg.fonts.map((f, index) => ({ f, index })).filter(({ f }) => f.weight === "bold");
6978
+ const primaryOrder = normalCandidates.length > 0 ? normalCandidates : boldCandidates;
6979
+ for (const { f, index } of primaryOrder) {
6980
+ try {
6981
+ normalFontBytes = await loadSingleFontCandidate(f);
6982
+ break;
6983
+ } catch (err) {
6984
+ failedFonts.push({
6985
+ index,
6986
+ family: f.family,
6987
+ weight: f.weight,
6988
+ url: f.url,
6989
+ reason: err?.message || String(err)
6990
+ });
6991
+ }
6992
+ }
6993
+ if (normalFontBytes && !boldFontBytes && boldCandidates.length > 0 && normalCandidates.length > 0) {
6994
+ for (const { f, index } of boldCandidates) {
6995
+ try {
6996
+ boldFontBytes = await loadSingleFontCandidate(f);
6997
+ break;
6998
+ } catch (err) {
6999
+ failedFonts.push({
7000
+ index,
7001
+ family: f.family,
7002
+ weight: f.weight,
7003
+ url: f.url,
7004
+ reason: err?.message || String(err)
7005
+ });
7006
+ }
7007
+ }
7008
+ }
7009
+ }
7010
+ if (!normalFontBytes && options?.customFontBytes && options.customFontBytes.byteLength > 0) {
7011
+ try {
7012
+ inspectTrueTypeFont(options.customFontBytes);
7013
+ normalFontBytes = options.customFontBytes;
7014
+ } catch (err) {
7015
+ failedFonts.push({
7016
+ index: failedFonts.length,
7017
+ reason: err?.message || String(err)
7018
+ });
7019
+ }
7020
+ }
7021
+ if (!normalFontBytes && snapshot?.resourceBindings) {
7022
+ const fontBinding = Object.values(snapshot.resourceBindings).find(
7023
+ (b) => b.type === "font" && Boolean(b.dataUri)
7024
+ );
7025
+ if (fontBinding?.dataUri) {
7026
+ try {
7027
+ const decoded = dataUriToBytes(fontBinding.dataUri);
7028
+ inspectTrueTypeFont(decoded);
7029
+ normalFontBytes = decoded;
7030
+ } catch (err) {
7031
+ failedFonts.push({
7032
+ index: failedFonts.length,
7033
+ family: fontBinding.name,
7034
+ reason: err?.message || String(err)
7035
+ });
7036
+ }
7037
+ }
7038
+ }
7039
+ if (normalFontBytes && normalFontBytes.byteLength > 0) {
7040
+ if (boldFontBytes) {
7041
+ try {
7042
+ inspectTrueTypeFont(boldFontBytes);
7043
+ } catch {
7044
+ boldFontBytes = void 0;
7045
+ }
7046
+ }
7047
+ return { effectiveMode: "subset-ttf", normalFontBytes, boldFontBytes };
7048
+ }
7049
+ const fallbackPolicy = renderCfg?.fallback ?? "error";
7050
+ const detailSummary = failedFonts.length > 0 ? failedFonts.map(
7051
+ (e) => `#${e.index}${e.family ? ` (${e.family})` : ""}${e.url ? ` [${e.url}]` : ""}: ${e.reason}`
7052
+ ).join("; ") : "\u672A\u63D0\u4F9B\u53EF\u7528\u7684 TrueType (.ttf) \u5B57\u4F53\u5B57\u8282\u6216\u5730\u5740";
7053
+ if (fallbackPolicy === "raster-hd" || fallbackPolicy === "cid-vector") {
7054
+ renderCfg?.onWarning?.({
7055
+ code: "FONT_FALLBACK_ACTIVATED",
7056
+ message: `\u4E2D\u6587\u5B57\u4F53\u52A0\u8F7D\u5931\u8D25\uFF0C\u5DF2\u6309\u663E\u5F0F\u56DE\u9000\u7B56\u7565\u5207\u6362\u81F3 '${fallbackPolicy}'\uFF1A${detailSummary}`,
7057
+ details: { fallback: fallbackPolicy, failedFonts }
7058
+ });
7059
+ return { effectiveMode: fallbackPolicy };
7060
+ }
7061
+ throw new PdfRenderError(
7062
+ "FONT_UNAVAILABLE",
7063
+ `PDF \u5B50\u96C6\u5B57\u4F53\u4E0D\u53EF\u7528\uFF08cjkTextMode='subset-ttf'\uFF09\uFF1A${detailSummary}`,
7064
+ { failedFonts }
7065
+ );
7066
+ }
7067
+ function initVectorCjkEmbedState(pdfDoc, snapshot, effectiveData, options, preResolved) {
7068
+ const requested = preResolved?.effectiveMode ?? options?.render?.cjkTextMode ?? options?.cjkTextMode ?? "raster-hd";
6826
7069
  if (requested === "raster-hd") return null;
6827
- let resolvedFontBytes = options?.customFontBytes;
6828
- if ((!resolvedFontBytes || resolvedFontBytes.byteLength === 0) && snapshot?.resourceBindings) {
7070
+ let resolvedFontBytes = preResolved?.normalFontBytes ?? options?.customFontBytes;
7071
+ if ((!resolvedFontBytes || resolvedFontBytes.byteLength === 0) && !preResolved && snapshot?.resourceBindings) {
6829
7072
  const fontBinding = Object.values(snapshot.resourceBindings).find(
6830
7073
  (b) => b.type === "font" && Boolean(b.dataUri)
6831
7074
  );
@@ -6837,62 +7080,69 @@ function initVectorCjkEmbedState(pdfDoc, snapshot, effectiveData, options) {
6837
7080
  }
6838
7081
  }
6839
7082
  }
6840
- if (requested === "subset-ttf" && resolvedFontBytes && resolvedFontBytes.byteLength > 0) {
7083
+ if (requested === "subset-ttf") {
7084
+ if (!resolvedFontBytes || resolvedFontBytes.byteLength === 0) {
7085
+ throw new PdfRenderError(
7086
+ "FONT_UNAVAILABLE",
7087
+ "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"
7088
+ );
7089
+ }
6841
7090
  const usedCodePoints = collectUsedCodePointsFromPdfUnit(snapshot, effectiveData);
6842
- const subset = subsetTrueTypeFont(resolvedFontBytes, usedCodePoints);
6843
- const scale = 1e3 / (subset.unitsPerEm || 1e3);
6844
- const fontFileStream = pdfDoc.context.flateStream(subset.subsetBytes, {
6845
- Length1: subset.subsetBytes.byteLength
6846
- });
6847
- const fontFileRef = pdfDoc.context.register(fontFileStream);
6848
- const scaledWidths = subset.gidAdvanceWidths.map((w) => Math.round(w * scale));
6849
- const fontDescriptorRef2 = pdfDoc.context.register(
6850
- pdfDoc.context.obj({
6851
- Type: "FontDescriptor",
6852
- FontName: "UNVPDF+SubsetTTF",
6853
- Flags: 32,
6854
- FontBBox: subset.bbox.map((v) => Math.round(v * scale)),
6855
- ItalicAngle: 0,
6856
- Ascent: Math.round(subset.ascent * scale),
6857
- Descent: Math.round(subset.descent * scale),
6858
- CapHeight: Math.round(subset.ascent * scale),
6859
- StemV: 80,
6860
- FontFile2: fontFileRef
6861
- })
6862
- );
6863
- const cidFontRef2 = pdfDoc.context.register(
6864
- pdfDoc.context.obj({
6865
- Type: "Font",
6866
- Subtype: "CIDFontType2",
6867
- BaseFont: "UNVPDF+SubsetTTF",
6868
- CIDSystemInfo: {
6869
- Registry: PDFString.of("Adobe"),
6870
- Ordering: PDFString.of("Identity"),
6871
- Supplement: 0
6872
- },
6873
- FontDescriptor: fontDescriptorRef2,
6874
- DW: 1e3,
6875
- W: [0, scaledWidths],
6876
- CIDToGIDMap: "Identity"
6877
- })
7091
+ const { type0FontRef: type0FontRef2, subset } = registerSubsetType0FontInDoc(
7092
+ pdfDoc,
7093
+ resolvedFontBytes,
7094
+ usedCodePoints,
7095
+ "UNVPDF+SubsetTTF"
6878
7096
  );
6879
- const toUnicodeCmap = buildToUnicodeCmapString(subset.codePointToGid);
6880
- const toUnicodeRef = pdfDoc.context.register(pdfDoc.context.flateStream(toUnicodeCmap));
6881
- const type0FontRef2 = pdfDoc.context.register(
6882
- pdfDoc.context.obj({
6883
- Type: "Font",
6884
- Subtype: "Type0",
6885
- BaseFont: "UNVPDF+SubsetTTF",
6886
- Encoding: "Identity-H",
6887
- DescendantFonts: [cidFontRef2],
6888
- ToUnicode: toUnicodeRef
6889
- })
7097
+ const missingItems = collectMissingGlyphsFromPdfUnit(
7098
+ snapshot,
7099
+ (cp) => (subset.codePointToGid[cp] ?? 0) > 0,
7100
+ effectiveData,
7101
+ formatPdfTableCell
6890
7102
  );
7103
+ if (missingItems.length > 0) {
7104
+ const missingPolicy = options?.render?.missingGlyph ?? "warn";
7105
+ if (missingPolicy === "error") {
7106
+ const desc = missingItems.map(
7107
+ (m) => `${m.pageId ? `${m.pageId}/` : ""}${m.elementId}: ${m.chars.map((c, idx) => `'${c}' (${m.codePoints[idx]})`).join(", ")}`
7108
+ ).join("; ");
7109
+ throw new PdfRenderError(
7110
+ "MISSING_GLYPH",
7111
+ `PDF \u5B50\u96C6\u5B57\u4F53\u7F3A\u5C11\u6587\u6863\u6240\u9700\u5B57\u5F62\uFF1A${desc}`,
7112
+ { missingGlyphs: missingItems }
7113
+ );
7114
+ }
7115
+ if (options?.render?.onWarning) {
7116
+ for (const item of missingItems) {
7117
+ options.render.onWarning({
7118
+ code: "MISSING_GLYPH",
7119
+ pageId: item.pageId,
7120
+ elementId: item.elementId,
7121
+ 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(", ")}`,
7122
+ details: { chars: item.chars, codePoints: item.codePoints }
7123
+ });
7124
+ }
7125
+ }
7126
+ }
7127
+ let boldType0FontRef;
7128
+ let boldSubset;
7129
+ const boldBytes = preResolved?.boldFontBytes ?? options?.customBoldFontBytes;
7130
+ if (boldBytes && boldBytes.byteLength > 0) {
7131
+ const regBold = registerSubsetType0FontInDoc(
7132
+ pdfDoc,
7133
+ boldBytes,
7134
+ usedCodePoints,
7135
+ "UNVPDF+SubsetTTFBold"
7136
+ );
7137
+ boldType0FontRef = regBold.type0FontRef;
7138
+ boldSubset = regBold.subset;
7139
+ }
6891
7140
  return {
6892
7141
  mode: "subset-ttf",
6893
7142
  type0FontRef: type0FontRef2,
6894
7143
  subset,
6895
- pageFontKeys: /* @__PURE__ */ new WeakMap()
7144
+ pageFontKeys: /* @__PURE__ */ new WeakMap(),
7145
+ ...boldType0FontRef ? { boldType0FontRef, boldSubset, boldPageFontKeys: /* @__PURE__ */ new WeakMap() } : {}
6896
7146
  };
6897
7147
  }
6898
7148
  const fontDescriptorRef = pdfDoc.context.register(
@@ -6937,24 +7187,127 @@ function initVectorCjkEmbedState(pdfDoc, snapshot, effectiveData, options) {
6937
7187
  pageFontKeys: /* @__PURE__ */ new WeakMap()
6938
7188
  };
6939
7189
  }
6940
- function getOrRegisterPageCjkFontKey(page, state) {
7190
+ function getOrRegisterPageCjkFontKey(page, state, wantBold = false) {
7191
+ if (wantBold && state.boldType0FontRef && state.boldSubset && state.boldPageFontKeys) {
7192
+ const existingBold = state.boldPageFontKeys.get(page);
7193
+ if (existingBold) {
7194
+ return { fontKey: existingBold, activeSubset: state.boldSubset, usedDedicatedBold: true };
7195
+ }
7196
+ const boldKey = page.node.newFontDictionary("FSubB", state.boldType0FontRef);
7197
+ state.boldPageFontKeys.set(page, boldKey);
7198
+ return { fontKey: boldKey, activeSubset: state.boldSubset, usedDedicatedBold: true };
7199
+ }
6941
7200
  const existing = state.pageFontKeys.get(page);
6942
- if (existing) return existing;
7201
+ if (existing) {
7202
+ return { fontKey: existing, activeSubset: state.subset, usedDedicatedBold: false };
7203
+ }
6943
7204
  const key = page.node.newFontDictionary(state.mode === "subset-ttf" ? "FSub" : "FCid", state.type0FontRef);
6944
7205
  state.pageFontKeys.set(page, key);
6945
- return key;
7206
+ return { fontKey: key, activeSubset: state.subset, usedDedicatedBold: false };
7207
+ }
7208
+ function isIdeographOrFullwidthCodePoint(cp) {
7209
+ return cp >= 11904 && cp <= 40959 || cp >= 44032 && cp <= 55215 || cp >= 63744 && cp <= 64255 || cp >= 65072 && cp <= 65135 || cp >= 65280 && cp <= 65519 || cp >= 126976;
7210
+ }
7211
+ function wrapMixedCjkAndLatinLines(rawText, maxWidthPt, measureFn) {
7212
+ const normalized = rawText.replace(/\r\n?/g, "\n");
7213
+ const limit = Math.max(1, maxWidthPt);
7214
+ const out = [];
7215
+ const tokenizeParagraph = (para) => {
7216
+ const tokens = [];
7217
+ let buf = "";
7218
+ let bufKind = null;
7219
+ for (const ch of para) {
7220
+ const cp = ch.codePointAt(0) ?? 32;
7221
+ if (ch === " " || ch === " ") {
7222
+ if (bufKind === "space") {
7223
+ buf += ch;
7224
+ } else {
7225
+ if (buf) tokens.push({ kind: bufKind, text: buf });
7226
+ buf = ch;
7227
+ bufKind = "space";
7228
+ }
7229
+ } else if (isIdeographOrFullwidthCodePoint(cp)) {
7230
+ if (buf) {
7231
+ tokens.push({ kind: bufKind, text: buf });
7232
+ buf = "";
7233
+ bufKind = null;
7234
+ }
7235
+ tokens.push({ kind: "cjk", text: ch });
7236
+ } else {
7237
+ if (bufKind === "word") {
7238
+ buf += ch;
7239
+ } else {
7240
+ if (buf) tokens.push({ kind: bufKind, text: buf });
7241
+ buf = ch;
7242
+ bufKind = "word";
7243
+ }
7244
+ }
7245
+ }
7246
+ if (buf && bufKind) {
7247
+ tokens.push({ kind: bufKind, text: buf });
7248
+ }
7249
+ return tokens;
7250
+ };
7251
+ for (const para of normalized.split("\n")) {
7252
+ if (!para) {
7253
+ out.push({ text: "", isLastInParagraph: true });
7254
+ continue;
7255
+ }
7256
+ const tokens = tokenizeParagraph(para);
7257
+ let current = "";
7258
+ for (const tok of tokens) {
7259
+ if (tok.kind === "space") {
7260
+ if (!current) continue;
7261
+ const candidate2 = current + tok.text;
7262
+ if (measureFn(candidate2) <= limit) {
7263
+ current = candidate2;
7264
+ } else {
7265
+ out.push({ text: current.replace(/[ \t]+$/g, ""), isLastInParagraph: false });
7266
+ current = "";
7267
+ }
7268
+ continue;
7269
+ }
7270
+ const candidate = current + tok.text;
7271
+ if (measureFn(candidate) <= limit) {
7272
+ current = candidate;
7273
+ continue;
7274
+ }
7275
+ if (current) {
7276
+ out.push({ text: current.replace(/[ \t]+$/g, ""), isLastInParagraph: false });
7277
+ current = "";
7278
+ }
7279
+ if (measureFn(tok.text) <= limit || Array.from(tok.text).length <= 1) {
7280
+ current = tok.text;
7281
+ } else {
7282
+ let charBuf = "";
7283
+ for (const ch of tok.text) {
7284
+ const nextBuf = charBuf + ch;
7285
+ if (measureFn(nextBuf) > limit && charBuf.length > 0) {
7286
+ out.push({ text: charBuf, isLastInParagraph: false });
7287
+ charBuf = ch;
7288
+ } else {
7289
+ charBuf = nextBuf;
7290
+ }
7291
+ }
7292
+ current = charBuf;
7293
+ }
7294
+ }
7295
+ out.push({ text: current.replace(/[ \t]+$/g, ""), isLastInParagraph: true });
7296
+ }
7297
+ return out;
6946
7298
  }
6947
- function measureVectorCjkLine(line, fontSize, state, characterSpacing = 0) {
7299
+ function measureVectorCjkLine(line, fontSize, state, characterSpacing = 0, overrideSubset) {
6948
7300
  if (!line) return 0;
6949
7301
  const glyphCount = Array.from(line).length;
6950
7302
  const extraTc = glyphCount > 1 ? (glyphCount - 1) * characterSpacing : 0;
6951
- if (state.mode === "subset-ttf" && state.subset) {
6952
- const upem = state.subset.unitsPerEm || 1e3;
7303
+ const sub = overrideSubset ?? state.subset;
7304
+ if (state.mode === "subset-ttf" && sub) {
7305
+ const upem = sub.unitsPerEm || 1e3;
6953
7306
  let totalUnits = 0;
6954
7307
  for (const ch of line) {
6955
7308
  const cp = ch.codePointAt(0) ?? 63;
6956
- const gid = state.subset.codePointToGid[cp] ?? 0;
6957
- totalUnits += state.subset.gidAdvanceWidths[gid] ?? upem;
7309
+ const gid = sub.codePointToGid[cp] ?? 0;
7310
+ totalUnits += sub.gidAdvanceWidths[gid] ?? upem;
6958
7311
  }
6959
7312
  return totalUnits * fontSize / upem + extraTc;
6960
7313
  }
@@ -6965,12 +7318,13 @@ function measureVectorCjkLine(line, fontSize, state, characterSpacing = 0) {
6965
7318
  }
6966
7319
  return width + extraTc;
6967
7320
  }
6968
- function encodeVectorCjkLineHex(line, state) {
6969
- if (state.mode === "subset-ttf" && state.subset) {
7321
+ function encodeVectorCjkLineHex(line, state, overrideSubset) {
7322
+ const sub = overrideSubset ?? state.subset;
7323
+ if (state.mode === "subset-ttf" && sub) {
6970
7324
  let hex = "";
6971
7325
  for (const ch of line) {
6972
7326
  const cp = ch.codePointAt(0) ?? 63;
6973
- const gid = state.subset.codePointToGid[cp] ?? 0;
7327
+ const gid = sub.codePointToGid[cp] ?? 0;
6974
7328
  hex += gid.toString(16).padStart(4, "0").toUpperCase();
6975
7329
  }
6976
7330
  return hex;
@@ -6978,38 +7332,21 @@ function encodeVectorCjkLineHex(line, state) {
6978
7332
  return toUtf16BeHex(line, true);
6979
7333
  }
6980
7334
  function drawVectorCjkTextBox(page, pageHeight, text, left, top, width, height, style, state, noWrapSingleLine = false, colorType, overrideCharacterSpacing) {
6981
- const fontKey = getOrRegisterPageCjkFontKey(page, state);
7335
+ const wantBold = style?.fontWeight === "bold";
7336
+ const { fontKey, activeSubset, usedDedicatedBold } = getOrRegisterPageCjkFontKey(page, state, wantBold);
6982
7337
  const fontSize = style?.fontSize ?? 12;
6983
7338
  const pad = style?.padding ?? 4;
6984
- const maxWidth = Math.max(8, width - pad * 2);
7339
+ const maxWidth = Math.max(1, width - pad * 2);
6985
7340
  const lineHeight = fontSize * (style?.lineHeight ?? 1.38);
6986
7341
  const color = parseHexColor(style?.color) ?? { r: 0.12, g: 0.14, b: 0.16, a: 1 };
6987
7342
  const charSpacing = overrideCharacterSpacing ?? style?.characterSpacing ?? 0;
6988
7343
  const pdfY = pageHeight - top - height;
6989
- const lines = [];
6990
- if (noWrapSingleLine) {
6991
- for (const para of text.split("\n")) {
6992
- lines.push({ text: para, isLastInParagraph: true });
6993
- }
6994
- } else {
6995
- for (const para of text.split("\n")) {
6996
- if (!para) {
6997
- lines.push({ text: "", isLastInParagraph: true });
6998
- continue;
6999
- }
7000
- let current = "";
7001
- for (const ch of para) {
7002
- const candidate = current + ch;
7003
- if (measureVectorCjkLine(candidate, fontSize, state, charSpacing) > maxWidth && current.length > 0) {
7004
- lines.push({ text: current, isLastInParagraph: false });
7005
- current = ch;
7006
- } else {
7007
- current = candidate;
7008
- }
7009
- }
7010
- if (current) lines.push({ text: current, isLastInParagraph: true });
7011
- }
7012
- }
7344
+ const normalized = text.replace(/\r\n?/g, "\n");
7345
+ const lines = noWrapSingleLine ? normalized.split("\n").map((para) => ({ text: para, isLastInParagraph: true })) : wrapMixedCjkAndLatinLines(
7346
+ normalized,
7347
+ maxWidth,
7348
+ (s) => measureVectorCjkLine(s, fontSize, state, charSpacing, activeSubset)
7349
+ );
7013
7350
  const totalH = lines.length * lineHeight;
7014
7351
  let firstBaselineFromTop = pad + fontSize * 0.85;
7015
7352
  if (style?.verticalAlign === "middle") {
@@ -7021,12 +7358,34 @@ function drawVectorCjkTextBox(page, pageHeight, text, left, top, width, height,
7021
7358
  const cm = rgbToCmyk(color.r, color.g, color.b);
7022
7359
  return setFillingCmykColor(cm.c, cm.m, cm.y, cm.k);
7023
7360
  })() : setFillingRgbColor(color.r, color.g, color.b);
7361
+ const syntheticBoldOps = wantBold && !usedDedicatedBold ? [
7362
+ PDFOperator.of("Tr", [PDFNumber2.of(2)]),
7363
+ setLineWidth(Math.max(0.25, fontSize * 0.032)),
7364
+ colorType === "cmyk" ? (() => {
7365
+ const cm = rgbToCmyk(color.r, color.g, color.b);
7366
+ return setStrokingCmykColor(cm.c, cm.m, cm.y, cm.k);
7367
+ })() : setStrokingRgbColor(color.r, color.g, color.b)
7368
+ ] : [];
7024
7369
  const decoCol = toPdfLibColor(color, colorType);
7025
7370
  const decoThickness = Math.max(0.6, fontSize * 0.065);
7371
+ const applyClip = !noWrapSingleLine && width > 0 && height > 0;
7372
+ if (applyClip) {
7373
+ page.pushOperators(
7374
+ pushGraphicsState2(),
7375
+ rectangle2(left, pdfY, width, height),
7376
+ clip2(),
7377
+ endPath2()
7378
+ );
7379
+ }
7026
7380
  for (let i = 0; i < lines.length; i++) {
7027
7381
  const { text: line, isLastInParagraph } = lines[i];
7028
7382
  if (!line) continue;
7029
- const lineW = measureVectorCjkLine(line, fontSize, state, charSpacing);
7383
+ const drawY = pageHeight - top - (firstBaselineFromTop + i * lineHeight);
7384
+ if (!noWrapSingleLine) {
7385
+ if (i === 0 && height < fontSize * 0.55) break;
7386
+ if (i > 0 && drawY - fontSize * 0.14 < pdfY) break;
7387
+ }
7388
+ const lineW = measureVectorCjkLine(line, fontSize, state, charSpacing, activeSubset);
7030
7389
  let drawX = left + pad;
7031
7390
  let effectiveLineW = lineW;
7032
7391
  let extraJustifyTc = 0;
@@ -7041,9 +7400,7 @@ function drawVectorCjkTextBox(page, pageHeight, text, left, top, width, height,
7041
7400
  effectiveLineW = maxWidth;
7042
7401
  }
7043
7402
  }
7044
- const drawY = pageHeight - top - (firstBaselineFromTop + i * lineHeight);
7045
- if (drawY < pdfY - 2 && !noWrapSingleLine) break;
7046
- const hexStr = encodeVectorCjkLineHex(line, state);
7403
+ const hexStr = encodeVectorCjkLineHex(line, state, activeSubset);
7047
7404
  const totalTc = charSpacing + extraJustifyTc;
7048
7405
  const posOp = style?.italic ? PDFOperator.of("Tm", [
7049
7406
  PDFNumber2.of(1),
@@ -7057,6 +7414,7 @@ function drawVectorCjkTextBox(page, pageHeight, text, left, top, width, height,
7057
7414
  pushGraphicsState2(),
7058
7415
  beginText(),
7059
7416
  fillOp,
7417
+ ...syntheticBoldOps,
7060
7418
  setFontAndSize(fontKey, fontSize),
7061
7419
  ...totalTc !== 0 ? [setCharacterSpacing(totalTc)] : [],
7062
7420
  posOp,
@@ -7085,6 +7443,9 @@ function drawVectorCjkTextBox(page, pageHeight, text, left, top, width, height,
7085
7443
  });
7086
7444
  }
7087
7445
  }
7446
+ if (applyClip) {
7447
+ page.pushOperators(popGraphicsState2());
7448
+ }
7088
7449
  }
7089
7450
  function renderTextToPngBytesInBrowser(text, widthPt, heightPt, style) {
7090
7451
  if (typeof document === "undefined") return null;
@@ -7103,27 +7464,10 @@ function renderTextToPngBytesInBrowser(text, widthPt, heightPt, style) {
7103
7464
  ctx.fillStyle = style?.color ?? "#1f2329";
7104
7465
  ctx.textBaseline = "top";
7105
7466
  const pad = style?.padding ?? 4;
7106
- const maxWidth = Math.max(4, widthPt - pad * 2);
7107
- const lineHeight = fontSize * (style?.lineHeight ?? 1.4);
7108
- const paragraphs = text.split("\n");
7109
- const lines = [];
7110
- for (const para of paragraphs) {
7111
- if (!para) {
7112
- lines.push("");
7113
- continue;
7114
- }
7115
- let current = "";
7116
- for (const ch of para) {
7117
- const test = current + ch;
7118
- if (ctx.measureText(test).width > maxWidth && current.length > 0) {
7119
- lines.push(current);
7120
- current = ch;
7121
- } else {
7122
- current = test;
7123
- }
7124
- }
7125
- if (current) lines.push(current);
7126
- }
7467
+ const maxWidth = Math.max(1, widthPt - pad * 2);
7468
+ const lineHeight = fontSize * (style?.lineHeight ?? 1.38);
7469
+ const wrapped = wrapMixedCjkAndLatinLines(text, maxWidth, (s) => ctx.measureText(s).width);
7470
+ const lines = wrapped.map((w) => w.text);
7127
7471
  const totalTextHeight = lines.length * lineHeight;
7128
7472
  let startY = pad;
7129
7473
  if (style?.verticalAlign === "middle") {
@@ -7133,15 +7477,17 @@ function renderTextToPngBytesInBrowser(text, widthPt, heightPt, style) {
7133
7477
  }
7134
7478
  for (let i = 0; i < lines.length; i++) {
7135
7479
  const line = lines[i];
7480
+ if (!line) continue;
7481
+ const y = startY + i * lineHeight;
7482
+ if (i === 0 && heightPt < fontSize * 0.55) break;
7483
+ if (i > 0 && y + fontSize > heightPt + 1) break;
7136
7484
  const lineWidth = ctx.measureText(line).width;
7137
7485
  let x = pad;
7138
7486
  if (style?.textAlign === "center") {
7139
- x = (widthPt - lineWidth) / 2;
7487
+ x = Math.max(pad, (widthPt - lineWidth) / 2);
7140
7488
  } else if (style?.textAlign === "right") {
7141
- x = widthPt - pad - lineWidth;
7489
+ x = Math.max(pad, widthPt - pad - lineWidth);
7142
7490
  }
7143
- const y = startY + i * lineHeight;
7144
- if (y + fontSize > heightPt + 2) break;
7145
7491
  ctx.fillText(line, x, y);
7146
7492
  if (style?.underline) {
7147
7493
  ctx.beginPath();
@@ -7589,57 +7935,14 @@ async function drawTextBox(pdfDoc, page, pageHeight, text, left, top, width, hei
7589
7935
  const pad = style?.padding ?? 4;
7590
7936
  const color = parseHexColor(style?.color) ?? { r: 0.12, g: 0.14, b: 0.16, a: 1 };
7591
7937
  const pdfCol = toPdfLibColor(color, colorType);
7592
- const maxLineW = Math.max(10, bgWidth - pad * 2);
7593
- const lineHeight = fontSize * (style?.lineHeight ?? 1.35);
7938
+ const maxLineW = Math.max(1, bgWidth - pad * 2);
7939
+ const lineHeight = fontSize * (style?.lineHeight ?? 1.38);
7940
+ const normalizedText = text.replace(/\r\n?/g, "\n");
7594
7941
  const measureAscii = (s) => {
7595
7942
  if (!s) return 0;
7596
7943
  return font.widthOfTextAtSize(s, fontSize) + (s.length > 1 ? (s.length - 1) * charSpacing : 0);
7597
7944
  };
7598
- const wrappedLines = [];
7599
- if (extraOpts?.noWrapSingleLine) {
7600
- for (const para of text.split("\n")) {
7601
- wrappedLines.push({ text: para, isLastInParagraph: true });
7602
- }
7603
- } else {
7604
- for (const para of text.split("\n")) {
7605
- if (!para) {
7606
- wrappedLines.push({ text: "", isLastInParagraph: true });
7607
- continue;
7608
- }
7609
- const tokens = para.split(/( +)/).filter((t) => t.length > 0);
7610
- let current = "";
7611
- for (const tok of tokens) {
7612
- const candidate = current ? current + tok : tok.replace(/^ +/, "");
7613
- if (!candidate) continue;
7614
- if (measureAscii(candidate) <= maxLineW) {
7615
- current = candidate;
7616
- continue;
7617
- }
7618
- if (current) {
7619
- wrappedLines.push({ text: current.trimEnd(), isLastInParagraph: false });
7620
- current = "";
7621
- }
7622
- const trimmedTok = tok.replace(/^ +/, "");
7623
- if (!trimmedTok) continue;
7624
- if (measureAscii(trimmedTok) <= maxLineW) {
7625
- current = trimmedTok;
7626
- } else {
7627
- let charBuf = "";
7628
- for (const ch of trimmedTok) {
7629
- const nextBuf = charBuf + ch;
7630
- if (measureAscii(nextBuf) > maxLineW && charBuf.length > 0) {
7631
- wrappedLines.push({ text: charBuf, isLastInParagraph: false });
7632
- charBuf = ch;
7633
- } else {
7634
- charBuf = nextBuf;
7635
- }
7636
- }
7637
- current = charBuf;
7638
- }
7639
- }
7640
- wrappedLines.push({ text: current.trimEnd(), isLastInParagraph: true });
7641
- }
7642
- }
7945
+ const wrappedLines = extraOpts?.noWrapSingleLine ? normalizedText.split("\n").map((para) => ({ text: para, isLastInParagraph: true })) : wrapMixedCjkAndLatinLines(normalizedText, maxLineW, measureAscii);
7643
7946
  let singleLineDrawY = pageHeight - top - pad - fontSize * 0.85;
7644
7947
  if (style?.verticalAlign === "middle") {
7645
7948
  singleLineDrawY = pdfY + (height - fontSize * 0.75) / 2;
@@ -7654,12 +7957,22 @@ async function drawTextBox(pdfDoc, page, pageHeight, text, left, top, width, hei
7654
7957
  firstBaselineFromTop = Math.max(pad + fontSize * 0.78, height - pad - totalH + fontSize * 0.85);
7655
7958
  }
7656
7959
  const decoThickness = Math.max(0.6, fontSize * 0.065);
7960
+ const applyAsciiClip = !extraOpts?.noWrapSingleLine && bgWidth > 0 && height > 0;
7961
+ if (applyAsciiClip) {
7962
+ page.pushOperators(
7963
+ pushGraphicsState2(),
7964
+ rectangle2(left, pdfY, bgWidth, height),
7965
+ clip2(),
7966
+ endPath2()
7967
+ );
7968
+ }
7657
7969
  for (let i = 0; i < wrappedLines.length; i++) {
7658
7970
  const { text: lineText, isLastInParagraph } = wrappedLines[i];
7659
7971
  if (!lineText) continue;
7660
7972
  const baselineY = wrappedLines.length === 1 ? singleLineDrawY : pageHeight - top - (firstBaselineFromTop + i * lineHeight);
7661
- if (wrappedLines.length > 1 && !extraOpts?.noWrapSingleLine && baselineY < pdfY - 2) {
7662
- break;
7973
+ if (!extraOpts?.noWrapSingleLine) {
7974
+ if (i === 0 && height < fontSize * 0.55) break;
7975
+ if (i > 0 && baselineY - fontSize * 0.14 < pdfY) break;
7663
7976
  }
7664
7977
  const rawLineW = measureAscii(lineText);
7665
7978
  let drawX = left + pad;
@@ -7729,6 +8042,9 @@ async function drawTextBox(pdfDoc, page, pageHeight, text, left, top, width, hei
7729
8042
  });
7730
8043
  }
7731
8044
  }
8045
+ if (applyAsciiClip) {
8046
+ page.pushOperators(popGraphicsState2());
8047
+ }
7732
8048
  }
7733
8049
  function parseNumericCellValue(rawValue) {
7734
8050
  if (typeof rawValue === "number") {
@@ -7831,19 +8147,53 @@ function resolveDynamicTableRawRows(el, data) {
7831
8147
  }
7832
8148
  return el.rows ?? [];
7833
8149
  }
7834
- function paginatePdfTableRows(el, rawRows, pageHeight) {
8150
+ function calculatePdfTableRowCapacity(el, pageHeight, marginsPt) {
8151
+ const showHead = el.showHead !== false;
8152
+ const repeatHeader = el.repeatHeader !== false;
8153
+ const headerH = showHead ? el.headerHeight ?? 26 : 0;
8154
+ const rowH = el.rowHeight ?? 24;
8155
+ const subtotalSlot = el.showPageSubtotal ? 1 : 0;
8156
+ const grandTotalSlot = el.showGrandTotal ? 1 : 0;
8157
+ const bottomGuard = Math.max(8, marginsPt?.bottom ?? 0);
8158
+ const maxPageSpan = Math.max(headerH + rowH, pageHeight - el.transform.top - bottomGuard);
8159
+ const availableFirstPageHeight = el.transform.height > 0 ? Math.min(el.transform.height, maxPageSpan) : maxPageSpan;
8160
+ const firstBodySlots = Math.max(
8161
+ 1 + subtotalSlot + grandTotalSlot,
8162
+ Math.floor((availableFirstPageHeight - headerH) / rowH)
8163
+ );
8164
+ const firstPageRows = Math.max(1, firstBodySlots - subtotalSlot - grandTotalSlot);
8165
+ const contHeaderH = showHead && repeatHeader ? headerH : 0;
8166
+ const contBodySlots = Math.max(
8167
+ 1 + subtotalSlot,
8168
+ Math.floor((availableFirstPageHeight - contHeaderH) / rowH)
8169
+ );
8170
+ const continuationPageRows = Math.max(1, contBodySlots - subtotalSlot);
8171
+ return {
8172
+ capacityRows: firstPageRows,
8173
+ firstPageRows,
8174
+ continuationPageRows,
8175
+ headerHeight: headerH,
8176
+ rowHeight: rowH,
8177
+ availableFirstPageHeight
8178
+ };
8179
+ }
8180
+ function paginatePdfTableRows(el, rawRows, pageHeight, paginationOpts) {
7835
8181
  const showHead = el.showHead !== false;
8182
+ const repeatHeader = paginationOpts?.repeatHeader ?? el.repeatHeader ?? true;
8183
+ const tablePagination = paginationOpts?.tablePagination ?? el.pagination ?? "auto";
7836
8184
  const headerH = showHead ? el.headerHeight ?? 26 : 0;
7837
8185
  const rowH = el.rowHeight ?? 24;
7838
8186
  const subtotalLabel = el.pageSubtotalLabel || "\u672C\u9875\u5C0F\u8BA1";
7839
8187
  const grandTotalLabel = el.grandTotalLabel || "\u603B\u8BA1";
7840
8188
  const subtotalSlot = el.showPageSubtotal ? 1 : 0;
7841
8189
  const grandTotalSlot = el.showGrandTotal ? 1 : 0;
7842
- const remainingOnStartPage = pageHeight - el.transform.top - 4;
8190
+ const marginTopGuard = Math.max(36, paginationOpts?.marginTopPt ?? 0);
8191
+ const bottomGuard = Math.max(8, paginationOpts?.marginBottomPt ?? 0);
8192
+ const remainingOnStartPage = pageHeight - el.transform.top - Math.max(4, paginationOpts?.marginBottomPt ?? 0);
7843
8193
  const minRequiredForHeaderPlusOneRow = headerH + rowH * (1 + subtotalSlot);
7844
- const shouldDeferOrphanHeader = showHead && el.avoidOrphanHeader !== false && rawRows.length > 0 && el.transform.top > 36 && (remainingOnStartPage < headerH + rowH || el.avoidOrphanHeader === true && remainingOnStartPage < minRequiredForHeaderPlusOneRow);
7845
- const effectiveTop = shouldDeferOrphanHeader ? 36 : el.transform.top;
7846
- const maxPageSpan = Math.max(headerH + rowH, pageHeight - effectiveTop - 8);
8194
+ const shouldDeferOrphanHeader = tablePagination !== "none" && showHead && el.avoidOrphanHeader !== false && rawRows.length > 0 && el.transform.top > marginTopGuard && (remainingOnStartPage < headerH + rowH || el.avoidOrphanHeader === true && remainingOnStartPage < minRequiredForHeaderPlusOneRow);
8195
+ const effectiveTop = shouldDeferOrphanHeader ? marginTopGuard : el.transform.top;
8196
+ const maxPageSpan = Math.max(headerH + rowH, pageHeight - effectiveTop - bottomGuard);
7847
8197
  const availableHeight = !shouldDeferOrphanHeader && el.transform.height > 0 ? Math.min(el.transform.height, maxPageSpan) : maxPageSpan;
7848
8198
  const totalBodySlots = Math.max(
7849
8199
  1 + subtotalSlot + grandTotalSlot,
@@ -7851,23 +8201,46 @@ function paginatePdfTableRows(el, rawRows, pageHeight) {
7851
8201
  );
7852
8202
  const maxDataRegular = Math.max(1, totalBodySlots - subtotalSlot);
7853
8203
  const maxDataFinal = Math.max(1, totalBodySlots - subtotalSlot - grandTotalSlot);
8204
+ const contHeaderH = showHead && repeatHeader ? headerH : 0;
8205
+ const contBodySlots = Math.max(
8206
+ totalBodySlots,
8207
+ Math.floor((availableHeight - contHeaderH) / rowH)
8208
+ );
8209
+ const maxContRegular = Math.max(1, contBodySlots - subtotalSlot);
8210
+ const maxContFinal = Math.max(1, contBodySlots - subtotalSlot - grandTotalSlot);
7854
8211
  const slices = [];
7855
- if (shouldDeferOrphanHeader) {
7856
- slices.push({ startRowIndex: 0, rows: [], deferred: true });
7857
- }
7858
- if (rawRows.length === 0) {
7859
- slices.push({ startRowIndex: 0, rows: [] });
8212
+ if (tablePagination === "none") {
8213
+ const cap = maxDataFinal;
8214
+ if (rawRows.length > cap) {
8215
+ paginationOpts?.onOverflow?.({
8216
+ capacityRows: cap,
8217
+ actualRows: rawRows.length,
8218
+ overflowRows: rawRows.length - cap
8219
+ });
8220
+ }
8221
+ slices.push({ startRowIndex: 0, rows: rawRows.slice(0, cap) });
7860
8222
  } else {
7861
- let cursor = 0;
7862
- while (cursor < rawRows.length) {
7863
- const remaining = rawRows.length - cursor;
7864
- if (remaining <= maxDataFinal) {
7865
- slices.push({ startRowIndex: cursor, rows: rawRows.slice(cursor) });
7866
- break;
8223
+ if (shouldDeferOrphanHeader) {
8224
+ slices.push({ startRowIndex: 0, rows: [], deferred: true });
8225
+ }
8226
+ if (rawRows.length === 0) {
8227
+ slices.push({ startRowIndex: 0, rows: [] });
8228
+ } else {
8229
+ let cursor = 0;
8230
+ let isFirstDataChunk = true;
8231
+ while (cursor < rawRows.length) {
8232
+ const remaining = rawRows.length - cursor;
8233
+ const activeFinalCap = isFirstDataChunk ? maxDataFinal : maxContFinal;
8234
+ const activeRegularCap = isFirstDataChunk ? maxDataRegular : maxContRegular;
8235
+ if (remaining <= activeFinalCap) {
8236
+ slices.push({ startRowIndex: cursor, rows: rawRows.slice(cursor) });
8237
+ break;
8238
+ }
8239
+ const takeCount = remaining <= activeRegularCap ? Math.max(1, Math.min(activeRegularCap, remaining - 1)) : activeRegularCap;
8240
+ slices.push({ startRowIndex: cursor, rows: rawRows.slice(cursor, cursor + takeCount) });
8241
+ cursor += takeCount;
8242
+ isFirstDataChunk = false;
7867
8243
  }
7868
- const takeCount = remaining <= maxDataRegular ? Math.max(1, Math.min(maxDataRegular, remaining - 1)) : maxDataRegular;
7869
- slices.push({ startRowIndex: cursor, rows: rawRows.slice(cursor, cursor + takeCount) });
7870
- cursor += takeCount;
7871
8244
  }
7872
8245
  }
7873
8246
  const grandTotalRow = el.showGrandTotal ? computePdfTableSummaryRow(rawRows, el.columns, grandTotalLabel) : void 0;
@@ -7907,7 +8280,40 @@ function resolveBorderDashArray(borderStyle, thickness) {
7907
8280
  }
7908
8281
  return void 0;
7909
8282
  }
7910
- async function drawTableCellWithBorders(pdfDoc, page, pageHeight, text, left, top, width, height, style, borderOpts, cjkState, colorType) {
8283
+ function computeShrunkCellFontSize(text, width, height, baseStyle, minFontSizePt, cjkState) {
8284
+ const maxFs = baseStyle.fontSize ?? 9.5;
8285
+ const minFs = Math.max(4, Math.min(maxFs, minFontSizePt));
8286
+ if (!text || maxFs <= minFs) return maxFs;
8287
+ const pad = baseStyle.padding ?? 5;
8288
+ const innerW = Math.max(1, width - pad * 2);
8289
+ const innerH = Math.max(1, height - pad * 2);
8290
+ const lhMul = baseStyle.lineHeight ?? 1.38;
8291
+ const charSp = baseStyle.characterSpacing ?? 0;
8292
+ let candidate = maxFs;
8293
+ while (candidate > minFs) {
8294
+ const measureFn = (s) => {
8295
+ if (cjkState) {
8296
+ return measureVectorCjkLine(s, candidate, cjkState, charSp);
8297
+ }
8298
+ let w = 0;
8299
+ for (const ch of s) {
8300
+ const cp = ch.codePointAt(0) ?? 32;
8301
+ w += cp > 127 ? candidate : candidate * 0.56;
8302
+ }
8303
+ const len = Array.from(s).length;
8304
+ return w + (len > 1 ? (len - 1) * charSp : 0);
8305
+ };
8306
+ const wrapped = wrapMixedCjkAndLatinLines(text, innerW, measureFn);
8307
+ const totalH = wrapped.length * candidate * lhMul;
8308
+ const anyWider = wrapped.some((ln) => ln.text.length > 0 && measureFn(ln.text) > innerW + 0.5);
8309
+ if (totalH <= innerH + 1.5 && !anyWider) {
8310
+ return Math.round(candidate * 100) / 100;
8311
+ }
8312
+ candidate = Math.max(minFs, Math.round((candidate - 0.5) * 100) / 100);
8313
+ }
8314
+ return minFs;
8315
+ }
8316
+ async function drawTableCellWithBorders(pdfDoc, page, pageHeight, text, left, top, width, height, style, borderOpts, cjkState, colorType, autoFitOpts) {
7911
8317
  const pdfY = pageHeight - top - height;
7912
8318
  const bg = parseHexColor(style.backgroundColor);
7913
8319
  if (bg && bg.a > 0) {
@@ -7921,6 +8327,7 @@ async function drawTableCellWithBorders(pdfDoc, page, pageHeight, text, left, to
7921
8327
  borderWidth: 0
7922
8328
  });
7923
8329
  }
8330
+ const effectiveFontSize = autoFitOpts?.enabled ? computeShrunkCellFontSize(text, width, height, style, autoFitOpts.minFontSize ?? 6, cjkState) : style.fontSize;
7924
8331
  await drawTextBox(
7925
8332
  pdfDoc,
7926
8333
  page,
@@ -7932,6 +8339,7 @@ async function drawTableCellWithBorders(pdfDoc, page, pageHeight, text, left, to
7932
8339
  height,
7933
8340
  {
7934
8341
  ...style,
8342
+ fontSize: effectiveFontSize,
7935
8343
  backgroundColor: void 0,
7936
8344
  borderWidth: 0,
7937
8345
  borderColor: void 0
@@ -7996,11 +8404,12 @@ async function drawTableCellWithBorders(pdfDoc, page, pageHeight, text, left, to
7996
8404
  });
7997
8405
  }
7998
8406
  }
7999
- async function drawTableChunk(pdfDoc, page, pageHeight, el, chunk, cjkState, colorType) {
8407
+ async function drawTableChunk(pdfDoc, page, pageHeight, el, chunk, cjkState, colorType, tableRenderOpts) {
8000
8408
  if (chunk.deferredOrphanHeader) return;
8001
8409
  const { left, top, width } = el.transform;
8002
- const showHead = el.showHead !== false;
8003
- const headerH = showHead ? el.headerHeight ?? 26 : 0;
8410
+ const repeatHeader = tableRenderOpts?.repeatHeader ?? el.repeatHeader ?? true;
8411
+ const showHeadOnThisChunk = el.showHead !== false && (chunk.chunkIndex === 0 || repeatHeader);
8412
+ const headerH = showHeadOnThisChunk ? el.headerHeight ?? 26 : 0;
8004
8413
  const rowH = el.rowHeight ?? 24;
8005
8414
  const colCount = el.columns.length;
8006
8415
  const totalRatio = el.columns.reduce((s, c) => s + (c.widthRatio || 1), 0) || 1;
@@ -8014,9 +8423,10 @@ async function drawTableChunk(pdfDoc, page, pageHeight, el, chunk, cjkState, col
8014
8423
  }
8015
8424
  }
8016
8425
  const stripeBg = el.zebraStripeColor ?? el.stripedColor;
8426
+ const zebraParity = tableRenderOpts?.zebraParity ?? el.zebraParity ?? "continuous";
8017
8427
  const defaultBorderW = el.borderWidth ?? 0.75;
8018
8428
  const defaultBorderCol = el.borderColor ?? "#cbd5e1";
8019
- if (showHead && headerH > 0) {
8429
+ if (showHeadOnThisChunk && headerH > 0) {
8020
8430
  for (let c = 0; c < colCount; c++) {
8021
8431
  const col = el.columns[c];
8022
8432
  const cw = colWidths[c];
@@ -8102,8 +8512,8 @@ async function drawTableChunk(pdfDoc, page, pageHeight, el, chunk, cjkState, col
8102
8512
  for (let r = 0; r < visibleBodyRows; r++) {
8103
8513
  const rowY = top + headerH + r * rowH;
8104
8514
  const rowCells = chunk.formattedRows[r];
8105
- const isZebra = r % 2 === 1;
8106
8515
  const globalR = chunk.startRowIndex + r;
8516
+ const isZebra = (zebraParity === "chunk" ? r : globalR) % 2 === 1;
8107
8517
  for (let c = 0; c < colCount; c++) {
8108
8518
  const localKey = `${r}:${c}`;
8109
8519
  if (coveredCells.has(localKey)) continue;
@@ -8122,6 +8532,9 @@ async function drawTableChunk(pdfDoc, page, pageHeight, el, chunk, cjkState, col
8122
8532
  const vAlign = cellStyle?.verticalAlign ?? metaVertAligns[globalCellKey] ?? metaVertAligns[localKey] ?? col.verticalAlign ?? el.bodyStyle?.verticalAlign ?? "middle";
8123
8533
  const hAlign = cellStyle?.textAlign ?? col.align ?? el.bodyStyle?.textAlign ?? "left";
8124
8534
  const cellText = mergeInfo && mergeInfo.sourceGlobalRow < chunk.startRowIndex ? "" : rowCells[c] ?? "";
8535
+ const resolvedCellBg = cellStyle?.backgroundColor ?? (isZebra && stripeBg ? stripeBg : el.bodyStyle?.backgroundColor ?? "#ffffff");
8536
+ const autoFitEnabled = Boolean(col.autoFitFontSize ?? el.autoFitFontSize);
8537
+ const autoFitMinFs = col.minFontSize ?? el.minFontSize ?? 6;
8125
8538
  await drawTableCellWithBorders(
8126
8539
  pdfDoc,
8127
8540
  page,
@@ -8133,10 +8546,10 @@ async function drawTableChunk(pdfDoc, page, pageHeight, el, chunk, cjkState, col
8133
8546
  mergedH,
8134
8547
  {
8135
8548
  fontSize: 9.5,
8136
- backgroundColor: isZebra && stripeBg ? stripeBg : "#ffffff",
8137
8549
  padding: 5,
8138
8550
  ...el.bodyStyle,
8139
8551
  ...cellStyle,
8552
+ backgroundColor: resolvedCellBg,
8140
8553
  textAlign: hAlign,
8141
8554
  verticalAlign: vAlign
8142
8555
  },
@@ -8147,7 +8560,8 @@ async function drawTableChunk(pdfDoc, page, pageHeight, el, chunk, cjkState, col
8147
8560
  borderStyle: cellStyle?.borderStyle ?? el.borderStyle
8148
8561
  },
8149
8562
  cjkState,
8150
- colorType
8563
+ colorType,
8564
+ autoFitEnabled ? { enabled: true, minFontSize: autoFitMinFs } : void 0
8151
8565
  );
8152
8566
  }
8153
8567
  currentRowSlot += 1;
@@ -8416,18 +8830,39 @@ async function drawRichOrColumnTextBox(pdfDoc, page, pageHeight, spans, left, to
8416
8830
  const col = parseHexColor(seg.colorHex) ?? { r: 0.12, g: 0.14, b: 0.16, a: 1 };
8417
8831
  const pdfCol = toPdfLibColor(col, colorType);
8418
8832
  if (hasNonAscii(seg.text) && cjkState || cjkState?.mode === "subset-ttf") {
8419
- const fontKey = getOrRegisterPageCjkFontKey(page, cjkState);
8420
- const hexStr = encodeVectorCjkLineHex(seg.text, cjkState);
8833
+ const { fontKey, activeSubset, usedDedicatedBold } = getOrRegisterPageCjkFontKey(
8834
+ page,
8835
+ cjkState,
8836
+ Boolean(seg.bold)
8837
+ );
8838
+ const hexStr = encodeVectorCjkLineHex(seg.text, cjkState, activeSubset);
8421
8839
  const fillOp = colorType === "cmyk" ? (() => {
8422
8840
  const cm = rgbToCmyk(col.r, col.g, col.b);
8423
8841
  return setFillingCmykColor(cm.c, cm.m, cm.y, cm.k);
8424
8842
  })() : setFillingRgbColor(col.r, col.g, col.b);
8843
+ const boldOps = seg.bold && !usedDedicatedBold ? [
8844
+ PDFOperator.of("Tr", [PDFNumber2.of(2)]),
8845
+ setLineWidth(Math.max(0.25, seg.fontSize * 0.032)),
8846
+ colorType === "cmyk" ? (() => {
8847
+ const cm = rgbToCmyk(col.r, col.g, col.b);
8848
+ return setStrokingCmykColor(cm.c, cm.m, cm.y, cm.k);
8849
+ })() : setStrokingRgbColor(col.r, col.g, col.b)
8850
+ ] : [];
8851
+ const posOp = seg.italic ? PDFOperator.of("Tm", [
8852
+ PDFNumber2.of(1),
8853
+ PDFNumber2.of(0),
8854
+ PDFNumber2.of(0.2126),
8855
+ PDFNumber2.of(1),
8856
+ PDFNumber2.of(segX),
8857
+ PDFNumber2.of(baselineY)
8858
+ ]) : moveText(segX, baselineY);
8425
8859
  page.pushOperators(
8426
8860
  pushGraphicsState2(),
8427
8861
  beginText(),
8428
8862
  fillOp,
8863
+ ...boldOps,
8429
8864
  setFontAndSize(fontKey, seg.fontSize),
8430
- moveText(segX, baselineY),
8865
+ posOp,
8431
8866
  showText(PDFHexString.of(hexStr)),
8432
8867
  endText(),
8433
8868
  popGraphicsState2()
@@ -8925,7 +9360,7 @@ async function drawInvisibleSearchableOcrSpans(pdfDoc, pdfPage, pageHeight, span
8925
9360
  cjkTextMode: "cid-vector"
8926
9361
  });
8927
9362
  }
8928
- const fontKey = getOrRegisterPageCjkFontKey(pdfPage, localCjkState);
9363
+ const { fontKey } = getOrRegisterPageCjkFontKey(pdfPage, localCjkState);
8929
9364
  const hexStr = encodeVectorCjkLineHex(txt, localCjkState);
8930
9365
  pdfPage.pushOperators(
8931
9366
  pushGraphicsState2(),
@@ -9012,6 +9447,7 @@ async function exportPdfBytes(snapshot, runtimeData, options) {
9012
9447
  options?.accessibilityTagged ?? snapshot.accessibilityTagged ?? snapshot.metadata?.accessibilityTagged
9013
9448
  );
9014
9449
  const optimizeSize = Boolean(options?.optimizeSize);
9450
+ const preResolvedFonts = await resolveRenderFontsForExport(snapshot, options);
9015
9451
  const pdfDoc = await PDFDocument2.create();
9016
9452
  if (snapshot.metadata?.sanitized) {
9017
9453
  pdfDoc.setTitle("");
@@ -9020,8 +9456,19 @@ async function exportPdfBytes(snapshot, runtimeData, options) {
9020
9456
  pdfDoc.setKeywords([]);
9021
9457
  pdfDoc.setCreator("");
9022
9458
  pdfDoc.setProducer("");
9459
+ } else {
9460
+ pdfDoc.setProducer("Univer PDF Engine (@yudaocode/univer-pdfs)");
9461
+ pdfDoc.setCreator("Univer PDF Engine (@yudaocode/univer-pdfs)");
9462
+ }
9463
+ const fixedDateRaw = options?.render?.creationDate;
9464
+ if (fixedDateRaw !== void 0) {
9465
+ const fixedDate = fixedDateRaw instanceof Date ? fixedDateRaw : new Date(fixedDateRaw);
9466
+ if (!Number.isNaN(fixedDate.getTime())) {
9467
+ pdfDoc.setCreationDate(fixedDate);
9468
+ pdfDoc.setModificationDate(fixedDate);
9469
+ }
9023
9470
  }
9024
- const cjkState = initVectorCjkEmbedState(pdfDoc, snapshot, effectiveData, options);
9471
+ const cjkState = initVectorCjkEmbedState(pdfDoc, snapshot, effectiveData, options, preResolvedFonts);
9025
9472
  const ocgLayerMap = attachOptionalContentLayers(pdfDoc, snapshot.layers ?? []);
9026
9473
  const taggedStructItems = [];
9027
9474
  const usedAcroFieldNames = /* @__PURE__ */ new Set();
@@ -9222,6 +9669,7 @@ async function exportPdfBytes(snapshot, runtimeData, options) {
9222
9669
  const tableChunksByElementId = {};
9223
9670
  const listChunksByElementId = {};
9224
9671
  let maxChunksOnPage = 1;
9672
+ let primaryPaginatedTable = null;
9225
9673
  const visibleElements = [];
9226
9674
  let hasExpandText = false;
9227
9675
  for (const elementId of order) {
@@ -9233,11 +9681,34 @@ async function exportPdfBytes(snapshot, runtimeData, options) {
9233
9681
  }
9234
9682
  if (el.type === "table" /* TABLE */) {
9235
9683
  const rawRows = resolveDynamicTableRawRows(el, effectiveData);
9236
- const chunks = paginatePdfTableRows(el, rawRows, estSize.height);
9684
+ const chunks = paginatePdfTableRows(el, rawRows, estSize.height, {
9685
+ marginTopPt,
9686
+ marginBottomPt,
9687
+ tablePagination: options?.render?.tablePagination ?? el.pagination,
9688
+ repeatHeader: options?.render?.repeatHeader ?? el.repeatHeader,
9689
+ onOverflow: ({ capacityRows, actualRows, overflowRows }) => {
9690
+ options?.render?.onWarning?.({
9691
+ code: "TABLE_OVERFLOW",
9692
+ pageId,
9693
+ elementId,
9694
+ 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`,
9695
+ details: {
9696
+ pageId,
9697
+ elementId,
9698
+ capacityRows,
9699
+ actualRows,
9700
+ overflowRows
9701
+ }
9702
+ });
9703
+ }
9704
+ });
9237
9705
  tableChunksByElementId[elementId] = chunks;
9238
9706
  if (chunks.length > maxChunksOnPage) {
9239
9707
  maxChunksOnPage = chunks.length;
9240
9708
  }
9709
+ if (chunks.length > 1 && !primaryPaginatedTable) {
9710
+ primaryPaginatedTable = el;
9711
+ }
9241
9712
  }
9242
9713
  if (el.type === "list" /* LIST */ && el.overflow !== "clip") {
9243
9714
  const preResolvedItems = (el.items ?? []).map(
@@ -9274,13 +9745,82 @@ async function exportPdfBytes(snapshot, runtimeData, options) {
9274
9745
  maxChunksOnPage = dynamicSplitRanges.length;
9275
9746
  }
9276
9747
  }
9748
+ let tableFlowPlan;
9749
+ if (primaryPaginatedTable && !hasExpandText) {
9750
+ const tChunks = tableChunksByElementId[primaryPaginatedTable.id] ?? [];
9751
+ if (tChunks.length > 1) {
9752
+ const origTop = primaryPaginatedTable.transform.top;
9753
+ const origBot = origTop + primaryPaginatedTable.transform.height;
9754
+ const aboveOnceIds = /* @__PURE__ */ new Set();
9755
+ const trailingEls = [];
9756
+ let hasRepeatingAbove = false;
9757
+ for (const other of visibleElements) {
9758
+ if (other.id === primaryPaginatedTable.id) continue;
9759
+ if (other.type === "table" /* TABLE */ || other.type === "list" /* LIST */) continue;
9760
+ const isPageTokenBanner = other.type === "text" /* TEXT */ && /\{\{\s*(?:page|totalPages)\s*\}\}/.test(other.content || "");
9761
+ if (isPageTokenBanner) {
9762
+ if (other.transform.top < origTop) {
9763
+ hasRepeatingAbove = true;
9764
+ }
9765
+ continue;
9766
+ }
9767
+ if (other.transform.top < origTop) {
9768
+ aboveOnceIds.add(other.id);
9769
+ } else {
9770
+ trailingEls.push(other);
9771
+ }
9772
+ }
9773
+ const continuationTableTop = hasRepeatingAbove ? origTop : Math.max(24, marginTopPt || 36);
9774
+ const lastTableChunkIdx = tChunks.length - 1;
9775
+ const lastChunk = tChunks[lastTableChunkIdx];
9776
+ const effRepeatHdr = options?.render?.repeatHeader ?? primaryPaginatedTable.repeatHeader ?? true;
9777
+ const lastShowHead = primaryPaginatedTable.showHead !== false && (lastTableChunkIdx === 0 || effRepeatHdr);
9778
+ const lastHdrH = lastShowHead ? primaryPaginatedTable.headerHeight ?? 26 : 0;
9779
+ const lastSlots = lastChunk.formattedRows.length + (lastChunk.subtotalRow ? 1 : 0) + (lastChunk.grandTotalRow ? 1 : 0);
9780
+ const lastTableStart = lastTableChunkIdx === 0 ? origTop : continuationTableTop;
9781
+ const lastTableBottom = lastTableStart + lastHdrH + lastSlots * (primaryPaginatedTable.rowHeight ?? 24);
9782
+ const trailingIds = /* @__PURE__ */ new Set();
9783
+ const topOverrides = {};
9784
+ let trailingTargetChunk = lastTableChunkIdx;
9785
+ if (trailingEls.length > 0) {
9786
+ const gapFor = (o) => o.transform.top >= origBot ? o.transform.top - origBot : Math.max(12, o.transform.top - origTop);
9787
+ const bottomLimit = estSize.height - Math.max(8, marginBottomPt);
9788
+ const fitsOnLastTablePage = trailingEls.every(
9789
+ (o) => lastTableBottom + gapFor(o) + o.transform.height <= bottomLimit
9790
+ );
9791
+ if (fitsOnLastTablePage) {
9792
+ for (const o of trailingEls) {
9793
+ trailingIds.add(o.id);
9794
+ topOverrides[o.id] = lastTableBottom + gapFor(o);
9795
+ }
9796
+ } else {
9797
+ trailingTargetChunk = maxChunksOnPage;
9798
+ maxChunksOnPage += 1;
9799
+ const minTop = Math.min(...trailingEls.map((o) => o.transform.top));
9800
+ const baseStart = Math.max(24, marginTopPt || 36);
9801
+ for (const o of trailingEls) {
9802
+ trailingIds.add(o.id);
9803
+ topOverrides[o.id] = baseStart + (o.transform.top - minTop);
9804
+ }
9805
+ }
9806
+ }
9807
+ tableFlowPlan = {
9808
+ aboveOnceIds,
9809
+ trailingIds,
9810
+ trailingTargetChunk,
9811
+ topOverrides,
9812
+ continuationTableTop
9813
+ };
9814
+ }
9815
+ }
9277
9816
  for (let cIdx = 0; cIdx < maxChunksOnPage; cIdx++) {
9278
9817
  physicalPlan.push({
9279
9818
  pageId,
9280
9819
  chunkIndex: cIdx,
9281
9820
  tableChunksByElementId,
9282
9821
  listChunksByElementId,
9283
- dynamicSplitRanges
9822
+ dynamicSplitRanges,
9823
+ tableFlowPlan
9284
9824
  });
9285
9825
  }
9286
9826
  }
@@ -9409,6 +9949,20 @@ async function exportPdfBytes(snapshot, runtimeData, options) {
9409
9949
  }
9410
9950
  }
9411
9951
  for (const { elementId, el, isStaticSchema } of renderQueue) {
9952
+ if (!isStaticSchema && planItem.tableFlowPlan && el.type !== "table" /* TABLE */ && el.type !== "list" /* LIST */) {
9953
+ if (planItem.tableFlowPlan.aboveOnceIds.has(elementId) && chunkIndex !== 0) {
9954
+ continue;
9955
+ }
9956
+ if (planItem.tableFlowPlan.trailingIds.has(elementId) && chunkIndex !== planItem.tableFlowPlan.trailingTargetChunk) {
9957
+ continue;
9958
+ }
9959
+ }
9960
+ if (!isStaticSchema && el.type === "table" /* TABLE */ && tableChunksByElementId[elementId]) {
9961
+ const tChunk = tableChunksByElementId[elementId][chunkIndex];
9962
+ if (!tChunk || tChunk.deferredOrphanHeader) {
9963
+ continue;
9964
+ }
9965
+ }
9412
9966
  if (!isStaticSchema && planItem.dynamicSplitRanges && planItem.dynamicSplitRanges.length > 1 && el.type !== "table" /* TABLE */ && el.type !== "list" /* LIST */ && (!activeDynamicRange || !activeDynamicRange.elementIds.includes(elementId))) {
9413
9967
  continue;
9414
9968
  }
@@ -9461,7 +10015,7 @@ async function exportPdfBytes(snapshot, runtimeData, options) {
9461
10015
  try {
9462
10016
  const elColorType = options?.colorType ?? el.colorType ?? snapshot.metadata?.colorType;
9463
10017
  const placement = !isStaticSchema ? activeDynamicRange?.placements.find((p) => p.id === elementId) : void 0;
9464
- let top = el.transform.top + offsetYPt;
10018
+ let top = (!isStaticSchema && planItem.tableFlowPlan && planItem.tableFlowPlan.topOverrides[elementId] !== void 0 && chunkIndex === planItem.tableFlowPlan.trailingTargetChunk ? planItem.tableFlowPlan.topOverrides[elementId] : el.transform.top) + offsetYPt;
9465
10019
  let height = el.transform.height;
9466
10020
  const left = el.transform.left + offsetXPt;
9467
10021
  const width = el.transform.width;
@@ -10650,10 +11204,15 @@ async function exportPdfBytes(snapshot, runtimeData, options) {
10650
11204
  elColorType
10651
11205
  );
10652
11206
  } else if (el.type === "table" /* TABLE */) {
10653
- const chunks = tableChunksByElementId[elementId] ?? paginatePdfTableRows(el, resolveDynamicTableRawRows(el, effectiveData), pageHeight);
11207
+ const chunks = tableChunksByElementId[elementId] ?? paginatePdfTableRows(el, resolveDynamicTableRawRows(el, effectiveData), pageHeight, {
11208
+ marginTopPt,
11209
+ marginBottomPt,
11210
+ tablePagination: options?.render?.tablePagination ?? el.pagination,
11211
+ repeatHeader: options?.render?.repeatHeader ?? el.repeatHeader
11212
+ });
10654
11213
  const activeChunk = chunks[chunkIndex];
10655
11214
  if (activeChunk && !activeChunk.deferredOrphanHeader) {
10656
- const tableTop = chunkIndex > 0 && chunks[0]?.deferredOrphanHeader ? Math.max(24, marginTopPt || 36) + offsetYPt : top;
11215
+ const tableTop = chunkIndex > 0 && planItem.tableFlowPlan ? planItem.tableFlowPlan.continuationTableTop + offsetYPt : chunkIndex > 0 && chunks[0]?.deferredOrphanHeader ? Math.max(24, marginTopPt || 36) + offsetYPt : top;
10657
11216
  const shiftedTableEl = {
10658
11217
  ...el,
10659
11218
  transform: { ...el.transform, left, top: tableTop }
@@ -10665,7 +11224,11 @@ async function exportPdfBytes(snapshot, runtimeData, options) {
10665
11224
  shiftedTableEl,
10666
11225
  activeChunk,
10667
11226
  cjkState,
10668
- elColorType
11227
+ elColorType,
11228
+ {
11229
+ repeatHeader: options?.render?.repeatHeader,
11230
+ zebraParity: options?.render?.zebraParity
11231
+ }
10669
11232
  );
10670
11233
  }
10671
11234
  } else if (el.type === "annotation" /* ANNOTATION */) {
@@ -10919,7 +11482,7 @@ async function exportPdfBytes(snapshot, runtimeData, options) {
10919
11482
  });
10920
11483
  }
10921
11484
  } else if (cjkState) {
10922
- const fontKey = getOrRegisterPageCjkFontKey(pdfPage, cjkState);
11485
+ const { fontKey } = getOrRegisterPageCjkFontKey(pdfPage, cjkState);
10923
11486
  const hexWm = encodeVectorCjkLineHex(watermarkText, cjkState);
10924
11487
  for (let wy = 90; wy < pageHeight - 40; wy += isTiled ? 185 : pageHeight) {
10925
11488
  for (let wx = 45; wx < pageWidth2 - 50; wx += isTiled ? 225 : pageWidth2) {
@@ -11827,6 +12390,111 @@ function collectUsedCodePointsFromPdfUnit(unitData, data) {
11827
12390
  });
11828
12391
  return Array.from(codePoints).sort((a, b) => a - b);
11829
12392
  }
12393
+ function collectMissingGlyphsFromPdfUnit(unitData, hasGlyph, data, formatTableCell) {
12394
+ const effectiveData = data ?? unitData.metadata?.sampleData;
12395
+ const results = [];
12396
+ const checkStrings = (pageId, elementId, strings) => {
12397
+ const missingSet = /* @__PURE__ */ new Set();
12398
+ for (const s of strings) {
12399
+ if (!s) continue;
12400
+ for (const ch of s) {
12401
+ const cp = ch.codePointAt(0);
12402
+ if (cp === void 0 || cp < 32 || cp === 127) continue;
12403
+ if (!hasGlyph(cp)) {
12404
+ missingSet.add(cp);
12405
+ }
12406
+ }
12407
+ }
12408
+ if (missingSet.size > 0) {
12409
+ const sorted = Array.from(missingSet).sort((a, b) => a - b);
12410
+ results.push({
12411
+ ...pageId ? { pageId } : {},
12412
+ elementId,
12413
+ chars: sorted.map((cp) => String.fromCodePoint(cp)),
12414
+ codePoints: sorted.map((cp) => `U+${cp.toString(16).toUpperCase().padStart(4, "0")}`)
12415
+ });
12416
+ }
12417
+ };
12418
+ if (unitData.metadata?.watermarkText && unitData.metadata?.watermarkConfig?.enabled !== false) {
12419
+ checkStrings(void 0, "__watermark__", [String(unitData.metadata.watermarkText)]);
12420
+ }
12421
+ const totalPages = unitData.document.pageOrder.length;
12422
+ const startPageOffset = Math.max(1, Number(unitData.metadata?.startPageNumber ?? 1) || 1);
12423
+ unitData.document.pageOrder.forEach((pageId, pIdx) => {
12424
+ const pageCtx = { pageNumber: startPageOffset + pIdx, totalPages: startPageOffset + totalPages - 1 };
12425
+ const map = unitData.editState.elementsByPage[pageId] ?? {};
12426
+ const order = unitData.editState.elementOrderByPage[pageId] ?? Object.keys(map);
12427
+ for (const id of order) {
12428
+ const el = map[id];
12429
+ if (!el || el.hidden) continue;
12430
+ if (el.type === "text" /* TEXT */) {
12431
+ const texts = [
12432
+ resolveTemplateString(el.content, el.fieldKey || el.bindingField, effectiveData, pageCtx)
12433
+ ];
12434
+ if (el.richSpans?.length) {
12435
+ for (const span of el.richSpans) {
12436
+ texts.push(resolveTemplateString(span.text, void 0, effectiveData, pageCtx));
12437
+ }
12438
+ }
12439
+ checkStrings(pageId, id, texts);
12440
+ } else if (el.type === "list" /* LIST */) {
12441
+ checkStrings(
12442
+ pageId,
12443
+ id,
12444
+ el.items.map((item) => resolveTemplateString(item, void 0, effectiveData, pageCtx))
12445
+ );
12446
+ } else if (el.type === "stamp" /* STAMP */) {
12447
+ checkStrings(pageId, id, [el.primaryText, el.secondaryText]);
12448
+ } else if (el.type === "table" /* TABLE */) {
12449
+ const texts = [];
12450
+ if (el.showHead !== false) {
12451
+ for (const col of el.columns) {
12452
+ texts.push(col.header);
12453
+ }
12454
+ }
12455
+ if (el.showPageSubtotal) texts.push(el.pageSubtotalLabel || "\u672C\u9875\u5C0F\u8BA1");
12456
+ if (el.showGrandTotal) texts.push(el.grandTotalLabel || "\u603B\u8BA1");
12457
+ const rawRows = [];
12458
+ if (effectiveData && el.bindingField) {
12459
+ const bound = getByPathLocal(effectiveData, el.bindingField);
12460
+ if (Array.isArray(bound)) {
12461
+ for (const rowObj of bound) {
12462
+ if (Array.isArray(rowObj)) {
12463
+ rawRows.push(rowObj);
12464
+ } else if (rowObj && typeof rowObj === "object") {
12465
+ rawRows.push(el.columns.map((col) => rowObj[col.field]));
12466
+ }
12467
+ }
12468
+ }
12469
+ }
12470
+ const effectiveRows = rawRows.length > 0 ? rawRows : el.rows ?? [];
12471
+ for (const row of effectiveRows) {
12472
+ el.columns.forEach((col, cIdx) => {
12473
+ const rawVal = row[cIdx];
12474
+ texts.push(formatTableCell ? formatTableCell(rawVal, col) : String(rawVal ?? ""));
12475
+ });
12476
+ }
12477
+ checkStrings(pageId, id, texts);
12478
+ } else if (el.type === "checkbox" /* CHECKBOX */) {
12479
+ checkStrings(pageId, id, [el.label]);
12480
+ } else if (el.type === "radioGroup" /* RADIO_GROUP */) {
12481
+ checkStrings(pageId, id, [...el.options, el.value]);
12482
+ } else if (el.type === "select" /* SELECT */) {
12483
+ checkStrings(pageId, id, [...el.options, el.value, el.placeholder]);
12484
+ } else if (el.type === "dateTime" /* DATE_TIME */) {
12485
+ const key = el.formFieldName || el.fieldKey || el.bindingField;
12486
+ const bound = key ? getByPathLocal(effectiveData, key) : void 0;
12487
+ const rawVal = bound !== void 0 && bound !== null ? String(bound) : el.value ?? "";
12488
+ checkStrings(pageId, id, [formatPdfDateTimeValue(rawVal, el.format, el.dateKind, el.locale)]);
12489
+ } else if (el.type === "redaction" /* REDACTION */) {
12490
+ checkStrings(pageId, id, [el.overlayLabel]);
12491
+ } else if (el.type === "annotation" /* ANNOTATION */) {
12492
+ checkStrings(pageId, id, [el.author, el.comment]);
12493
+ }
12494
+ }
12495
+ });
12496
+ return results;
12497
+ }
11830
12498
  function readTag(bytes, offset) {
11831
12499
  return String.fromCharCode(
11832
12500
  bytes[offset],
@@ -11960,6 +12628,9 @@ function parseTrueTypeInternal(ttfBytes) {
11960
12628
  }
11961
12629
  }
11962
12630
  const head = tableSlices.get("head");
12631
+ if (head.byteLength < 54) {
12632
+ throw new Error("[UniverPdfs] Invalid TrueType font: truncated head table.");
12633
+ }
11963
12634
  const headView = new DataView(head.buffer, head.byteOffset, head.byteLength);
11964
12635
  const unitsPerEm = headView.getUint16(18, false) || 1e3;
11965
12636
  const xMin = headView.getInt16(36, false);
@@ -11968,9 +12639,18 @@ function parseTrueTypeInternal(ttfBytes) {
11968
12639
  const yMax = headView.getInt16(42, false);
11969
12640
  const indexToLocFormat = headView.getInt16(50, false) === 1 ? 1 : 0;
11970
12641
  const maxp = tableSlices.get("maxp");
12642
+ if (maxp.byteLength < 6) {
12643
+ throw new Error("[UniverPdfs] Invalid TrueType font: truncated maxp table.");
12644
+ }
11971
12645
  const maxpView = new DataView(maxp.buffer, maxp.byteOffset, maxp.byteLength);
11972
12646
  const numGlyphs = maxpView.getUint16(4, false);
12647
+ if (numGlyphs <= 0) {
12648
+ throw new Error("[UniverPdfs] Invalid TrueType font: numGlyphs is 0.");
12649
+ }
11973
12650
  const hhea = tableSlices.get("hhea");
12651
+ if (hhea.byteLength < 36) {
12652
+ throw new Error("[UniverPdfs] Invalid TrueType font: truncated hhea table.");
12653
+ }
11974
12654
  const hheaView = new DataView(hhea.buffer, hhea.byteOffset, hhea.byteLength);
11975
12655
  const ascent = hheaView.getInt16(4, false);
11976
12656
  const descent = hheaView.getInt16(6, false);
@@ -12011,6 +12691,9 @@ function parseTrueTypeInternal(ttfBytes) {
12011
12691
  }
12012
12692
  }
12013
12693
  const cmapMap = parseCmapTable(tableSlices.get("cmap"));
12694
+ if (cmapMap.size === 0) {
12695
+ throw new Error("[UniverPdfs] Invalid TrueType font: empty or unreadable cmap table.");
12696
+ }
12014
12697
  return {
12015
12698
  inspection: {
12016
12699
  sfntVersion,
@@ -12318,7 +13001,7 @@ function subsetTrueTypeFont(ttfBytes, codePoints) {
12318
13001
  const cmapPairs = [];
12319
13002
  for (const cp of uniqueCps) {
12320
13003
  const oldGid = cmapMap.get(cp);
12321
- if (oldGid !== void 0 && oldGid > 0) {
13004
+ if (oldGid !== void 0 && oldGid > 0 && oldGid < inspection.numGlyphs) {
12322
13005
  const newGid = enqueueOldGid(oldGid);
12323
13006
  codePointToGid[cp] = newGid;
12324
13007
  cmapPairs.push({ cp, gid: newGid });
@@ -12462,7 +13145,7 @@ function buildCompositeTestGlyph(compGidA, compGidB) {
12462
13145
  view.setInt16(24, 80, false);
12463
13146
  return buf;
12464
13147
  }
12465
- 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\u2605";
13148
+ var DEFAULT_FIXTURE_CJK_TEXT = "\u987A\u4E30\u7535\u5B50\u9762\u5355\u4E09\u8054\u91C7\u8D2D\u51FA\u5E93\u5957\u6253\u6A21\u677F\u542B\u8FFD\u6EAF\u7801\u660E\u7EC6\u8868\u4E0E\u7B7E\u6536\u7EA2\u7AE0\u828B\u9053\u4F01\u4E1A\u7EA7\u62A5\u8868\u8BA2\u5355\u7F16\u53F7\u5BA2\u6237\u540D\u79F0\u6536\u8D27\u5730\u5740\u5546\u54C1\u89C4\u683C\u6570\u91CF\u5355\u4EF7\u91D1\u989D\u5408\u8BA1\u5DF2\u6838\u9A8C\u4FDD\u4EF7\u8FD0\u8F93\u6B21\u65E5\u8FBE\u9646\u8FD0\u4E13\u7968\u666E\u7968\u4E0A\u6D77\u6D66\u4E1C\u5F20\u6C5F\u9AD8\u79D1\u6280\u56ED\u533A\u5317\u4EAC\u6DF1\u5733\u676D\u5DDE\u4E2D\u6587\u77E2\u91CF\u53EF\u68C0\u7D22\u5B57\u4F53\u5B50\u96C6\u5316\u6D4B\u8BD5\u4E00\u4E8C\u4E09\u56DB\u4E94\u516D\u4E03\u516B\u4E5D\u5341\u767E\u5343\u4E07\u96F6\u5143\u89D2\u5206\u5E74\u6708\u65E5\u65F6\u5206\u79D2\u9875\u5171\u7B2C\u5185\u90E8\u8D44\u6599\u590D\u5370\u65E0\u6548\u8D22\u52A1\u4E13\u7528\u7AE0\u4ED3\u5E93\u7B7E\u7AE0\u9879\u76EE\u6458\u8981\u5BA1\u6279\u4EBA\u65E5\u671F\u8BF4\u660E\u72B6\u6001\u901A\u8FC7\u5F85\u5BA1\u6BD4\u4F8B\u589E\u957F\u7387\u5B8C\u6210\u5EA6\u6708\u5EA6\u5B63\u5EA6\u5E74\u5EA6\u5DE5\u4E1A\u4F20\u611F\u5668\u6A21\u5757\u63A7\u5236\u5668\u7CBE\u5BC6\u7EC4\u4EF6\u534E\u4E1C\u534E\u5357\u534E\u5317\u7ECF\u8425\u7B80\u62A5\u6838\u5FC3\u6B63\u5E38\u884C\u51FA\u88C1\u5207\u5916\u6EA2\u90BB\u683C\u5F20\u5DE5\u636E\u6001\u5165\u8DE8\u8868\u5934\u6591\u9A6C\u7EB9\u8FDE\u7EED\u6027\u8BC1\u5E8F\u5DE6\u5BF9\u9F50\u9876\u90E8\u5E95\u53F3\u7F29\u5C0F\u5B57\u81EA\u9002\u5E94\u591A\u6BB5\u6DF7\u6392\u957F\u6587\u672C\u793A\u4F8B\u5168\u89D2\u6807\u70B9\u5907\u6CE8\u751F\u50FB\u56FE\u6807\u7F3A\u8BCA\u65AD\u5DEE\u9519\u4EA4\u4ED8\u56FA\u9AD8\u5C06\u5728\u4E25\u7EDD\u5411\u4E0B\u65B9\u5143\u7D20\u4F4D\u8FB9\u4E4B\u5C45\u5782\u76F4\u7387\u5F53\u7D27\u51D1\u52A8\u81F3\u4F4E\u4FDD\u7559\u6536\u7F16\u5907\u54C1\u5957\u9996\u4FB5\u5165\u4EC5\u672B\u5C3E\u73B0\u91CD\u53E0\u680F\u51C6\u7248\u5730\u5B9A\u5BB9\u500D\u540E\xD7\xA5\uFFE5\uFF0C\u3002\uFF1A\uFF1B\uFF01\uFF1F\uFF08\uFF09\u3010\u3011\u300A\u300B\uFF05\u2014\xB7\u201C\u201D\u2018\u2019\uFF5C\u2605";
12466
13149
  function buildMinimalTestTrueTypeFont(extraCodePoints) {
12467
13150
  const cpSet = /* @__PURE__ */ new Set();
12468
13151
  for (let ascii = 32; ascii <= 126; ascii++) {
@@ -15270,8 +15953,11 @@ export {
15270
15953
  parseSvgTransformAttr,
15271
15954
  parseSvgToVectorCommands,
15272
15955
  drawVectorSvgOnPdfPage,
15956
+ PdfRenderError,
15957
+ clearPdfFontUrlCache,
15273
15958
  resolveTemplateString,
15274
15959
  validatePdfTemplateVariables,
15960
+ wrapMixedCjkAndLatinLines,
15275
15961
  renderQrCodeDataUrl,
15276
15962
  computeDynamicFontSize,
15277
15963
  computeAutoFitFontSize,
@@ -15280,6 +15966,7 @@ export {
15280
15966
  formatPdfTableCell,
15281
15967
  computePdfTableSummaryRow,
15282
15968
  resolveDynamicTableRawRows,
15969
+ calculatePdfTableRowCapacity,
15283
15970
  paginatePdfTableRows,
15284
15971
  formatBatesNumber,
15285
15972
  exportPdfBytes,
@@ -15291,6 +15978,7 @@ export {
15291
15978
  overlayDiagnosticGridOnPdfBytes,
15292
15979
  inspectPdfExportCapabilities,
15293
15980
  collectUsedCodePointsFromPdfUnit,
15981
+ collectMissingGlyphsFromPdfUnit,
15294
15982
  inspectTrueTypeFont,
15295
15983
  getTrueTypeMappedCodePoints,
15296
15984
  subsetTrueTypeFont,
@@ -15332,4 +16020,4 @@ export {
15332
16020
  renderJsxToPdfmeTemplate,
15333
16021
  exportJsxToPdfBytes
15334
16022
  };
15335
- //# sourceMappingURL=chunk-72OJSR4Z.js.map
16023
+ //# sourceMappingURL=chunk-4A226M74.js.map