@yudaocode/univer-pdfs 1.6.218 → 1.6.219

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/es/index.js CHANGED
@@ -20,6 +20,8 @@ import {
20
20
  PAGE_SIZE_PRESETS_MM,
21
21
  PDF_PAGE_PRESETS,
22
22
  PDF_PASSWORD_PADDING,
23
+ PDF_STANDARD_STAMP_PRESETS,
24
+ PDF_STANDARD_STAMP_PRESET_MAP,
23
25
  PDF_TABLE_THEME_PRESETS,
24
26
  PT_PER_MM,
25
27
  Page,
@@ -49,6 +51,7 @@ import {
49
51
  applyPdfSecurityToDocument,
50
52
  buildMinimalTestTrueTypeFont,
51
53
  buildObjectEncryptionKey,
54
+ buildPdfApprovalStampSvg,
52
55
  bytesToHex,
53
56
  calculatePdfTableRowCapacity,
54
57
  clearPdfFontUrlCache,
@@ -74,6 +77,8 @@ import {
74
77
  computeSmartSnapWithEqualGap,
75
78
  computeUserPasswordValue,
76
79
  createDefaultPdfUnitData,
80
+ createPdfApprovalStampElement,
81
+ createPdfApprovalStampSvgElement,
77
82
  createPdfCjkFontSources,
78
83
  decodePdfPermissionFlags,
79
84
  decryptPdfBytes,
@@ -111,13 +116,16 @@ import {
111
116
  extractAcroFormValuesFromPdfBytes,
112
117
  extractNativeTextSpansFromPdfBytes,
113
118
  extractPdfFormValues,
119
+ extractSvgTextDescriptors,
114
120
  fillPdfFormValues,
115
121
  formatBatesNumber,
116
122
  formatGs1HumanReadable,
117
123
  formatPdfDateTimeValue,
124
+ formatPdfPageIndicesLabel,
118
125
  formatPdfTableCell,
119
126
  fromPdfmeTemplate,
120
127
  getDefaultDateTimeFormat,
128
+ getPdfStandardStampPreset,
121
129
  getTrueTypeMappedCodePoints,
122
130
  hexToBytes,
123
131
  importFromPdfmeTemplate,
@@ -149,6 +157,7 @@ import {
149
157
  parsePdfColorWithAlpha,
150
158
  parsePdfContentStreamTextOps,
151
159
  parsePdfPageRange,
160
+ parsePdfPageRangeSpec,
152
161
  parseSafeKeyValueRecord,
153
162
  parseSvgToVectorCommands,
154
163
  parseSvgTransformAttr,
@@ -174,6 +183,7 @@ import {
174
183
  resolveDynamicTableRawRows,
175
184
  resolveMultiVariableText,
176
185
  resolvePageSizeMm,
186
+ resolvePdfCropBoxPt,
177
187
  resolvePolygonNormalizedPoints,
178
188
  resolveTemplateString,
179
189
  rgbToCmyk,
@@ -182,6 +192,8 @@ import {
182
192
  scanTemplateExpressionTokens,
183
193
  smoothSignatureStrokeQuadratic,
184
194
  splitPdfBytes,
195
+ splitPdfBytesByRanges,
196
+ splitPdfUnitByRanges,
185
197
  stripPdfPageNativeTextInRects,
186
198
  subsetTrueTypeFont,
187
199
  svgToDataUri,
@@ -196,7 +208,7 @@ import {
196
208
  visitTemplateVariables,
197
209
  wrapMixedCjkAndLatinLines,
198
210
  wrapPdfTextLines
199
- } from "./chunk-SUXA7HBV.js";
211
+ } from "./chunk-PQUNQAVL.js";
200
212
  import {
201
213
  Fragment,
202
214
  PDF_JSX_ELEMENT_SYMBOL,
@@ -752,6 +764,8 @@ var PdfSelectionService = class extends Disposable {
752
764
  this.viewportRatio$ = this._viewportRatio$.asObservable();
753
765
  this._previewOpen$ = new BehaviorSubject(false);
754
766
  this.previewOpen$ = this._previewOpen$.asObservable();
767
+ this._splitModalOpen$ = new BehaviorSubject(false);
768
+ this.splitModalOpen$ = this._splitModalOpen$.asObservable();
755
769
  this._findReplaceOpen$ = new BehaviorSubject(false);
756
770
  this.findReplaceOpen$ = this._findReplaceOpen$.asObservable();
757
771
  this._searchHighlight$ = new BehaviorSubject(null);
@@ -798,6 +812,7 @@ var PdfSelectionService = class extends Disposable {
798
812
  this._inkColor$.complete();
799
813
  this._viewportRatio$.complete();
800
814
  this._previewOpen$.complete();
815
+ this._splitModalOpen$.complete();
801
816
  this._findReplaceOpen$.complete();
802
817
  this._searchHighlight$.complete();
803
818
  this._scrollTarget$.complete();
@@ -938,6 +953,12 @@ var PdfSelectionService = class extends Disposable {
938
953
  setPreviewOpen(open) {
939
954
  this._previewOpen$.next(open);
940
955
  }
956
+ getSplitModalOpen() {
957
+ return this._splitModalOpen$.getValue();
958
+ }
959
+ setSplitModalOpen(open) {
960
+ this._splitModalOpen$.next(open);
961
+ }
941
962
  getFindReplaceOpen() {
942
963
  return this._findReplaceOpen$.getValue();
943
964
  }
@@ -1354,8 +1375,12 @@ function createDefaultElementByType(type, partial) {
1354
1375
  type: "stamp" /* STAMP */,
1355
1376
  name: partial?.name ?? "\u7535\u5B50\u7B7E\u7AE0",
1356
1377
  stampShape: partial?.stampShape ?? "oval",
1378
+ ...partial?.preset ? { preset: partial.preset } : {},
1357
1379
  primaryText: partial?.primaryText ?? "\u828B\u9053\u79D1\u6280\u5408\u540C\u4E13\u7528\u7AE0",
1358
1380
  secondaryText: partial?.secondaryText ?? "\u5DF2\u5BA1\u6838 \xB7 APPROVED",
1381
+ ...partial?.signer ? { signer: partial.signer } : {},
1382
+ ...partial?.dateText ? { dateText: partial.dateText } : {},
1383
+ ...partial?.svgContent ? { svgContent: partial.svgContent } : {},
1359
1384
  color: partial?.color ?? "#dc2626",
1360
1385
  opacity: partial?.opacity ?? 0.88,
1361
1386
  transform: {
@@ -1566,6 +1591,7 @@ function createDefaultElementByType(type, partial) {
1566
1591
  const annotationType = partial?.annotationType ?? "highlight";
1567
1592
  const defaultColor = annotationType === "highlight" ? "#facc15" : annotationType === "stickyNote" ? "#f59e0b" : annotationType === "squiggly" ? "#f97316" : "#ef4444";
1568
1593
  const isSticky = annotationType === "stickyNote";
1594
+ const resolvedReviewStatus = partial?.reviewStatus ?? (partial?.status === "accepted" || partial?.status === "rejected" || partial?.status === "completed" || partial?.status === "cancelled" ? partial.status : "open");
1569
1595
  return {
1570
1596
  id,
1571
1597
  type: "annotation" /* ANNOTATION */,
@@ -1575,7 +1601,8 @@ function createDefaultElementByType(type, partial) {
1575
1601
  opacity: partial?.opacity ?? (annotationType === "highlight" ? 0.38 : 0.95),
1576
1602
  author: partial?.author ?? "Reviewer",
1577
1603
  comment: partial?.comment ?? "",
1578
- status: partial?.status ?? "open",
1604
+ status: partial?.status ?? resolvedReviewStatus,
1605
+ reviewStatus: resolvedReviewStatus,
1579
1606
  replies: Array.isArray(partial?.replies) ? Tools2.deepClone(partial.replies) : [],
1580
1607
  transform: {
1581
1608
  ...baseTransform,
@@ -1681,6 +1708,14 @@ var UpdatePdfElementsCommand = {
1681
1708
  ...item.patch.style ?? {}
1682
1709
  };
1683
1710
  }
1711
+ if (merged.type === "annotation" /* ANNOTATION */) {
1712
+ const patchAny = item.patch;
1713
+ if (patchAny.status !== void 0 && patchAny.reviewStatus === void 0) {
1714
+ merged.reviewStatus = patchAny.status === "resolved" ? "completed" : patchAny.status;
1715
+ } else if (patchAny.reviewStatus !== void 0 && patchAny.status === void 0) {
1716
+ merged.status = patchAny.reviewStatus;
1717
+ }
1718
+ }
1684
1719
  afterUpdates.push({ id: item.id, element: merged });
1685
1720
  }
1686
1721
  }
@@ -2089,13 +2124,16 @@ var SetPdfPageCropBoxCommand = {
2089
2124
  if (!prevPage) return false;
2090
2125
  const beforePage = Tools2.deepClone(prevPage);
2091
2126
  const afterPage = Tools2.deepClone(prevPage);
2092
- if (params?.cropBox) {
2093
- afterPage.cropBox = {
2094
- left: Math.max(0, Number(params.cropBox.left) || 0),
2095
- top: Math.max(0, Number(params.cropBox.top) || 0),
2096
- width: Math.max(8, Number(params.cropBox.width) || 8),
2097
- height: Math.max(8, Number(params.cropBox.height) || 8)
2098
- };
2127
+ const resolvedCrop = resolvePdfCropBoxPt(params?.cropBox ?? null);
2128
+ if (resolvedCrop && params?.cropBox) {
2129
+ const hasPtAliases = "leftPt" in params.cropBox || "topPt" in params.cropBox || "widthPt" in params.cropBox || "heightPt" in params.cropBox;
2130
+ afterPage.cropBox = hasPtAliases ? {
2131
+ ...resolvedCrop,
2132
+ leftPt: resolvedCrop.left,
2133
+ topPt: resolvedCrop.top,
2134
+ widthPt: resolvedCrop.width,
2135
+ heightPt: resolvedCrop.height
2136
+ } : resolvedCrop;
2099
2137
  } else {
2100
2138
  delete afterPage.cropBox;
2101
2139
  }
@@ -3100,6 +3138,153 @@ var UpdatePdfUnitPropsCommand = {
3100
3138
  return Boolean(result);
3101
3139
  }
3102
3140
  };
3141
+ function resolveAnnotationTarget(unit, preferredPageId, elementId) {
3142
+ const direct = unit.getElement(preferredPageId, elementId);
3143
+ if (direct && direct.type === "annotation" /* ANNOTATION */) {
3144
+ return { pageId: preferredPageId, element: direct };
3145
+ }
3146
+ for (const pid of unit.getPageOrder()) {
3147
+ const found = unit.getElement(pid, elementId);
3148
+ if (found && found.type === "annotation" /* ANNOTATION */) {
3149
+ return { pageId: pid, element: found };
3150
+ }
3151
+ }
3152
+ return null;
3153
+ }
3154
+ var AddPdfAnnotationReplyCommand = {
3155
+ id: "pdfs.command.add-annotation-reply",
3156
+ type: CommandType2.COMMAND,
3157
+ handler: (accessor, params) => {
3158
+ if (!params?.elementId) return false;
3159
+ const rawContent = (params.reply?.content ?? params.content ?? "").trim();
3160
+ if (!rawContent) return false;
3161
+ const ctx = resolveContext(accessor, params.unitId, params.pageId);
3162
+ if (!ctx) return false;
3163
+ const target = resolveAnnotationTarget(ctx.unit, ctx.pageId, params.elementId);
3164
+ if (!target) return false;
3165
+ const newReply = {
3166
+ id: params.reply?.id || params.id || `reply-${generateRandomId3(6)}`,
3167
+ author: (params.reply?.author ?? params.author ?? "Reviewer").trim() || "Reviewer",
3168
+ content: rawContent,
3169
+ createdAt: params.reply?.createdAt || params.createdAt || (/* @__PURE__ */ new Date()).toISOString()
3170
+ };
3171
+ const beforeEl = Tools2.deepClone(target.element);
3172
+ const afterEl = {
3173
+ ...Tools2.deepClone(target.element),
3174
+ replies: [...Tools2.deepClone(target.element.replies ?? []), Tools2.deepClone(newReply)]
3175
+ };
3176
+ const commandService = accessor.get(ICommandService);
3177
+ const undoRedoService = accessor.get(IUndoRedoService);
3178
+ const redoParams = {
3179
+ unitId: ctx.unitId,
3180
+ pageId: target.pageId,
3181
+ updates: [{ id: target.element.id, element: afterEl }]
3182
+ };
3183
+ const undoParams = {
3184
+ unitId: ctx.unitId,
3185
+ pageId: target.pageId,
3186
+ updates: [{ id: target.element.id, element: beforeEl }]
3187
+ };
3188
+ const result = commandService.syncExecuteCommand(UpdatePdfElementsMutation.id, redoParams);
3189
+ if (result) {
3190
+ undoRedoService.pushUndoRedo({
3191
+ unitID: ctx.unitId,
3192
+ undoMutations: [{ id: UpdatePdfElementsMutation.id, params: undoParams }],
3193
+ redoMutations: [{ id: UpdatePdfElementsMutation.id, params: redoParams }]
3194
+ });
3195
+ params.onCreated?.(Tools2.deepClone(newReply));
3196
+ }
3197
+ return Boolean(result);
3198
+ }
3199
+ };
3200
+ var DeletePdfAnnotationReplyCommand = {
3201
+ id: "pdfs.command.delete-annotation-reply",
3202
+ type: CommandType2.COMMAND,
3203
+ handler: (accessor, params) => {
3204
+ if (!params?.elementId || !params?.replyId) return false;
3205
+ const ctx = resolveContext(accessor, params.unitId, params.pageId);
3206
+ if (!ctx) return false;
3207
+ const target = resolveAnnotationTarget(ctx.unit, ctx.pageId, params.elementId);
3208
+ if (!target) return false;
3209
+ const prevReplies = target.element.replies ?? [];
3210
+ if (!prevReplies.some((r) => r.id === params.replyId)) {
3211
+ return false;
3212
+ }
3213
+ const beforeEl = Tools2.deepClone(target.element);
3214
+ const afterEl = {
3215
+ ...Tools2.deepClone(target.element),
3216
+ replies: Tools2.deepClone(prevReplies.filter((r) => r.id !== params.replyId))
3217
+ };
3218
+ const commandService = accessor.get(ICommandService);
3219
+ const undoRedoService = accessor.get(IUndoRedoService);
3220
+ const redoParams = {
3221
+ unitId: ctx.unitId,
3222
+ pageId: target.pageId,
3223
+ updates: [{ id: target.element.id, element: afterEl }]
3224
+ };
3225
+ const undoParams = {
3226
+ unitId: ctx.unitId,
3227
+ pageId: target.pageId,
3228
+ updates: [{ id: target.element.id, element: beforeEl }]
3229
+ };
3230
+ const result = commandService.syncExecuteCommand(UpdatePdfElementsMutation.id, redoParams);
3231
+ if (result) {
3232
+ undoRedoService.pushUndoRedo({
3233
+ unitID: ctx.unitId,
3234
+ undoMutations: [{ id: UpdatePdfElementsMutation.id, params: undoParams }],
3235
+ redoMutations: [{ id: UpdatePdfElementsMutation.id, params: redoParams }]
3236
+ });
3237
+ }
3238
+ return Boolean(result);
3239
+ }
3240
+ };
3241
+ var VALID_ANNOTATION_REVIEW_STATUSES = /* @__PURE__ */ new Set([
3242
+ "open",
3243
+ "accepted",
3244
+ "rejected",
3245
+ "completed",
3246
+ "cancelled"
3247
+ ]);
3248
+ var SetPdfAnnotationReviewStatusCommand = {
3249
+ id: "pdfs.command.set-annotation-review-status",
3250
+ type: CommandType2.COMMAND,
3251
+ handler: (accessor, params) => {
3252
+ if (!params?.elementId || !VALID_ANNOTATION_REVIEW_STATUSES.has(params.reviewStatus)) {
3253
+ return false;
3254
+ }
3255
+ const ctx = resolveContext(accessor, params.unitId, params.pageId);
3256
+ if (!ctx) return false;
3257
+ const target = resolveAnnotationTarget(ctx.unit, ctx.pageId, params.elementId);
3258
+ if (!target) return false;
3259
+ const beforeEl = Tools2.deepClone(target.element);
3260
+ const afterEl = {
3261
+ ...Tools2.deepClone(target.element),
3262
+ reviewStatus: params.reviewStatus,
3263
+ status: params.reviewStatus
3264
+ };
3265
+ const commandService = accessor.get(ICommandService);
3266
+ const undoRedoService = accessor.get(IUndoRedoService);
3267
+ const redoParams = {
3268
+ unitId: ctx.unitId,
3269
+ pageId: target.pageId,
3270
+ updates: [{ id: target.element.id, element: afterEl }]
3271
+ };
3272
+ const undoParams = {
3273
+ unitId: ctx.unitId,
3274
+ pageId: target.pageId,
3275
+ updates: [{ id: target.element.id, element: beforeEl }]
3276
+ };
3277
+ const result = commandService.syncExecuteCommand(UpdatePdfElementsMutation.id, redoParams);
3278
+ if (result) {
3279
+ undoRedoService.pushUndoRedo({
3280
+ unitID: ctx.unitId,
3281
+ undoMutations: [{ id: UpdatePdfElementsMutation.id, params: undoParams }],
3282
+ redoMutations: [{ id: UpdatePdfElementsMutation.id, params: redoParams }]
3283
+ });
3284
+ }
3285
+ return Boolean(result);
3286
+ }
3287
+ };
3103
3288
 
3104
3289
  // src/exporter/pdf-advanced-tools.ts
3105
3290
  import { generateRandomId as generateRandomId4, Tools as Tools3 } from "@univerjs/core";
@@ -5086,160 +5271,1274 @@ async function verifyPdfAuditSeal(pdfBytes) {
5086
5271
  }
5087
5272
 
5088
5273
  // src/exporter/pdf-convert-and-compliance.ts
5089
- import { generateRandomId as generateRandomId5, Tools as Tools4 } from "@univerjs/core";
5274
+ import { generateRandomId as generateRandomId6, Tools as Tools5 } from "@univerjs/core";
5090
5275
  import {
5091
5276
  clip,
5092
5277
  concatTransformationMatrix,
5093
5278
  decodePDFRawStream,
5094
5279
  drawObject,
5095
5280
  endPath,
5281
+ PDFArray as PDFArray4,
5282
+ PDFDict as PDFDict4,
5283
+ PDFDocument as PDFDocument4,
5284
+ PDFHexString as PDFHexString4,
5285
+ PDFName as PDFName4,
5286
+ PDFRawStream as PDFRawStream2,
5287
+ PDFRef as PDFRef4,
5288
+ PDFString as PDFString4,
5289
+ popGraphicsState,
5290
+ pushGraphicsState,
5291
+ rectangle
5292
+ } from "pdf-lib";
5293
+
5294
+ // src/exporter/pdf-importer.ts
5295
+ import { generateRandomId as generateRandomId5, Tools as Tools4 } from "@univerjs/core";
5296
+ import {
5096
5297
  PDFArray as PDFArray3,
5097
5298
  PDFDict as PDFDict3,
5098
5299
  PDFDocument as PDFDocument3,
5099
5300
  PDFHexString as PDFHexString3,
5100
5301
  PDFName as PDFName3,
5101
- PDFRawStream as PDFRawStream2,
5302
+ PDFNumber as PDFNumber2,
5102
5303
  PDFRef as PDFRef3,
5103
- PDFString as PDFString3,
5104
- popGraphicsState,
5105
- pushGraphicsState,
5106
- rectangle
5304
+ PDFString as PDFString3
5107
5305
  } from "pdf-lib";
5108
- function collectOrderedPageFragments(unit, pageId, pageIndex) {
5109
- const suppressed = new Set(unit.editState.suppressedSourceIds ?? []);
5110
- const layersById = new Map((unit.layers ?? []).map((l) => [l.id, l]));
5111
- const rawSpans = unit.metadata?.nativeTextSpansByPage?.[pageId] ?? unit.editState.nativeTextSpansByPage?.[pageId] ?? [];
5112
- const textFragments = rawSpans.filter((s) => !s.suppressed && !suppressed.has(s.id) && s.text.trim().length > 0).map((s) => ({
5113
- text: s.text.trim(),
5114
- left: s.left,
5115
- top: s.top,
5116
- width: s.width,
5117
- height: s.height,
5118
- fontSize: s.fontSize || 11,
5119
- bold: (s.fontSize || 11) >= 14
5120
- }));
5121
- const explicitBlocks = [];
5122
- const map = unit.editState.elementsByPage[pageId] ?? {};
5123
- const order = unit.editState.elementOrderByPage[pageId] ?? Object.keys(map);
5124
- for (const id of order) {
5125
- const el = map[id];
5126
- if (!el || el.hidden) continue;
5127
- if (el.layerId) {
5128
- const layer = layersById.get(el.layerId);
5129
- if (layer && layer.visible === false && layer.printable === false) continue;
5130
- }
5131
- if (el.type === "text" /* TEXT */) {
5132
- const txt = (el.content ?? "").trim();
5133
- if (!txt) continue;
5134
- const lines = txt.split("\n");
5135
- const fs = el.style?.fontSize ?? 12;
5136
- const lineH = fs * (el.style?.lineHeight ?? 1.35);
5137
- lines.forEach((line, lIdx) => {
5138
- if (!line.trim()) return;
5139
- textFragments.push({
5140
- text: line.trim(),
5141
- left: el.transform.left,
5142
- top: el.transform.top + lIdx * lineH,
5143
- width: el.transform.width,
5144
- height: lineH,
5145
- fontSize: fs,
5146
- bold: el.style?.fontWeight === "bold"
5147
- });
5148
- });
5149
- } else if (el.type === "checkbox" /* CHECKBOX */) {
5150
- textFragments.push({
5151
- text: `${el.checked ? "[X]" : "[ ]"} ${el.label || el.name || ""}`.trim(),
5152
- left: el.transform.left,
5153
- top: el.transform.top,
5154
- width: el.transform.width,
5155
- height: el.transform.height,
5156
- fontSize: el.style?.fontSize ?? 10.5,
5157
- bold: false
5158
- });
5159
- } else if (el.type === "select" /* SELECT */ || el.type === "radioGroup" /* RADIO_GROUP */) {
5160
- if (el.value) {
5161
- textFragments.push({
5162
- text: `${el.name ? `${el.name}: ` : ""}${el.value}`,
5163
- left: el.transform.left,
5164
- top: el.transform.top,
5165
- width: el.transform.width,
5166
- height: el.transform.height,
5167
- fontSize: el.style?.fontSize ?? 10.5,
5168
- bold: false
5169
- });
5170
- }
5171
- } else if (el.type === "table" /* TABLE */) {
5172
- const headers = el.columns.map((c) => c.header);
5173
- const formattedRows = (el.rows ?? []).map(
5174
- (r) => el.columns.map((col, ci) => formatPdfTableCell(r[ci], col))
5175
- );
5176
- explicitBlocks.push({
5177
- type: "table",
5178
- headers,
5179
- rows: formattedRows,
5180
- pageIndex,
5181
- topPt: el.transform.top
5182
- });
5183
- } else if (el.type === "list" /* LIST */) {
5184
- explicitBlocks.push({
5185
- type: "list",
5186
- ordered: el.listType === "ordered",
5187
- items: [...el.items ?? []],
5188
- pageIndex,
5189
- topPt: el.transform.top
5190
- });
5191
- } else if (el.type === "image" /* IMAGE */) {
5192
- explicitBlocks.push({
5193
- type: "image",
5194
- altText: el.altText || el.name || "Image",
5195
- widthPt: el.transform.width,
5196
- heightPt: el.transform.height,
5197
- src: el.src,
5198
- pageIndex,
5199
- topPt: el.transform.top
5200
- });
5306
+ function hasPdfMagicHeader(bytes) {
5307
+ if (!bytes || bytes.byteLength < 5) return false;
5308
+ const maxScan = Math.min(bytes.byteLength - 5, 1024);
5309
+ for (let i = 0; i <= maxScan; i++) {
5310
+ if (bytes[i] === 37 && bytes[i + 1] === 80 && bytes[i + 2] === 68 && bytes[i + 3] === 70 && bytes[i + 4] === 45) {
5311
+ return true;
5201
5312
  }
5202
5313
  }
5203
- return { textFragments, explicitBlocks };
5314
+ return false;
5204
5315
  }
5205
- function clusterFragmentsIntoLines(fragments) {
5206
- if (fragments.length === 0) return [];
5207
- const sorted = [...fragments].sort((a, b) => a.top - b.top || a.left - b.left);
5208
- const rawLines = [];
5209
- for (const frag of sorted) {
5210
- const centerY = frag.top + frag.height / 2;
5211
- const hit = rawLines.find((line) => {
5212
- const lineRef = line[0];
5213
- const lineCenterY = lineRef.top + lineRef.height / 2;
5214
- const tol = Math.max(4.5, Math.min(frag.height, lineRef.height) * 0.5);
5215
- return Math.abs(centerY - lineCenterY) <= tol;
5216
- });
5217
- if (hit) {
5218
- hit.push(frag);
5219
- } else {
5220
- rawLines.push([frag]);
5221
- }
5316
+ function decodePdfTextValue(obj) {
5317
+ if (obj instanceof PDFHexString3 || obj instanceof PDFString3 || obj instanceof PDFName3) {
5318
+ return obj.decodeText();
5222
5319
  }
5223
- return rawLines.map((items) => {
5224
- items.sort((a, b) => a.left - b.left);
5225
- const cells = [];
5226
- for (const it of items) {
5227
- const prev = cells[cells.length - 1];
5228
- if (prev && it.left - prev.right <= 12) {
5229
- prev.text = `${prev.text} ${it.text}`.trim();
5230
- prev.right = Math.max(prev.right, it.left + it.width);
5231
- } else {
5232
- cells.push({
5233
- left: it.left,
5234
- right: it.left + it.width,
5235
- text: it.text
5236
- });
5320
+ return "";
5321
+ }
5322
+ function extractOutlinesBookmarksFromDoc(doc) {
5323
+ const outlinesRef = doc.catalog.get(PDFName3.of("Outlines"));
5324
+ const outlinesDict = doc.context.lookupMaybe(outlinesRef, PDFDict3);
5325
+ if (!outlinesDict) return [];
5326
+ const pages = doc.getPages();
5327
+ const pageRefKeyToIdx = /* @__PURE__ */ new Map();
5328
+ pages.forEach((p, idx) => {
5329
+ pageRefKeyToIdx.set(`${p.ref.objectNumber}:${p.ref.generationNumber}`, idx);
5330
+ });
5331
+ const resolveDest = (itemDict) => {
5332
+ let destObj = itemDict.get(PDFName3.of("Dest"));
5333
+ if (!destObj) {
5334
+ const actionDict = doc.context.lookupMaybe(itemDict.get(PDFName3.of("A")), PDFDict3);
5335
+ if (actionDict) {
5336
+ destObj = actionDict.get(PDFName3.of("D"));
5237
5337
  }
5238
5338
  }
5239
- return {
5240
- topPt: Math.min(...items.map((x) => x.top)),
5241
- bottomPt: Math.max(...items.map((x) => x.top + x.height)),
5242
- fontSize: Math.max(...items.map((x) => x.fontSize)),
5339
+ const destArr = doc.context.lookupMaybe(destObj, PDFArray3);
5340
+ if (!destArr || destArr.size() === 0) return { pageIndex: 0 };
5341
+ const pRef = destArr.get(0);
5342
+ let pageIndex = 0;
5343
+ if (pRef instanceof PDFRef3) {
5344
+ pageIndex = pageRefKeyToIdx.get(`${pRef.objectNumber}:${pRef.generationNumber}`) ?? 0;
5345
+ } else if (pRef instanceof PDFNumber2) {
5346
+ pageIndex = Math.max(0, Math.min(pages.length - 1, Math.floor(pRef.asNumber())));
5347
+ }
5348
+ let topPt;
5349
+ if (destArr.size() >= 4) {
5350
+ const yObj = destArr.get(3);
5351
+ if (yObj instanceof PDFNumber2 && pages[pageIndex]) {
5352
+ const pageHeight = pages[pageIndex].getHeight();
5353
+ topPt = Math.round(Math.max(0, pageHeight - yObj.asNumber()) * 100) / 100;
5354
+ }
5355
+ }
5356
+ return { pageIndex, topPt };
5357
+ };
5358
+ const visited = /* @__PURE__ */ new Set();
5359
+ const walkLevel = (firstRef) => {
5360
+ const list = [];
5361
+ let cur = firstRef;
5362
+ while (cur) {
5363
+ if (cur instanceof PDFRef3) {
5364
+ const key = `${cur.objectNumber}:${cur.generationNumber}`;
5365
+ if (visited.has(key)) break;
5366
+ visited.add(key);
5367
+ }
5368
+ const itemDict = cur instanceof PDFDict3 ? cur : doc.context.lookupMaybe(cur, PDFDict3);
5369
+ if (!itemDict) break;
5370
+ const title = decodePdfTextValue(itemDict.get(PDFName3.of("Title"))) || "Bookmark";
5371
+ const { pageIndex, topPt } = resolveDest(itemDict);
5372
+ const childFirst = itemDict.get(PDFName3.of("First"));
5373
+ const children = childFirst ? walkLevel(childFirst) : [];
5374
+ const bm = {
5375
+ id: `bm-${generateRandomId5(6)}`,
5376
+ title,
5377
+ pageIndex,
5378
+ ...topPt !== void 0 ? { topOffsetPt: topPt, topPt } : {},
5379
+ ...children.length > 0 ? { children } : {}
5380
+ };
5381
+ list.push(bm);
5382
+ const nextRef = itemDict.get(PDFName3.of("Next"));
5383
+ if (!nextRef || nextRef === cur) break;
5384
+ cur = nextRef;
5385
+ }
5386
+ return list;
5387
+ };
5388
+ return walkLevel(outlinesDict.get(PDFName3.of("First")));
5389
+ }
5390
+ function extractLayersFromDoc(doc) {
5391
+ const ocProps = doc.context.lookupMaybe(doc.catalog.get(PDFName3.of("OCProperties")), PDFDict3);
5392
+ if (!ocProps) return [];
5393
+ const ocgsArr = doc.context.lookupMaybe(ocProps.get(PDFName3.of("OCGs")), PDFArray3);
5394
+ if (!ocgsArr || ocgsArr.size() === 0) return [];
5395
+ const defaultCfg = doc.context.lookupMaybe(ocProps.get(PDFName3.of("D")), PDFDict3);
5396
+ const offRefKeys = /* @__PURE__ */ new Set();
5397
+ const lockedRefKeys = /* @__PURE__ */ new Set();
5398
+ if (defaultCfg) {
5399
+ const offArr = doc.context.lookupMaybe(defaultCfg.get(PDFName3.of("OFF")), PDFArray3);
5400
+ if (offArr) {
5401
+ for (let i = 0; i < offArr.size(); i++) {
5402
+ const r = offArr.get(i);
5403
+ if (r instanceof PDFRef3) offRefKeys.add(`${r.objectNumber}:${r.generationNumber}`);
5404
+ }
5405
+ }
5406
+ const lockedArr = doc.context.lookupMaybe(defaultCfg.get(PDFName3.of("Locked")), PDFArray3);
5407
+ if (lockedArr) {
5408
+ for (let i = 0; i < lockedArr.size(); i++) {
5409
+ const r = lockedArr.get(i);
5410
+ if (r instanceof PDFRef3) lockedRefKeys.add(`${r.objectNumber}:${r.generationNumber}`);
5411
+ }
5412
+ }
5413
+ }
5414
+ const out = [];
5415
+ for (let i = 0; i < ocgsArr.size(); i++) {
5416
+ const entry = ocgsArr.get(i);
5417
+ const key = entry instanceof PDFRef3 ? `${entry.objectNumber}:${entry.generationNumber}` : "";
5418
+ const dict = entry instanceof PDFDict3 ? entry : doc.context.lookupMaybe(entry, PDFDict3);
5419
+ if (!dict) continue;
5420
+ const name = decodePdfTextValue(dict.get(PDFName3.of("Name"))) || `Layer ${i + 1}`;
5421
+ let printable = true;
5422
+ const usage = doc.context.lookupMaybe(dict.get(PDFName3.of("Usage")), PDFDict3);
5423
+ if (usage) {
5424
+ const printDict = doc.context.lookupMaybe(usage.get(PDFName3.of("Print")), PDFDict3);
5425
+ if (printDict && decodePdfTextValue(printDict.get(PDFName3.of("PrintState"))) === "OFF") {
5426
+ printable = false;
5427
+ }
5428
+ }
5429
+ out.push({
5430
+ id: `layer-${generateRandomId5(6)}`,
5431
+ name,
5432
+ visible: key ? !offRefKeys.has(key) : true,
5433
+ locked: key ? lockedRefKeys.has(key) : false,
5434
+ printable
5435
+ });
5436
+ }
5437
+ return out;
5438
+ }
5439
+ async function importPdfBytesToUnit(pdfBytes, options) {
5440
+ if (!hasPdfMagicHeader(pdfBytes)) {
5441
+ throw new Error("Invalid PDF binary: missing %PDF- header signature.");
5442
+ }
5443
+ const encryptionInspection = inspectPdfEncryption(pdfBytes);
5444
+ const decryptedBytes = await verifyAndDecryptPdfBytes(pdfBytes, options?.password);
5445
+ const unitTitle = options?.name ?? options?.title;
5446
+ const unit = await importAcroFormPdfToUnit(decryptedBytes, {
5447
+ unitId: options?.unitId,
5448
+ title: unitTitle
5449
+ });
5450
+ if (options?.fileName && unit.sourceDocumentRef) {
5451
+ unit.sourceDocumentRef.fileName = options.fileName;
5452
+ }
5453
+ try {
5454
+ const doc = await PDFDocument3.load(decryptedBytes, { updateMetadata: false });
5455
+ const parsedBookmarks = extractOutlinesBookmarksFromDoc(doc);
5456
+ if (parsedBookmarks.length > 0) {
5457
+ unit.bookmarks = Tools4.deepClone(parsedBookmarks);
5458
+ unit.metadata = {
5459
+ ...unit.metadata ?? {},
5460
+ bookmarks: Tools4.deepClone(parsedBookmarks)
5461
+ };
5462
+ }
5463
+ const parsedLayers = extractLayersFromDoc(doc);
5464
+ if (parsedLayers.length > 0) {
5465
+ unit.layers = Tools4.deepClone(parsedLayers);
5466
+ }
5467
+ if (unitTitle === void 0) {
5468
+ const docTitle = doc.getTitle();
5469
+ if (docTitle) {
5470
+ unit.name = docTitle;
5471
+ } else if (options?.fileName) {
5472
+ unit.name = options.fileName.replace(/\.pdf$/i, "");
5473
+ }
5474
+ }
5475
+ } catch {
5476
+ }
5477
+ if (encryptionInspection.encrypted) {
5478
+ unit.metadata = {
5479
+ ...unit.metadata ?? {},
5480
+ importedEncryptionInfo: {
5481
+ encrypted: true,
5482
+ requiresOpenPassword: encryptionInspection.requiresOpenPassword,
5483
+ keyLength: encryptionInspection.keyLength,
5484
+ permissions: { ...encryptionInspection.permissions }
5485
+ }
5486
+ };
5487
+ }
5488
+ if (options?.promoteNativeTextToElements) {
5489
+ const spansByPage = unit.editState.nativeTextSpansByPage ?? {};
5490
+ for (const pageId of unit.document.pageOrder) {
5491
+ const pageSpans = spansByPage[pageId] ?? [];
5492
+ if (!unit.editState.elementsByPage[pageId]) {
5493
+ unit.editState.elementsByPage[pageId] = {};
5494
+ }
5495
+ if (!unit.editState.elementOrderByPage[pageId]) {
5496
+ unit.editState.elementOrderByPage[pageId] = [];
5497
+ }
5498
+ for (const span of pageSpans) {
5499
+ if (span.suppressed) continue;
5500
+ span.suppressed = true;
5501
+ const elId = `el-${generateRandomId5(6)}`;
5502
+ const textEl = {
5503
+ id: elId,
5504
+ type: "text" /* TEXT */,
5505
+ name: "Imported Text",
5506
+ content: span.text,
5507
+ metadata: { promotedFromNativeSpanId: span.id },
5508
+ transform: {
5509
+ left: span.left,
5510
+ top: span.top,
5511
+ width: span.width,
5512
+ height: span.height,
5513
+ angle: 0
5514
+ },
5515
+ style: {
5516
+ fontFamily: "Inter, PingFang SC, Microsoft YaHei, sans-serif",
5517
+ fontSize: span.fontSize,
5518
+ fontWeight: "normal",
5519
+ color: "#1B1C1F",
5520
+ textAlign: "left",
5521
+ verticalAlign: "middle",
5522
+ lineHeight: 1.2,
5523
+ padding: 0
5524
+ }
5525
+ };
5526
+ unit.editState.elementsByPage[pageId][elId] = textEl;
5527
+ unit.editState.elementOrderByPage[pageId].push(elId);
5528
+ }
5529
+ }
5530
+ if (unit.metadata?.nativeTextSpansByPage) {
5531
+ unit.metadata.nativeTextSpansByPage = Tools4.deepClone(spansByPage);
5532
+ }
5533
+ }
5534
+ return unit;
5535
+ }
5536
+
5537
+ // src/exporter/pdf-to-pptx.ts
5538
+ var PPTX_EMU_PER_PT = 12700;
5539
+ function ptToPptxEmu(pt) {
5540
+ if (!Number.isFinite(pt)) return 0;
5541
+ return Math.max(0, Math.round(pt * PPTX_EMU_PER_PT));
5542
+ }
5543
+ var PPTX_CRC32_TABLE = (() => {
5544
+ const table = new Uint32Array(256);
5545
+ for (let n = 0; n < 256; n++) {
5546
+ let c = n;
5547
+ for (let k = 0; k < 8; k++) {
5548
+ c = c & 1 ? 3988292384 ^ c >>> 1 : c >>> 1;
5549
+ }
5550
+ table[n] = c >>> 0;
5551
+ }
5552
+ return table;
5553
+ })();
5554
+ function computeCrc32(data) {
5555
+ let crc = 4294967295;
5556
+ for (let i = 0; i < data.length; i++) {
5557
+ crc = PPTX_CRC32_TABLE[(crc ^ data[i]) & 255] ^ crc >>> 8;
5558
+ }
5559
+ return (crc ^ 4294967295) >>> 0;
5560
+ }
5561
+ function buildPptxZipArchive(entries) {
5562
+ const enc = new TextEncoder();
5563
+ const localParts = [];
5564
+ const centralParts = [];
5565
+ let offset = 0;
5566
+ for (const entry of entries) {
5567
+ const nameBytes = enc.encode(entry.path);
5568
+ const data = entry.data;
5569
+ const crc = computeCrc32(data);
5570
+ const localHeader = new Uint8Array(30 + nameBytes.length);
5571
+ const lv = new DataView(localHeader.buffer);
5572
+ lv.setUint32(0, 67324752, true);
5573
+ lv.setUint16(4, 20, true);
5574
+ lv.setUint16(6, 2048, true);
5575
+ lv.setUint16(8, 0, true);
5576
+ lv.setUint16(10, 0, true);
5577
+ lv.setUint16(12, 33, true);
5578
+ lv.setUint32(14, crc, true);
5579
+ lv.setUint32(18, data.byteLength, true);
5580
+ lv.setUint32(22, data.byteLength, true);
5581
+ lv.setUint16(26, nameBytes.length, true);
5582
+ lv.setUint16(28, 0, true);
5583
+ localHeader.set(nameBytes, 30);
5584
+ const centralHeader = new Uint8Array(46 + nameBytes.length);
5585
+ const cv = new DataView(centralHeader.buffer);
5586
+ cv.setUint32(0, 33639248, true);
5587
+ cv.setUint16(4, 20, true);
5588
+ cv.setUint16(6, 20, true);
5589
+ cv.setUint16(8, 2048, true);
5590
+ cv.setUint16(10, 0, true);
5591
+ cv.setUint16(12, 0, true);
5592
+ cv.setUint16(14, 33, true);
5593
+ cv.setUint32(16, crc, true);
5594
+ cv.setUint32(20, data.byteLength, true);
5595
+ cv.setUint32(24, data.byteLength, true);
5596
+ cv.setUint16(28, nameBytes.length, true);
5597
+ cv.setUint16(30, 0, true);
5598
+ cv.setUint16(32, 0, true);
5599
+ cv.setUint16(34, 0, true);
5600
+ cv.setUint16(36, 0, true);
5601
+ cv.setUint32(38, 0, true);
5602
+ cv.setUint32(42, offset, true);
5603
+ centralHeader.set(nameBytes, 46);
5604
+ localParts.push(localHeader, data);
5605
+ centralParts.push(centralHeader);
5606
+ offset += localHeader.byteLength + data.byteLength;
5607
+ }
5608
+ const centralSize = centralParts.reduce((sum, part) => sum + part.byteLength, 0);
5609
+ const eocd = new Uint8Array(22);
5610
+ const ev = new DataView(eocd.buffer);
5611
+ ev.setUint32(0, 101010256, true);
5612
+ ev.setUint16(4, 0, true);
5613
+ ev.setUint16(6, 0, true);
5614
+ ev.setUint16(8, entries.length, true);
5615
+ ev.setUint16(10, entries.length, true);
5616
+ ev.setUint32(12, centralSize, true);
5617
+ ev.setUint32(16, offset, true);
5618
+ ev.setUint16(20, 0, true);
5619
+ const out = new Uint8Array(offset + centralSize + eocd.byteLength);
5620
+ let pos = 0;
5621
+ for (const part of localParts) {
5622
+ out.set(part, pos);
5623
+ pos += part.byteLength;
5624
+ }
5625
+ for (const part of centralParts) {
5626
+ out.set(part, pos);
5627
+ pos += part.byteLength;
5628
+ }
5629
+ out.set(eocd, pos);
5630
+ return out;
5631
+ }
5632
+ function escapeXml2(raw) {
5633
+ return raw.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
5634
+ }
5635
+ function toRgbHex6(color, fallback = "1B1C1F") {
5636
+ if (!color || color === "transparent" || color === "none") return null;
5637
+ const parsed = parsePdfColorWithAlpha(color);
5638
+ if (!parsed || parsed.a <= 0) return null;
5639
+ const toHex2 = (v) => Math.max(0, Math.min(255, Math.round(v * 255))).toString(16).padStart(2, "0").toUpperCase();
5640
+ const hex6 = `${toHex2(parsed.r)}${toHex2(parsed.g)}${toHex2(parsed.b)}`;
5641
+ const alphaPct = parsed.a < 0.999 ? Math.round(parsed.a * 1e5) : void 0;
5642
+ return { hex6: hex6 || fallback, alphaPct };
5643
+ }
5644
+ function buildSolidFillXml(color, extraOpacity = 1) {
5645
+ const c = toRgbHex6(color);
5646
+ if (!c) return "<a:noFill/>";
5647
+ const baseAlpha = c.alphaPct !== void 0 ? c.alphaPct / 1e5 : 1;
5648
+ const effectiveAlpha = Math.max(0, Math.min(1, baseAlpha * extraOpacity));
5649
+ const alphaTag = effectiveAlpha < 0.999 ? `<a:alpha val="${Math.round(effectiveAlpha * 1e5)}"/>` : "";
5650
+ return `<a:solidFill><a:srgbClr val="${c.hex6}">${alphaTag}</a:srgbClr></a:solidFill>`;
5651
+ }
5652
+ function buildLineXml(strokeColor, strokeWidthPt = 1, options) {
5653
+ if (!strokeColor || strokeColor === "none" || strokeWidthPt <= 0) {
5654
+ return "<a:ln><a:noFill/></a:ln>";
5655
+ }
5656
+ const c = toRgbHex6(strokeColor);
5657
+ if (!c) return "<a:ln><a:noFill/></a:ln>";
5658
+ const wEmu = Math.max(6350, ptToPptxEmu(strokeWidthPt));
5659
+ const baseAlpha = c.alphaPct !== void 0 ? c.alphaPct / 1e5 : 1;
5660
+ const effAlpha = Math.max(0, Math.min(1, baseAlpha * (options?.opacity ?? 1)));
5661
+ const alphaTag = effAlpha < 0.999 ? `<a:alpha val="${Math.round(effAlpha * 1e5)}"/>` : "";
5662
+ const dashTag = options?.dash ? '<a:prstDash val="dash"/>' : "";
5663
+ const headTag = options?.startArrow ? '<a:headEnd type="triangle" w="med" len="med"/>' : "";
5664
+ const tailTag = options?.endArrow ? '<a:tailEnd type="triangle" w="med" len="med"/>' : "";
5665
+ return `<a:ln w="${wEmu}"><a:solidFill><a:srgbClr val="${c.hex6}">${alphaTag}</a:srgbClr></a:solidFill>${dashTag}${headTag}${tailTag}</a:ln>`;
5666
+ }
5667
+ function buildXfrmXml(tagPrefix, leftPt, topPt, widthPt, heightPt, angleDeg, flipX, flipY) {
5668
+ const x = ptToPptxEmu(leftPt);
5669
+ const y = ptToPptxEmu(topPt);
5670
+ const cx = Math.max(12700, ptToPptxEmu(widthPt));
5671
+ const cy = Math.max(12700, ptToPptxEmu(heightPt));
5672
+ const attrs = [];
5673
+ const normAngle = ((angleDeg ?? 0) % 360 + 360) % 360;
5674
+ if (normAngle > 0.01) {
5675
+ attrs.push(`rot="${Math.round(normAngle * 6e4)}"`);
5676
+ }
5677
+ if (flipX) attrs.push('flipH="1"');
5678
+ if (flipY) attrs.push('flipV="1"');
5679
+ const attrSuffix = attrs.length > 0 ? ` ${attrs.join(" ")}` : "";
5680
+ return `<${tagPrefix}:xfrm${attrSuffix}><a:off x="${x}" y="${y}"/><a:ext cx="${cx}" cy="${cy}"/></${tagPrefix}:xfrm>`;
5681
+ }
5682
+ function decodeBase64ToBytes(b64) {
5683
+ const cleaned = b64.replace(/[\r\n\s]/g, "");
5684
+ if (typeof atob === "function") {
5685
+ const bin = atob(cleaned);
5686
+ const out2 = new Uint8Array(bin.length);
5687
+ for (let i = 0; i < bin.length; i++) {
5688
+ out2[i] = bin.charCodeAt(i);
5689
+ }
5690
+ return out2;
5691
+ }
5692
+ const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
5693
+ const lookup = new Uint8Array(256);
5694
+ for (let i = 0; i < chars.length; i++) lookup[chars.charCodeAt(i)] = i;
5695
+ const padLen = cleaned.endsWith("==") ? 2 : cleaned.endsWith("=") ? 1 : 0;
5696
+ const byteLen = Math.max(0, Math.floor(cleaned.length * 3 / 4) - padLen);
5697
+ const out = new Uint8Array(byteLen);
5698
+ let p = 0;
5699
+ for (let i = 0; i < cleaned.length; i += 4) {
5700
+ const e1 = lookup[cleaned.charCodeAt(i)];
5701
+ const e2 = lookup[cleaned.charCodeAt(i + 1)];
5702
+ const e3 = lookup[cleaned.charCodeAt(i + 2)];
5703
+ const e4 = lookup[cleaned.charCodeAt(i + 3)];
5704
+ const triple = e1 << 18 | e2 << 12 | e3 << 6 | e4;
5705
+ if (p < byteLen) out[p++] = triple >> 16 & 255;
5706
+ if (p < byteLen) out[p++] = triple >> 8 & 255;
5707
+ if (p < byteLen) out[p++] = triple & 255;
5708
+ }
5709
+ return out;
5710
+ }
5711
+ function parseRasterImageDataUrl(dataUrl) {
5712
+ if (!dataUrl || !dataUrl.startsWith("data:image/")) return null;
5713
+ const commaIdx = dataUrl.indexOf(",");
5714
+ if (commaIdx < 0) return null;
5715
+ const header = dataUrl.slice(0, commaIdx).toLowerCase();
5716
+ if (!header.includes(";base64")) return null;
5717
+ let ext = null;
5718
+ if (header.startsWith("data:image/png")) {
5719
+ ext = "png";
5720
+ } else if (header.startsWith("data:image/jpeg") || header.startsWith("data:image/jpg")) {
5721
+ ext = "jpg";
5722
+ }
5723
+ if (!ext) return null;
5724
+ const bytes = decodeBase64ToBytes(dataUrl.slice(commaIdx + 1));
5725
+ if (bytes.byteLength === 0) return null;
5726
+ return { ext, bytes };
5727
+ }
5728
+ function mapTextAlignToDrawingMl(align) {
5729
+ if (align === "center") return "ctr";
5730
+ if (align === "right") return "r";
5731
+ if (align === "justify") return "just";
5732
+ return "l";
5733
+ }
5734
+ function mapVertAlignToDrawingMl(vAlign) {
5735
+ if (vAlign === "top") return "t";
5736
+ if (vAlign === "bottom") return "b";
5737
+ return "ctr";
5738
+ }
5739
+ function buildTextBoxShapeXml(params) {
5740
+ const fsPt = Math.max(4, params.style?.fontSize ?? 12);
5741
+ const sz = Math.round(fsPt * 100);
5742
+ const isBold = params.style?.fontWeight === "bold";
5743
+ const isItalic = Boolean(params.style?.italic);
5744
+ const isUnderline = Boolean(params.style?.underline);
5745
+ const textCol = toRgbHex6(params.style?.color, "1B1C1F")?.hex6 ?? "1B1C1F";
5746
+ const algn = mapTextAlignToDrawingMl(params.style?.textAlign);
5747
+ const anchor = mapVertAlignToDrawingMl(params.style?.verticalAlign);
5748
+ const padPt = params.style?.padding ?? (params.noWrap ? 0 : 4);
5749
+ const ins = ptToPptxEmu(padPt);
5750
+ const fillXml = params.style?.backgroundColor ? buildSolidFillXml(params.style.backgroundColor, params.opacity ?? 1) : "<a:noFill/>";
5751
+ const lineXml = params.style?.borderColor && (params.style?.borderWidth ?? 0) > 0 ? buildLineXml(params.style.borderColor, params.style.borderWidth ?? 1, {
5752
+ opacity: params.opacity ?? 1
5753
+ }) : "";
5754
+ const buildRunPr = (opts) => {
5755
+ const attrs = [
5756
+ 'lang="zh-CN"',
5757
+ 'altLang="en-US"',
5758
+ `sz="${opts.szVal}"`,
5759
+ ...opts.bold ? ['b="1"'] : [],
5760
+ ...opts.italic ? ['i="1"'] : [],
5761
+ ...opts.underline ? ['u="sng"'] : [],
5762
+ 'dirty="0"'
5763
+ ].join(" ");
5764
+ return `<a:rPr ${attrs}><a:solidFill><a:srgbClr val="${opts.hex6}"/></a:solidFill></a:rPr>`;
5765
+ };
5766
+ let paragraphsXml = "";
5767
+ if (params.richSpans && params.richSpans.length > 0) {
5768
+ const runsXml = params.richSpans.map((sp) => {
5769
+ const spSz = Math.round(Math.max(4, sp.fontSize ?? fsPt) * 100);
5770
+ const spHex = toRgbHex6(sp.color, textCol)?.hex6 ?? textCol;
5771
+ const rPr = buildRunPr({
5772
+ szVal: spSz,
5773
+ bold: sp.bold ?? isBold,
5774
+ italic: sp.italic ?? isItalic,
5775
+ underline: sp.underline ?? isUnderline,
5776
+ hex6: spHex
5777
+ });
5778
+ return `<a:r>${rPr}<a:t>${escapeXml2(sp.text)}</a:t></a:r>`;
5779
+ }).join("");
5780
+ paragraphsXml = `<a:p><a:pPr algn="${algn}"/>${runsXml}<a:endParaRPr lang="zh-CN" sz="${sz}"/></a:p>`;
5781
+ } else {
5782
+ const lines = (params.text ?? "").replace(/\r\n?/g, "\n").split("\n");
5783
+ const rPr = buildRunPr({
5784
+ szVal: sz,
5785
+ bold: isBold,
5786
+ italic: isItalic,
5787
+ underline: isUnderline,
5788
+ hex6: textCol
5789
+ });
5790
+ paragraphsXml = lines.map(
5791
+ (ln) => `<a:p><a:pPr algn="${algn}"/>${ln.length > 0 ? `<a:r>${rPr}<a:t>${escapeXml2(ln)}</a:t></a:r>` : ""}<a:endParaRPr lang="zh-CN" sz="${sz}"/></a:p>`
5792
+ ).join("");
5793
+ }
5794
+ return [
5795
+ "<p:sp>",
5796
+ `<p:nvSpPr><p:cNvPr id="${params.shapeId}" name="${escapeXml2(params.name)}"/><p:cNvSpPr txBox="1"/><p:nvPr/></p:nvSpPr>`,
5797
+ `<p:spPr>${buildXfrmXml(
5798
+ "a",
5799
+ params.leftPt,
5800
+ params.topPt,
5801
+ params.widthPt,
5802
+ params.heightPt,
5803
+ params.angleDeg,
5804
+ params.flipX,
5805
+ params.flipY
5806
+ )}<a:prstGeom prst="rect"><a:avLst/></a:prstGeom>${fillXml}${lineXml}</p:spPr>`,
5807
+ `<p:txBody><a:bodyPr wrap="${params.noWrap ? "none" : "square"}" lIns="${ins}" tIns="${ins}" rIns="${ins}" bIns="${ins}" anchor="${anchor}"/><a:lstStyle/>${paragraphsXml}</p:txBody>`,
5808
+ "</p:sp>"
5809
+ ].join("");
5810
+ }
5811
+ function buildTableGraphicFrameXml(shapeId, el, sampleData) {
5812
+ const cols = el.columns?.length ? el.columns : [{ id: "col-1", header: "Column 1", field: "col1", widthRatio: 1 }];
5813
+ const totalRatio = cols.reduce((sum, c) => sum + Math.max(0.1, c.widthRatio || 1), 0) || 1;
5814
+ const tableWidthEmu = Math.max(12700, ptToPptxEmu(el.transform.width));
5815
+ const colWidthsEmu = cols.map(
5816
+ (c) => Math.max(12700, Math.round(Math.max(0.1, c.widthRatio || 1) / totalRatio * tableWidthEmu))
5817
+ );
5818
+ const showHead = el.showHead !== false;
5819
+ const headerH = ptToPptxEmu(el.headerHeight ?? 26);
5820
+ const rowH = ptToPptxEmu(el.rowHeight ?? 24);
5821
+ const rawRows = resolveDynamicTableRawRows(el, sampleData);
5822
+ const formattedRows = rawRows.map((r) => cols.map((col, ci) => formatPdfTableCell(r[ci], col)));
5823
+ const totalTableHeightEmu = Math.max(
5824
+ ptToPptxEmu(el.transform.height),
5825
+ (showHead ? headerH : 0) + Math.max(1, formattedRows.length) * rowH
5826
+ );
5827
+ const borderHex = toRgbHex6(el.borderColor ?? "#CBD5E1", "CBD5E1")?.hex6 ?? "CBD5E1";
5828
+ const borderWidthEmu = Math.max(6350, ptToPptxEmu(el.borderWidth ?? 0.75));
5829
+ const cellBordersXml = ["lnL", "lnR", "lnT", "lnB"].map(
5830
+ (tag) => `<a:${tag} w="${borderWidthEmu}" cap="flat" cmpd="sng" algn="ctr"><a:solidFill><a:srgbClr val="${borderHex}"/></a:solidFill></a:${tag}>`
5831
+ ).join("");
5832
+ const buildCellXml = (text, opts) => {
5833
+ const sz = Math.round(Math.max(4, opts.fontSizePt) * 100);
5834
+ const algn = mapTextAlignToDrawingMl(opts.align);
5835
+ const bgHex = toRgbHex6(opts.bgColor)?.hex6;
5836
+ const fillXml = bgHex ? `<a:solidFill><a:srgbClr val="${bgHex}"/></a:solidFill>` : "<a:noFill/>";
5837
+ const rPr = `<a:rPr lang="zh-CN" altLang="en-US" sz="${sz}"${opts.bold ? ' b="1"' : ""} dirty="0"><a:solidFill><a:srgbClr val="${opts.textHex}"/></a:solidFill></a:rPr>`;
5838
+ return [
5839
+ "<a:tc>",
5840
+ `<a:txBody><a:bodyPr/><a:lstStyle/><a:p><a:pPr algn="${algn}"/>${text ? `<a:r>${rPr}<a:t>${escapeXml2(text)}</a:t></a:r>` : ""}<a:endParaRPr lang="zh-CN" sz="${sz}"/></a:p></a:txBody>`,
5841
+ `<a:tcPr marL="45720" marR="45720" marT="22860" marB="22860" anchor="ctr">${cellBordersXml}${fillXml}</a:tcPr>`,
5842
+ "</a:tc>"
5843
+ ].join("");
5844
+ };
5845
+ const trXmlParts = [];
5846
+ if (showHead) {
5847
+ const headFs = el.headerStyle?.fontSize ?? 10;
5848
+ const headHex = toRgbHex6(el.headerStyle?.color, "1B1C1F")?.hex6 ?? "1B1C1F";
5849
+ const headBg = el.headerStyle?.backgroundColor ?? "#F1F5F9";
5850
+ const headCells = cols.map(
5851
+ (col) => buildCellXml(col.header ?? "", {
5852
+ fontSizePt: headFs,
5853
+ bold: (el.headerStyle?.fontWeight ?? "bold") === "bold",
5854
+ textHex: headHex,
5855
+ bgColor: headBg,
5856
+ align: col.align ?? "left"
5857
+ })
5858
+ ).join("");
5859
+ trXmlParts.push(`<a:tr h="${headerH}">${headCells}</a:tr>`);
5860
+ }
5861
+ const bodyFs = el.bodyStyle?.fontSize ?? 10;
5862
+ const bodyHex = toRgbHex6(el.bodyStyle?.color, "334155")?.hex6 ?? "334155";
5863
+ const bodyBold = el.bodyStyle?.fontWeight === "bold";
5864
+ const stripeBg = el.zebraStripeColor ?? el.stripedColor;
5865
+ const effectiveBodyRows = formattedRows.length > 0 ? formattedRows : [cols.map(() => "")];
5866
+ effectiveBodyRows.forEach((row, rIdx) => {
5867
+ const rowBg = rIdx % 2 === 1 && stripeBg ? stripeBg : el.bodyStyle?.backgroundColor;
5868
+ const cellsXml = cols.map(
5869
+ (col, cIdx) => buildCellXml(row[cIdx] ?? "", {
5870
+ fontSizePt: bodyFs,
5871
+ bold: bodyBold,
5872
+ textHex: bodyHex,
5873
+ bgColor: rowBg,
5874
+ align: col.align ?? "left"
5875
+ })
5876
+ ).join("");
5877
+ trXmlParts.push(`<a:tr h="${rowH}">${cellsXml}</a:tr>`);
5878
+ });
5879
+ const gridColsXml = colWidthsEmu.map((w) => `<a:gridCol w="${w}"/>`).join("");
5880
+ return [
5881
+ "<p:graphicFrame>",
5882
+ `<p:nvGraphicFramePr><p:cNvPr id="${shapeId}" name="${escapeXml2(el.name || "Table")}"/><p:cNvGraphicFramePr><a:graphicFrameLocks noGrp="1"/></p:cNvGraphicFramePr><p:nvPr/></p:nvGraphicFramePr>`,
5883
+ `<p:xfrm><a:off x="${ptToPptxEmu(el.transform.left)}" y="${ptToPptxEmu(el.transform.top)}"/><a:ext cx="${tableWidthEmu}" cy="${totalTableHeightEmu}"/></p:xfrm>`,
5884
+ '<a:graphic><a:graphicData uri="http://schemas.openxmlformats.org/presentationml/2006/table">',
5885
+ `<a:tbl><a:tblPr firstRow="${showHead ? 1 : 0}" bandRow="1"/><a:tblGrid>${gridColsXml}</a:tblGrid>${trXmlParts.join("")}</a:tbl>`,
5886
+ "</a:graphicData></a:graphic>",
5887
+ "</p:graphicFrame>"
5888
+ ].join("");
5889
+ }
5890
+ function buildPictureXml(params) {
5891
+ return [
5892
+ "<p:pic>",
5893
+ `<p:nvPicPr><p:cNvPr id="${params.shapeId}" name="${escapeXml2(params.name)}"/><p:cNvPicPr><a:picLocks noChangeAspect="0"/></p:cNvPicPr><p:nvPr/></p:nvPicPr>`,
5894
+ `<p:blipFill><a:blip r:embed="${params.rId}"/><a:stretch><a:fillRect/></a:stretch></p:blipFill>`,
5895
+ `<p:spPr>${buildXfrmXml(
5896
+ "a",
5897
+ params.leftPt,
5898
+ params.topPt,
5899
+ params.widthPt,
5900
+ params.heightPt,
5901
+ params.angleDeg,
5902
+ params.flipX,
5903
+ params.flipY
5904
+ )}<a:prstGeom prst="rect"><a:avLst/></a:prstGeom></p:spPr>`,
5905
+ "</p:pic>"
5906
+ ].join("");
5907
+ }
5908
+ function buildVectorGeomShapeXml(params) {
5909
+ const fillXml = params.prst === "line" ? "" : buildSolidFillXml(params.fillColor, params.opacity ?? 1);
5910
+ const lineXml = buildLineXml(params.strokeColor, params.strokeWidthPt ?? 1, {
5911
+ dash: params.dash,
5912
+ startArrow: params.startArrow,
5913
+ endArrow: params.endArrow,
5914
+ opacity: params.opacity ?? 1
5915
+ });
5916
+ const txBody = params.labelText ? `<p:txBody><a:bodyPr anchor="ctr"/><a:lstStyle/><a:p><a:pPr algn="ctr"/><a:r><a:rPr lang="zh-CN" sz="900" b="1"><a:solidFill><a:srgbClr val="${toRgbHex6(params.labelColor, "FFFFFF")?.hex6 ?? "FFFFFF"}"/></a:solidFill></a:rPr><a:t>${escapeXml2(params.labelText)}</a:t></a:r></a:p></p:txBody>` : "";
5917
+ return [
5918
+ "<p:sp>",
5919
+ `<p:nvSpPr><p:cNvPr id="${params.shapeId}" name="${escapeXml2(params.name)}"/><p:cNvSpPr/><p:nvPr/></p:nvSpPr>`,
5920
+ `<p:spPr>${buildXfrmXml(
5921
+ "a",
5922
+ params.leftPt,
5923
+ params.topPt,
5924
+ params.widthPt,
5925
+ params.heightPt,
5926
+ params.angleDeg,
5927
+ params.flipX,
5928
+ params.flipY
5929
+ )}<a:prstGeom prst="${params.prst}"><a:avLst/></a:prstGeom>${fillXml}${lineXml}</p:spPr>`,
5930
+ txBody,
5931
+ "</p:sp>"
5932
+ ].join("");
5933
+ }
5934
+ function convertPdfUnitToPptxBytes(unitData) {
5935
+ const enc = new TextEncoder();
5936
+ const rawPageOrder = unitData.document.pageOrder ?? [];
5937
+ const pageIds = rawPageOrder.length > 0 ? rawPageOrder : ["__empty_slide_1__"];
5938
+ const firstPage = rawPageOrder[0] ? unitData.document.pages[rawPageOrder[0]] : void 0;
5939
+ const presentationSize = firstPage?.pageSize ?? unitData.document.pageSize ?? {
5940
+ width: 595.28,
5941
+ height: 841.89
5942
+ };
5943
+ const sldCxEmu = Math.min(51206400, Math.max(914400, ptToPptxEmu(presentationSize.width)));
5944
+ const sldCyEmu = Math.min(51206400, Math.max(914400, ptToPptxEmu(presentationSize.height)));
5945
+ const suppressedSet = new Set(unitData.editState.suppressedSourceIds ?? []);
5946
+ const layersById = new Map((unitData.layers ?? []).map((l) => [l.id, l]));
5947
+ const sampleData = unitData.metadata?.sampleData;
5948
+ const rawSpansByPage = unitData.metadata?.nativeTextSpansByPage ?? unitData.editState.nativeTextSpansByPage ?? {};
5949
+ const mediaFiles = [];
5950
+ const mediaIndexBySrc = /* @__PURE__ */ new Map();
5951
+ const registerMediaDataUrl = (src) => {
5952
+ if (!src) return null;
5953
+ const cachedIdx = mediaIndexBySrc.get(src);
5954
+ if (cachedIdx !== void 0) {
5955
+ const m = mediaFiles[cachedIdx];
5956
+ return { fileName: m.fileName, ext: m.ext };
5957
+ }
5958
+ const parsed = parseRasterImageDataUrl(src);
5959
+ if (!parsed) return null;
5960
+ const nextNumber = mediaFiles.length + 1;
5961
+ const fileName = `image${nextNumber}.${parsed.ext}`;
5962
+ mediaIndexBySrc.set(src, mediaFiles.length);
5963
+ mediaFiles.push({ fileName, ext: parsed.ext, bytes: parsed.bytes });
5964
+ return { fileName, ext: parsed.ext };
5965
+ };
5966
+ const slideXmlEntries = [];
5967
+ pageIds.forEach((pageId, pageIndex) => {
5968
+ const pageMeta = unitData.document.pages[pageId];
5969
+ const pageCtx = { pageNumber: pageIndex + 1, totalPages: pageIds.length };
5970
+ const shapeXmlParts = [];
5971
+ const slideMediaRels = [];
5972
+ let nextShapeId = 2;
5973
+ let nextRelId = 2;
5974
+ const spans = rawSpansByPage[pageId] ?? [];
5975
+ for (const sp of spans) {
5976
+ if (sp.suppressed || suppressedSet.has(sp.id) || !sp.text.trim()) continue;
5977
+ const fs = sp.fontSize || 11;
5978
+ shapeXmlParts.push(
5979
+ buildTextBoxShapeXml({
5980
+ shapeId: nextShapeId++,
5981
+ name: `NativeText ${sp.id}`,
5982
+ leftPt: sp.left,
5983
+ topPt: sp.top,
5984
+ widthPt: Math.max(12, sp.width),
5985
+ heightPt: Math.max(10, sp.height),
5986
+ text: sp.text,
5987
+ style: {
5988
+ fontSize: fs,
5989
+ fontWeight: fs >= 14 ? "bold" : "normal",
5990
+ color: "#1B1C1F",
5991
+ textAlign: "left",
5992
+ verticalAlign: "middle",
5993
+ padding: 0
5994
+ },
5995
+ noWrap: true
5996
+ })
5997
+ );
5998
+ }
5999
+ const elMap = unitData.editState.elementsByPage[pageId] ?? {};
6000
+ const elOrder = unitData.editState.elementOrderByPage[pageId] ?? Object.keys(elMap);
6001
+ for (const elId of elOrder) {
6002
+ const el = elMap[elId];
6003
+ if (!el || el.hidden) continue;
6004
+ if (el.layerId) {
6005
+ const layer = layersById.get(el.layerId);
6006
+ if (layer && layer.visible === false && layer.printable === false) continue;
6007
+ }
6008
+ const tr = el.transform;
6009
+ const flipX = Boolean(tr.flipX ?? el.flipX);
6010
+ const flipY = Boolean(tr.flipY ?? el.flipY);
6011
+ if (el.type === "text" /* TEXT */) {
6012
+ const resolvedText = resolveTemplateString(
6013
+ el.content ?? "",
6014
+ el.fieldKey || el.bindingField,
6015
+ sampleData,
6016
+ pageCtx
6017
+ );
6018
+ shapeXmlParts.push(
6019
+ buildTextBoxShapeXml({
6020
+ shapeId: nextShapeId++,
6021
+ name: el.name || `Text ${el.id}`,
6022
+ leftPt: tr.left,
6023
+ topPt: tr.top,
6024
+ widthPt: tr.width,
6025
+ heightPt: tr.height,
6026
+ angleDeg: tr.angle,
6027
+ flipX,
6028
+ flipY,
6029
+ text: resolvedText,
6030
+ style: el.style,
6031
+ richSpans: el.richSpans,
6032
+ opacity: el.opacity
6033
+ })
6034
+ );
6035
+ } else if (el.type === "list" /* LIST */) {
6036
+ const listLines = (el.items ?? []).map(
6037
+ (item, idx) => el.listType === "ordered" ? `${(el.startNumber ?? 1) + idx}. ${item}` : el.listType === "check" ? `[x] ${item}` : `\u2022 ${item}`
6038
+ );
6039
+ shapeXmlParts.push(
6040
+ buildTextBoxShapeXml({
6041
+ shapeId: nextShapeId++,
6042
+ name: el.name || `List ${el.id}`,
6043
+ leftPt: tr.left,
6044
+ topPt: tr.top,
6045
+ widthPt: tr.width,
6046
+ heightPt: tr.height,
6047
+ angleDeg: tr.angle,
6048
+ flipX,
6049
+ flipY,
6050
+ text: listLines.join("\n"),
6051
+ style: { verticalAlign: "top", ...el.style ?? {} },
6052
+ opacity: el.opacity
6053
+ })
6054
+ );
6055
+ } else if (el.type === "dateTime" /* DATE_TIME */) {
6056
+ const formattedDt = formatPdfDateTimeValue(el.value, el.format, el.dateKind, el.locale);
6057
+ shapeXmlParts.push(
6058
+ buildTextBoxShapeXml({
6059
+ shapeId: nextShapeId++,
6060
+ name: el.name || `DateTime ${el.id}`,
6061
+ leftPt: tr.left,
6062
+ topPt: tr.top,
6063
+ widthPt: tr.width,
6064
+ heightPt: tr.height,
6065
+ angleDeg: tr.angle,
6066
+ flipX,
6067
+ flipY,
6068
+ text: formattedDt || el.value || "",
6069
+ style: {
6070
+ fontSize: el.fontSize ?? el.style?.fontSize ?? 11,
6071
+ color: el.color ?? el.style?.color ?? "#1B1C1F",
6072
+ backgroundColor: el.backgroundColor ?? el.style?.backgroundColor,
6073
+ textAlign: el.align ?? el.style?.textAlign ?? "left",
6074
+ verticalAlign: "middle"
6075
+ },
6076
+ opacity: el.opacity
6077
+ })
6078
+ );
6079
+ } else if (el.type === "checkbox" /* CHECKBOX */ || el.type === "radioGroup" /* RADIO_GROUP */ || el.type === "select" /* SELECT */) {
6080
+ const widgetText = el.type === "checkbox" /* CHECKBOX */ ? `${el.checked ? "[X]" : "[ ]"} ${el.label || ""}`.trim() : el.value || "";
6081
+ shapeXmlParts.push(
6082
+ buildTextBoxShapeXml({
6083
+ shapeId: nextShapeId++,
6084
+ name: el.name || `Form ${el.id}`,
6085
+ leftPt: tr.left,
6086
+ topPt: tr.top,
6087
+ widthPt: tr.width,
6088
+ heightPt: tr.height,
6089
+ angleDeg: tr.angle,
6090
+ text: widgetText,
6091
+ style: el.style ?? { fontSize: 10.5, color: "#1B1C1F" }
6092
+ })
6093
+ );
6094
+ } else if (el.type === "table" /* TABLE */) {
6095
+ shapeXmlParts.push(buildTableGraphicFrameXml(nextShapeId++, el, sampleData));
6096
+ } else if (el.type === "shape" /* SHAPE */) {
6097
+ const prst = el.shapeType === "ellipse" ? "ellipse" : el.shapeType === "line" ? "line" : (el.borderRadius ?? 0) > 0 ? "roundRect" : "rect";
6098
+ shapeXmlParts.push(
6099
+ buildVectorGeomShapeXml({
6100
+ shapeId: nextShapeId++,
6101
+ name: el.name || `Shape ${el.id}`,
6102
+ prst,
6103
+ leftPt: tr.left,
6104
+ topPt: tr.top,
6105
+ widthPt: tr.width,
6106
+ heightPt: tr.height,
6107
+ angleDeg: tr.angle,
6108
+ flipX,
6109
+ flipY,
6110
+ fillColor: el.fillColor,
6111
+ strokeColor: el.strokeColor,
6112
+ strokeWidthPt: el.strokeWidth ?? 1,
6113
+ dash: Boolean(el.dashArray?.length),
6114
+ startArrow: el.startArrow,
6115
+ endArrow: el.endArrow,
6116
+ opacity: el.shapeType === "highlight" ? el.opacity ?? 0.38 : el.opacity ?? 1
6117
+ })
6118
+ );
6119
+ } else if (el.type === "line" /* LINE */) {
6120
+ shapeXmlParts.push(
6121
+ buildVectorGeomShapeXml({
6122
+ shapeId: nextShapeId++,
6123
+ name: el.name || `Line ${el.id}`,
6124
+ prst: "line",
6125
+ leftPt: tr.left,
6126
+ topPt: tr.top,
6127
+ widthPt: tr.width,
6128
+ heightPt: Math.max(1, tr.height),
6129
+ angleDeg: tr.angle,
6130
+ flipX,
6131
+ flipY,
6132
+ strokeColor: el.strokeColor ?? "#2563EB",
6133
+ strokeWidthPt: el.strokeWidth ?? 1.5,
6134
+ dash: Boolean(el.dashArray?.length),
6135
+ startArrow: el.startArrow,
6136
+ endArrow: el.endArrow,
6137
+ opacity: el.opacity ?? 1
6138
+ })
6139
+ );
6140
+ } else if (el.type === "ellipse" /* ELLIPSE */) {
6141
+ shapeXmlParts.push(
6142
+ buildVectorGeomShapeXml({
6143
+ shapeId: nextShapeId++,
6144
+ name: el.name || `Ellipse ${el.id}`,
6145
+ prst: "ellipse",
6146
+ leftPt: tr.left,
6147
+ topPt: tr.top,
6148
+ widthPt: tr.width,
6149
+ heightPt: tr.height,
6150
+ angleDeg: tr.angle,
6151
+ flipX,
6152
+ flipY,
6153
+ fillColor: el.fillColor,
6154
+ strokeColor: el.strokeColor ?? "#2563EB",
6155
+ strokeWidthPt: el.strokeWidth ?? 1.5,
6156
+ dash: Boolean(el.dashArray?.length),
6157
+ opacity: el.opacity ?? 1
6158
+ })
6159
+ );
6160
+ } else if (el.type === "redaction" /* REDACTION */) {
6161
+ shapeXmlParts.push(
6162
+ buildVectorGeomShapeXml({
6163
+ shapeId: nextShapeId++,
6164
+ name: el.name || `Redaction ${el.id}`,
6165
+ prst: "rect",
6166
+ leftPt: tr.left,
6167
+ topPt: tr.top,
6168
+ widthPt: tr.width,
6169
+ heightPt: tr.height,
6170
+ fillColor: el.fillColor ?? "#000000",
6171
+ strokeColor: el.fillColor ?? "#000000",
6172
+ strokeWidthPt: 1,
6173
+ labelText: el.overlayLabel ?? "[CONFIDENTIAL]",
6174
+ labelColor: "#FFFFFF"
6175
+ })
6176
+ );
6177
+ } else if (el.type === "stamp" /* STAMP */) {
6178
+ const stampLines = [
6179
+ el.primaryText,
6180
+ el.secondaryText,
6181
+ [el.signer, el.dateText].filter(Boolean).join(" \xB7 ")
6182
+ ].filter(Boolean);
6183
+ shapeXmlParts.push(
6184
+ buildTextBoxShapeXml({
6185
+ shapeId: nextShapeId++,
6186
+ name: el.name || `Stamp ${el.id}`,
6187
+ leftPt: tr.left,
6188
+ topPt: tr.top,
6189
+ widthPt: tr.width,
6190
+ heightPt: tr.height,
6191
+ angleDeg: tr.angle,
6192
+ text: stampLines.join("\n"),
6193
+ style: {
6194
+ fontSize: 10,
6195
+ fontWeight: "bold",
6196
+ color: el.color ?? "#DC2626",
6197
+ borderColor: el.color ?? "#DC2626",
6198
+ borderWidth: 1.5,
6199
+ textAlign: "center",
6200
+ verticalAlign: "middle"
6201
+ },
6202
+ opacity: el.opacity ?? 0.9
6203
+ })
6204
+ );
6205
+ } else if (el.type === "image" /* IMAGE */ || el.type === "signature" /* SIGNATURE */) {
6206
+ const rawSrc = el.type === "image" /* IMAGE */ ? el.src || (el.resourceId ? unitData.resourceBindings?.[el.resourceId]?.dataUri : void 0) : el.signatureDataUri;
6207
+ const registered = registerMediaDataUrl(rawSrc);
6208
+ if (registered) {
6209
+ const rId = `rId${nextRelId++}`;
6210
+ slideMediaRels.push({ rId, target: `../media/${registered.fileName}` });
6211
+ shapeXmlParts.push(
6212
+ buildPictureXml({
6213
+ shapeId: nextShapeId++,
6214
+ name: el.name || el.altText || `Picture ${el.id}`,
6215
+ rId,
6216
+ leftPt: tr.left,
6217
+ topPt: tr.top,
6218
+ widthPt: tr.width,
6219
+ heightPt: tr.height,
6220
+ angleDeg: tr.angle,
6221
+ flipX,
6222
+ flipY
6223
+ })
6224
+ );
6225
+ } else if (el.type === "signature" /* SIGNATURE */ && (el.signerName || el.label)) {
6226
+ shapeXmlParts.push(
6227
+ buildTextBoxShapeXml({
6228
+ shapeId: nextShapeId++,
6229
+ name: el.name || `Signature ${el.id}`,
6230
+ leftPt: tr.left,
6231
+ topPt: tr.top,
6232
+ widthPt: tr.width,
6233
+ heightPt: tr.height,
6234
+ text: el.signerName ? `Signed: ${el.signerName}` : el.label ?? "Signature",
6235
+ style: { fontSize: 10, color: "#31363F", borderColor: "#7D8698", borderWidth: 1 }
6236
+ })
6237
+ );
6238
+ }
6239
+ }
6240
+ }
6241
+ const bgHex = pageMeta?.backgroundColor && pageMeta.backgroundColor.toLowerCase() !== "#ffffff" ? toRgbHex6(pageMeta.backgroundColor)?.hex6 : void 0;
6242
+ const bgXml = bgHex ? `<p:bg><p:bgPr><a:solidFill><a:srgbClr val="${bgHex}"/></a:solidFill><a:effectLst/></p:bgPr></p:bg>` : "";
6243
+ const slideXml = [
6244
+ '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>',
6245
+ '<p:sld xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main">',
6246
+ `<p:cSld>${bgXml}<p:spTree>`,
6247
+ '<p:nvGrpSpPr><p:cNvPr id="1" name=""/><p:cNvGrpSpPr/><p:nvPr/></p:nvGrpSpPr>',
6248
+ '<p:grpSpPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="0" cy="0"/><a:chOff x="0" y="0"/><a:chExt cx="0" cy="0"/></a:xfrm></p:grpSpPr>',
6249
+ shapeXmlParts.join(""),
6250
+ "</p:spTree></p:cSld>",
6251
+ "<p:clrMapOvr><a:masterClrMapping/></p:clrMapOvr>",
6252
+ "</p:sld>"
6253
+ ].join("");
6254
+ const slideRelsXml = [
6255
+ '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>',
6256
+ '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">',
6257
+ '<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideLayout" Target="../slideLayouts/slideLayout1.xml"/>',
6258
+ ...slideMediaRels.map(
6259
+ (rel) => `<Relationship Id="${rel.rId}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/image" Target="${rel.target}"/>`
6260
+ ),
6261
+ "</Relationships>"
6262
+ ].join("");
6263
+ slideXmlEntries.push({ slideXml, slideRelsXml });
6264
+ });
6265
+ const slideCount = slideXmlEntries.length;
6266
+ const sldIdListXml = slideXmlEntries.map((_, idx) => `<p:sldId id="${256 + idx}" r:id="rId${idx + 2}"/>`).join("");
6267
+ const presentationXml = [
6268
+ '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>',
6269
+ '<p:presentation xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main" saveSubsetFonts="1">',
6270
+ '<p:sldMasterIdLst><p:sldMasterId id="2147483648" r:id="rId1"/></p:sldMasterIdLst>',
6271
+ `<p:sldIdLst>${sldIdListXml}</p:sldIdLst>`,
6272
+ `<p:sldSz cx="${sldCxEmu}" cy="${sldCyEmu}"/>`,
6273
+ '<p:notesSz cx="6858000" cy="9144000"/>',
6274
+ "<p:defaultTextStyle/>",
6275
+ "</p:presentation>"
6276
+ ].join("");
6277
+ const presRelNextBase = slideCount + 2;
6278
+ const presentationRelsXml = [
6279
+ '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>',
6280
+ '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">',
6281
+ '<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideMaster" Target="slideMasters/slideMaster1.xml"/>',
6282
+ ...slideXmlEntries.map(
6283
+ (_, idx) => `<Relationship Id="rId${idx + 2}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/slide" Target="slides/slide${idx + 1}.xml"/>`
6284
+ ),
6285
+ `<Relationship Id="rId${presRelNextBase}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/presProps" Target="presProps.xml"/>`,
6286
+ `<Relationship Id="rId${presRelNextBase + 1}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/viewProps" Target="viewProps.xml"/>`,
6287
+ `<Relationship Id="rId${presRelNextBase + 2}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/tableStyles" Target="tableStyles.xml"/>`,
6288
+ `<Relationship Id="rId${presRelNextBase + 3}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme" Target="theme/theme1.xml"/>`,
6289
+ "</Relationships>"
6290
+ ].join("");
6291
+ const contentTypesXml = [
6292
+ '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>',
6293
+ '<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">',
6294
+ '<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>',
6295
+ '<Default Extension="xml" ContentType="application/xml"/>',
6296
+ '<Default Extension="png" ContentType="image/png"/>',
6297
+ '<Default Extension="jpg" ContentType="image/jpeg"/>',
6298
+ '<Default Extension="jpeg" ContentType="image/jpeg"/>',
6299
+ '<Override PartName="/ppt/presentation.xml" ContentType="application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml"/>',
6300
+ '<Override PartName="/ppt/slideMasters/slideMaster1.xml" ContentType="application/vnd.openxmlformats-officedocument.presentationml.slideMaster+xml"/>',
6301
+ '<Override PartName="/ppt/slideLayouts/slideLayout1.xml" ContentType="application/vnd.openxmlformats-officedocument.presentationml.slideLayout+xml"/>',
6302
+ '<Override PartName="/ppt/theme/theme1.xml" ContentType="application/vnd.openxmlformats-officedocument.theme+xml"/>',
6303
+ '<Override PartName="/ppt/presProps.xml" ContentType="application/vnd.openxmlformats-officedocument.presentationml.presProps+xml"/>',
6304
+ '<Override PartName="/ppt/viewProps.xml" ContentType="application/vnd.openxmlformats-officedocument.presentationml.viewProps+xml"/>',
6305
+ '<Override PartName="/ppt/tableStyles.xml" ContentType="application/vnd.openxmlformats-officedocument.presentationml.tableStyles+xml"/>',
6306
+ '<Override PartName="/docProps/core.xml" ContentType="application/vnd.openxmlformats-package.core-properties+xml"/>',
6307
+ '<Override PartName="/docProps/app.xml" ContentType="application/vnd.openxmlformats-officedocument.extended-properties+xml"/>',
6308
+ ...slideXmlEntries.map(
6309
+ (_, idx) => `<Override PartName="/ppt/slides/slide${idx + 1}.xml" ContentType="application/vnd.openxmlformats-officedocument.presentationml.slide+xml"/>`
6310
+ ),
6311
+ "</Types>"
6312
+ ].join("");
6313
+ const rootRelsXml = [
6314
+ '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>',
6315
+ '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">',
6316
+ '<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="ppt/presentation.xml"/>',
6317
+ '<Relationship Id="rId2" Type="http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties" Target="docProps/core.xml"/>',
6318
+ '<Relationship Id="rId3" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties" Target="docProps/app.xml"/>',
6319
+ "</Relationships>"
6320
+ ].join("");
6321
+ const slideMasterXml = [
6322
+ '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>',
6323
+ '<p:sldMaster xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main">',
6324
+ '<p:cSld><p:bg><p:bgRef idx="1001"><a:schemeClr val="bg1"/></p:bgRef></p:bg><p:spTree><p:nvGrpSpPr><p:cNvPr id="1" name=""/><p:cNvGrpSpPr/><p:nvPr/></p:nvGrpSpPr><p:grpSpPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="0" cy="0"/><a:chOff x="0" y="0"/><a:chExt cx="0" cy="0"/></a:xfrm></p:grpSpPr></p:spTree></p:cSld>',
6325
+ '<p:clrMap bg1="lt1" tx1="dk1" bg2="lt2" tx2="dk2" accent1="accent1" accent2="accent2" accent3="accent3" accent4="accent4" accent5="accent5" accent6="accent6" hlink="hlink" folHlink="folHlink"/>',
6326
+ '<p:sldLayoutIdLst><p:sldLayoutId id="2147483649" r:id="rId1"/></p:sldLayoutIdLst>',
6327
+ "</p:sldMaster>"
6328
+ ].join("");
6329
+ const slideMasterRelsXml = [
6330
+ '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>',
6331
+ '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">',
6332
+ '<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideLayout" Target="../slideLayouts/slideLayout1.xml"/>',
6333
+ '<Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme" Target="../theme/theme1.xml"/>',
6334
+ "</Relationships>"
6335
+ ].join("");
6336
+ const slideLayoutXml = [
6337
+ '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>',
6338
+ '<p:sldLayout xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main" type="blank" preserve="1">',
6339
+ '<p:cSld name="Blank"><p:spTree><p:nvGrpSpPr><p:cNvPr id="1" name=""/><p:cNvGrpSpPr/><p:nvPr/></p:nvGrpSpPr><p:grpSpPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="0" cy="0"/><a:chOff x="0" y="0"/><a:chExt cx="0" cy="0"/></a:xfrm></p:grpSpPr></p:spTree></p:cSld>',
6340
+ "<p:clrMapOvr><a:masterClrMapping/></p:clrMapOvr>",
6341
+ "</p:sldLayout>"
6342
+ ].join("");
6343
+ const slideLayoutRelsXml = [
6344
+ '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>',
6345
+ '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">',
6346
+ '<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideMaster" Target="../slideMasters/slideMaster1.xml"/>',
6347
+ "</Relationships>"
6348
+ ].join("");
6349
+ const themeXml = [
6350
+ '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>',
6351
+ '<a:theme xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" name="Univer PDF Theme">',
6352
+ "<a:themeElements>",
6353
+ '<a:clrScheme name="Standard"><a:dk1><a:srgbClr val="1B1C1F"/></a:dk1><a:lt1><a:srgbClr val="FFFFFF"/></a:lt1><a:dk2><a:srgbClr val="31363F"/></a:dk2><a:lt2><a:srgbClr val="F9FAFB"/></a:lt2><a:accent1><a:srgbClr val="2C53F1"/></a:accent1><a:accent2><a:srgbClr val="16A34A"/></a:accent2><a:accent3><a:srgbClr val="DC2626"/></a:accent3><a:accent4><a:srgbClr val="EA580C"/></a:accent4><a:accent5><a:srgbClr val="0D9488"/></a:accent5><a:accent6><a:srgbClr val="4F46E5"/></a:accent6><a:hlink><a:srgbClr val="2563EB"/></a:hlink><a:folHlink><a:srgbClr val="4F46E5"/></a:folHlink></a:clrScheme>',
6354
+ '<a:fontScheme name="Standard"><a:majorFont><a:latin typeface="Calibri"/><a:ea typeface="PingFang SC"/><a:cs typeface=""/></a:majorFont><a:minorFont><a:latin typeface="Calibri"/><a:ea typeface="PingFang SC"/><a:cs typeface=""/></a:minorFont></a:fontScheme>',
6355
+ '<a:fmtScheme name="Standard"><a:fillStyleLst><a:solidFill><a:schemeClr val="phClr"/></a:solidFill><a:solidFill><a:schemeClr val="phClr"/></a:solidFill><a:solidFill><a:schemeClr val="phClr"/></a:solidFill></a:fillStyleLst><a:lnStyleLst><a:ln w="9525"><a:solidFill><a:schemeClr val="phClr"/></a:solidFill></a:ln><a:ln w="19050"><a:solidFill><a:schemeClr val="phClr"/></a:solidFill></a:ln><a:ln w="25400"><a:solidFill><a:schemeClr val="phClr"/></a:solidFill></a:ln></a:lnStyleLst><a:effectStyleLst><a:effectStyle><a:effectLst/></a:effectStyle><a:effectStyle><a:effectLst/></a:effectStyle><a:effectStyle><a:effectLst/></a:effectStyle></a:effectStyleLst><a:bgFillStyleLst><a:solidFill><a:schemeClr val="phClr"/></a:solidFill><a:solidFill><a:schemeClr val="phClr"/></a:solidFill><a:solidFill><a:schemeClr val="phClr"/></a:solidFill></a:bgFillStyleLst></a:fmtScheme>',
6356
+ "</a:themeElements>",
6357
+ "</a:theme>"
6358
+ ].join("");
6359
+ const presPropsXml = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?><p:presentationPr xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main"/>';
6360
+ const viewPropsXml = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?><p:viewPr xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main"/>';
6361
+ const tableStylesXml = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?><a:tblStyleLst xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" def="{5C22544A-7EE6-4342-B048-85BDC9FD1C3A}"/>';
6362
+ const docTitle = escapeXml2(unitData.name || "Converted Presentation");
6363
+ const coreXml = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?><cp:coreProperties xmlns:cp="http://schemas.openxmlformats.org/package/2006/metadata/core-properties" xmlns:dc="http://purl.org/dc/elements/1.1/"><dc:title>${docTitle}</dc:title><dc:creator>Univer PDFs</dc:creator></cp:coreProperties>`;
6364
+ const appXml = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?><Properties xmlns="http://schemas.openxmlformats.org/officeDocument/2006/extended-properties"><Application>Univer PDFs</Application><Slides>${slideCount}</Slides></Properties>`;
6365
+ const entries = [
6366
+ { path: "[Content_Types].xml", data: enc.encode(contentTypesXml) },
6367
+ { path: "_rels/.rels", data: enc.encode(rootRelsXml) },
6368
+ { path: "docProps/core.xml", data: enc.encode(coreXml) },
6369
+ { path: "docProps/app.xml", data: enc.encode(appXml) },
6370
+ { path: "ppt/presentation.xml", data: enc.encode(presentationXml) },
6371
+ { path: "ppt/_rels/presentation.xml.rels", data: enc.encode(presentationRelsXml) },
6372
+ { path: "ppt/presProps.xml", data: enc.encode(presPropsXml) },
6373
+ { path: "ppt/viewProps.xml", data: enc.encode(viewPropsXml) },
6374
+ { path: "ppt/tableStyles.xml", data: enc.encode(tableStylesXml) },
6375
+ { path: "ppt/slideMasters/slideMaster1.xml", data: enc.encode(slideMasterXml) },
6376
+ { path: "ppt/slideMasters/_rels/slideMaster1.xml.rels", data: enc.encode(slideMasterRelsXml) },
6377
+ { path: "ppt/slideLayouts/slideLayout1.xml", data: enc.encode(slideLayoutXml) },
6378
+ { path: "ppt/slideLayouts/_rels/slideLayout1.xml.rels", data: enc.encode(slideLayoutRelsXml) },
6379
+ { path: "ppt/theme/theme1.xml", data: enc.encode(themeXml) }
6380
+ ];
6381
+ slideXmlEntries.forEach((s, idx) => {
6382
+ entries.push({
6383
+ path: `ppt/slides/slide${idx + 1}.xml`,
6384
+ data: enc.encode(s.slideXml)
6385
+ });
6386
+ entries.push({
6387
+ path: `ppt/slides/_rels/slide${idx + 1}.xml.rels`,
6388
+ data: enc.encode(s.slideRelsXml)
6389
+ });
6390
+ });
6391
+ for (const media of mediaFiles) {
6392
+ entries.push({
6393
+ path: `ppt/media/${media.fileName}`,
6394
+ data: media.bytes
6395
+ });
6396
+ }
6397
+ return buildPptxZipArchive(entries);
6398
+ }
6399
+ async function convertPdfBytesToPptxBytes(pdfBytes, options) {
6400
+ const unit = await importPdfBytesToUnit(pdfBytes, {
6401
+ password: options?.password
6402
+ });
6403
+ return convertPdfUnitToPptxBytes(unit);
6404
+ }
6405
+
6406
+ // src/exporter/pdf-convert-and-compliance.ts
6407
+ function collectOrderedPageFragments(unit, pageId, pageIndex) {
6408
+ const suppressed = new Set(unit.editState.suppressedSourceIds ?? []);
6409
+ const layersById = new Map((unit.layers ?? []).map((l) => [l.id, l]));
6410
+ const rawSpans = unit.metadata?.nativeTextSpansByPage?.[pageId] ?? unit.editState.nativeTextSpansByPage?.[pageId] ?? [];
6411
+ const textFragments = rawSpans.filter((s) => !s.suppressed && !suppressed.has(s.id) && s.text.trim().length > 0).map((s) => ({
6412
+ text: s.text.trim(),
6413
+ left: s.left,
6414
+ top: s.top,
6415
+ width: s.width,
6416
+ height: s.height,
6417
+ fontSize: s.fontSize || 11,
6418
+ bold: (s.fontSize || 11) >= 14
6419
+ }));
6420
+ const explicitBlocks = [];
6421
+ const map = unit.editState.elementsByPage[pageId] ?? {};
6422
+ const order = unit.editState.elementOrderByPage[pageId] ?? Object.keys(map);
6423
+ for (const id of order) {
6424
+ const el = map[id];
6425
+ if (!el || el.hidden) continue;
6426
+ if (el.layerId) {
6427
+ const layer = layersById.get(el.layerId);
6428
+ if (layer && layer.visible === false && layer.printable === false) continue;
6429
+ }
6430
+ if (el.type === "text" /* TEXT */) {
6431
+ const txt = (el.content ?? "").trim();
6432
+ if (!txt) continue;
6433
+ const lines = txt.split("\n");
6434
+ const fs = el.style?.fontSize ?? 12;
6435
+ const lineH = fs * (el.style?.lineHeight ?? 1.35);
6436
+ lines.forEach((line, lIdx) => {
6437
+ if (!line.trim()) return;
6438
+ textFragments.push({
6439
+ text: line.trim(),
6440
+ left: el.transform.left,
6441
+ top: el.transform.top + lIdx * lineH,
6442
+ width: el.transform.width,
6443
+ height: lineH,
6444
+ fontSize: fs,
6445
+ bold: el.style?.fontWeight === "bold"
6446
+ });
6447
+ });
6448
+ } else if (el.type === "checkbox" /* CHECKBOX */) {
6449
+ textFragments.push({
6450
+ text: `${el.checked ? "[X]" : "[ ]"} ${el.label || el.name || ""}`.trim(),
6451
+ left: el.transform.left,
6452
+ top: el.transform.top,
6453
+ width: el.transform.width,
6454
+ height: el.transform.height,
6455
+ fontSize: el.style?.fontSize ?? 10.5,
6456
+ bold: false
6457
+ });
6458
+ } else if (el.type === "select" /* SELECT */ || el.type === "radioGroup" /* RADIO_GROUP */) {
6459
+ if (el.value) {
6460
+ textFragments.push({
6461
+ text: `${el.name ? `${el.name}: ` : ""}${el.value}`,
6462
+ left: el.transform.left,
6463
+ top: el.transform.top,
6464
+ width: el.transform.width,
6465
+ height: el.transform.height,
6466
+ fontSize: el.style?.fontSize ?? 10.5,
6467
+ bold: false
6468
+ });
6469
+ }
6470
+ } else if (el.type === "table" /* TABLE */) {
6471
+ const headers = el.columns.map((c) => c.header);
6472
+ const formattedRows = (el.rows ?? []).map(
6473
+ (r) => el.columns.map((col, ci) => formatPdfTableCell(r[ci], col))
6474
+ );
6475
+ explicitBlocks.push({
6476
+ type: "table",
6477
+ headers,
6478
+ rows: formattedRows,
6479
+ pageIndex,
6480
+ topPt: el.transform.top
6481
+ });
6482
+ } else if (el.type === "list" /* LIST */) {
6483
+ explicitBlocks.push({
6484
+ type: "list",
6485
+ ordered: el.listType === "ordered",
6486
+ items: [...el.items ?? []],
6487
+ pageIndex,
6488
+ topPt: el.transform.top
6489
+ });
6490
+ } else if (el.type === "image" /* IMAGE */) {
6491
+ explicitBlocks.push({
6492
+ type: "image",
6493
+ altText: el.altText || el.name || "Image",
6494
+ widthPt: el.transform.width,
6495
+ heightPt: el.transform.height,
6496
+ src: el.src,
6497
+ pageIndex,
6498
+ topPt: el.transform.top
6499
+ });
6500
+ }
6501
+ }
6502
+ return { textFragments, explicitBlocks };
6503
+ }
6504
+ function clusterFragmentsIntoLines(fragments) {
6505
+ if (fragments.length === 0) return [];
6506
+ const sorted = [...fragments].sort((a, b) => a.top - b.top || a.left - b.left);
6507
+ const rawLines = [];
6508
+ for (const frag of sorted) {
6509
+ const centerY = frag.top + frag.height / 2;
6510
+ const hit = rawLines.find((line) => {
6511
+ const lineRef = line[0];
6512
+ const lineCenterY = lineRef.top + lineRef.height / 2;
6513
+ const tol = Math.max(4.5, Math.min(frag.height, lineRef.height) * 0.5);
6514
+ return Math.abs(centerY - lineCenterY) <= tol;
6515
+ });
6516
+ if (hit) {
6517
+ hit.push(frag);
6518
+ } else {
6519
+ rawLines.push([frag]);
6520
+ }
6521
+ }
6522
+ return rawLines.map((items) => {
6523
+ items.sort((a, b) => a.left - b.left);
6524
+ const cells = [];
6525
+ for (const it of items) {
6526
+ const prev = cells[cells.length - 1];
6527
+ if (prev && it.left - prev.right <= 12) {
6528
+ prev.text = `${prev.text} ${it.text}`.trim();
6529
+ prev.right = Math.max(prev.right, it.left + it.width);
6530
+ } else {
6531
+ cells.push({
6532
+ left: it.left,
6533
+ right: it.left + it.width,
6534
+ text: it.text
6535
+ });
6536
+ }
6537
+ }
6538
+ return {
6539
+ topPt: Math.min(...items.map((x) => x.top)),
6540
+ bottomPt: Math.max(...items.map((x) => x.top + x.height)),
6541
+ fontSize: Math.max(...items.map((x) => x.fontSize)),
5243
6542
  bold: items.some((x) => x.bold),
5244
6543
  cells
5245
6544
  };
@@ -5450,7 +6749,7 @@ function exportPdfToDocxSnapshot(unit) {
5450
6749
  const sectionIndex = dataStream.length;
5451
6750
  dataStream += "\n";
5452
6751
  return {
5453
- id: `doc-${unit.id || generateRandomId5(6)}`,
6752
+ id: `doc-${unit.id || generateRandomId6(6)}`,
5454
6753
  title: word.title,
5455
6754
  body: {
5456
6755
  dataStream,
@@ -5506,7 +6805,7 @@ function exportPdfToWorkbookSnapshot(unit) {
5506
6805
  };
5507
6806
  });
5508
6807
  return {
5509
- id: `wb-${unit.id || generateRandomId5(6)}`,
6808
+ id: `wb-${unit.id || generateRandomId6(6)}`,
5510
6809
  name: converted.name,
5511
6810
  appVersion: "1.6.204",
5512
6811
  sheetOrder,
@@ -5721,13 +7020,13 @@ async function applyOcrToUnitPage(unit, pageIndex, mode, adapter) {
5721
7020
  widthMm: ptToMm(pSize.width),
5722
7021
  heightMm: ptToMm(pSize.height),
5723
7022
  sourceDataUri: unit.sourceDocumentRef?.dataUri,
5724
- snapshot: Tools4.deepClone(unit)
7023
+ snapshot: Tools5.deepClone(unit)
5725
7024
  });
5726
- const next = Tools4.deepClone(unit);
7025
+ const next = Tools5.deepClone(unit);
5727
7026
  if (!next.editState.elementsByPage[pageId]) next.editState.elementsByPage[pageId] = {};
5728
7027
  if (!next.editState.elementOrderByPage[pageId]) next.editState.elementOrderByPage[pageId] = [];
5729
7028
  if (mode === "searchable") {
5730
- const rawMap = Tools4.deepClone(
7029
+ const rawMap = Tools5.deepClone(
5731
7030
  next.metadata?.nativeTextSpansByPage ?? next.editState.nativeTextSpansByPage ?? {}
5732
7031
  );
5733
7032
  if (!rawMap[pageId]) rawMap[pageId] = [];
@@ -5735,7 +7034,7 @@ async function applyOcrToUnitPage(unit, pageIndex, mode, adapter) {
5735
7034
  if (!blk.text?.trim()) continue;
5736
7035
  const heightPt = Math.max(8, mmToPt(blk.heightMm || 5));
5737
7036
  const span = {
5738
- id: `ocr-span-${generateRandomId5(6)}`,
7037
+ id: `ocr-span-${generateRandomId6(6)}`,
5739
7038
  pageId,
5740
7039
  pageIndex,
5741
7040
  text: blk.text.trim(),
@@ -5749,15 +7048,15 @@ async function applyOcrToUnitPage(unit, pageIndex, mode, adapter) {
5749
7048
  };
5750
7049
  rawMap[pageId].push(span);
5751
7050
  }
5752
- next.editState.nativeTextSpansByPage = Tools4.deepClone(rawMap);
7051
+ next.editState.nativeTextSpansByPage = Tools5.deepClone(rawMap);
5753
7052
  next.metadata = {
5754
7053
  ...next.metadata ?? {},
5755
- nativeTextSpansByPage: Tools4.deepClone(rawMap)
7054
+ nativeTextSpansByPage: Tools5.deepClone(rawMap)
5756
7055
  };
5757
7056
  } else {
5758
7057
  for (const blk of blocks) {
5759
7058
  if (!blk.text?.trim()) continue;
5760
- const elId = `ocr-el-${generateRandomId5(6)}`;
7059
+ const elId = `ocr-el-${generateRandomId6(6)}`;
5761
7060
  const heightPt = Math.max(12, mmToPt(blk.heightMm || 6));
5762
7061
  const fontSize = Math.round(Math.max(8, Math.min(24, heightPt * 0.72)) * 10) / 10;
5763
7062
  next.editState.elementsByPage[pageId][elId] = {
@@ -5795,7 +7094,7 @@ function sanitizePdfUnit(unit, options) {
5795
7094
  const stripAuthorHistory = options?.stripAuthorHistory !== false;
5796
7095
  const stripScripts = options?.stripScripts !== false;
5797
7096
  const stripSampleData = Boolean(options?.stripSampleData);
5798
- const next = Tools4.deepClone(unit);
7097
+ const next = Tools5.deepClone(unit);
5799
7098
  if (stripAttachments) {
5800
7099
  delete next.attachments;
5801
7100
  }
@@ -5831,7 +7130,7 @@ function sanitizePdfUnit(unit, options) {
5831
7130
  for (const pid of Object.keys(spansObj)) {
5832
7131
  spansObj[pid] = (spansObj[pid] ?? []).filter((s) => !s.suppressed && !suppressedSet.has(s.id));
5833
7132
  }
5834
- next.editState.nativeTextSpansByPage = Tools4.deepClone(spansObj);
7133
+ next.editState.nativeTextSpansByPage = Tools5.deepClone(spansObj);
5835
7134
  }
5836
7135
  next.metadata = cleanMeta;
5837
7136
  for (const pid of next.document.pageOrder) {
@@ -5874,7 +7173,7 @@ function optimizePdfUnit(unit, options) {
5874
7173
  const dedup = options?.deduplicateResources !== false;
5875
7174
  const pruneRes = options?.pruneUnusedResources !== false;
5876
7175
  const prunePages = options?.pruneOrphanedPages !== false;
5877
- const next = Tools4.deepClone(unit);
7176
+ const next = Tools5.deepClone(unit);
5878
7177
  const validPageSet = new Set(next.document.pageOrder);
5879
7178
  if (prunePages) {
5880
7179
  for (const pid of Object.keys(next.document.pages)) {
@@ -5948,10 +7247,10 @@ function optimizePdfUnit(unit, options) {
5948
7247
  return next;
5949
7248
  }
5950
7249
  function applyRedactRegexOnUnit(unit, pattern, flags = "gi", overlayLabel = "[REDACTED]", fillColor = "#000000") {
5951
- const next = Tools4.deepClone(unit);
7250
+ const next = Tools5.deepClone(unit);
5952
7251
  const safeFlags = flags.includes("g") ? flags : `${flags}g`;
5953
7252
  const re = new RegExp(pattern, safeFlags);
5954
- const rawSpansMap = Tools4.deepClone(
7253
+ const rawSpansMap = Tools5.deepClone(
5955
7254
  next.metadata?.nativeTextSpansByPage ?? next.editState.nativeTextSpansByPage ?? {}
5956
7255
  );
5957
7256
  const suppressed = new Set(next.editState.suppressedSourceIds ?? []);
@@ -5964,7 +7263,7 @@ function applyRedactRegexOnUnit(unit, pattern, flags = "gi", overlayLabel = "[RE
5964
7263
  if (el.hidden || el.type !== "text" /* TEXT */) continue;
5965
7264
  if (re.test(el.content)) {
5966
7265
  re.lastIndex = 0;
5967
- const redId = `redact-${generateRandomId5(6)}`;
7266
+ const redId = `redact-${generateRandomId6(6)}`;
5968
7267
  pageMap[redId] = {
5969
7268
  id: redId,
5970
7269
  type: "redaction" /* REDACTION */,
@@ -5981,7 +7280,7 @@ function applyRedactRegexOnUnit(unit, pattern, flags = "gi", overlayLabel = "[RE
5981
7280
  if (span.suppressed || suppressed.has(span.id)) continue;
5982
7281
  if (re.test(span.text)) {
5983
7282
  re.lastIndex = 0;
5984
- const redId = `redact-${generateRandomId5(6)}`;
7283
+ const redId = `redact-${generateRandomId6(6)}`;
5985
7284
  pageMap[redId] = {
5986
7285
  id: redId,
5987
7286
  type: "redaction" /* REDACTION */,
@@ -6004,7 +7303,7 @@ function applyRedactRegexOnUnit(unit, pattern, flags = "gi", overlayLabel = "[RE
6004
7303
  return next;
6005
7304
  }
6006
7305
  function flattenFormsOnUnit(unit) {
6007
- const next = Tools4.deepClone(unit);
7306
+ const next = Tools5.deepClone(unit);
6008
7307
  for (const pid of next.document.pageOrder) {
6009
7308
  const map = next.editState.elementsByPage[pid] ?? {};
6010
7309
  for (const [id, el] of Object.entries(map)) {
@@ -6041,7 +7340,7 @@ async function runPdfBatchPipeline(files, actions, baseExportOptions) {
6041
7340
  for (const file of files) {
6042
7341
  let workingUnit;
6043
7342
  if (file.unit) {
6044
- workingUnit = Tools4.deepClone(file.unit);
7343
+ workingUnit = Tools5.deepClone(file.unit);
6045
7344
  } else if (file.pdfBytes) {
6046
7345
  workingUnit = await importAcroFormPdfToUnit(file.pdfBytes, { title: file.name });
6047
7346
  } else {
@@ -6149,26 +7448,26 @@ function bytesToBase64Pure(bytes) {
6149
7448
  return btoa(bin);
6150
7449
  }
6151
7450
  async function extractAttachmentsFromPdfBytes(pdfBytes) {
6152
- const doc = await PDFDocument3.load(pdfBytes, { ignoreEncryption: true });
6153
- const namesDict = doc.context.lookupMaybe(doc.catalog.get(PDFName3.of("Names")), PDFDict3);
7451
+ const doc = await PDFDocument4.load(pdfBytes, { ignoreEncryption: true });
7452
+ const namesDict = doc.context.lookupMaybe(doc.catalog.get(PDFName4.of("Names")), PDFDict4);
6154
7453
  if (!namesDict) return [];
6155
- const efTree = doc.context.lookupMaybe(namesDict.get(PDFName3.of("EmbeddedFiles")), PDFDict3);
7454
+ const efTree = doc.context.lookupMaybe(namesDict.get(PDFName4.of("EmbeddedFiles")), PDFDict4);
6156
7455
  if (!efTree) return [];
6157
7456
  const out = [];
6158
7457
  const collectFromNode = (node) => {
6159
- const namesArr = doc.context.lookupMaybe(node.get(PDFName3.of("Names")), PDFArray3);
7458
+ const namesArr = doc.context.lookupMaybe(node.get(PDFName4.of("Names")), PDFArray4);
6160
7459
  if (namesArr) {
6161
7460
  for (let i = 0; i + 1 < namesArr.size(); i += 2) {
6162
7461
  const keyObj = namesArr.get(i);
6163
- const fsDict = doc.context.lookupMaybe(namesArr.get(i + 1), PDFDict3);
7462
+ const fsDict = doc.context.lookupMaybe(namesArr.get(i + 1), PDFDict4);
6164
7463
  if (!fsDict) continue;
6165
- const ufObj = fsDict.get(PDFName3.of("UF")) ?? fsDict.get(PDFName3.of("F")) ?? keyObj;
6166
- const fileName = ufObj instanceof PDFHexString3 || ufObj instanceof PDFString3 ? ufObj.decodeText() : String(ufObj);
6167
- const descObj = fsDict.get(PDFName3.of("Desc"));
6168
- const description = descObj instanceof PDFHexString3 || descObj instanceof PDFString3 ? descObj.decodeText() : void 0;
6169
- const efDict = doc.context.lookupMaybe(fsDict.get(PDFName3.of("EF")), PDFDict3);
6170
- const streamEntry = efDict?.get(PDFName3.of("UF")) ?? efDict?.get(PDFName3.of("F"));
6171
- const resolvedStream = streamEntry instanceof PDFRef3 ? doc.context.lookup(streamEntry) : streamEntry;
7464
+ const ufObj = fsDict.get(PDFName4.of("UF")) ?? fsDict.get(PDFName4.of("F")) ?? keyObj;
7465
+ const fileName = ufObj instanceof PDFHexString4 || ufObj instanceof PDFString4 ? ufObj.decodeText() : String(ufObj);
7466
+ const descObj = fsDict.get(PDFName4.of("Desc"));
7467
+ const description = descObj instanceof PDFHexString4 || descObj instanceof PDFString4 ? descObj.decodeText() : void 0;
7468
+ const efDict = doc.context.lookupMaybe(fsDict.get(PDFName4.of("EF")), PDFDict4);
7469
+ const streamEntry = efDict?.get(PDFName4.of("UF")) ?? efDict?.get(PDFName4.of("F"));
7470
+ const resolvedStream = streamEntry instanceof PDFRef4 ? doc.context.lookup(streamEntry) : streamEntry;
6172
7471
  if (!(resolvedStream instanceof PDFRawStream2)) continue;
6173
7472
  const rawStream = resolvedStream;
6174
7473
  let decoded;
@@ -6178,10 +7477,10 @@ async function extractAttachmentsFromPdfBytes(pdfBytes) {
6178
7477
  } catch {
6179
7478
  decoded = rawStream.contents;
6180
7479
  }
6181
- const subObj = rawStream.dict.get(PDFName3.of("Subtype"));
6182
- const mimeType = subObj instanceof PDFName3 ? subObj.decodeText().replace(/#2F/gi, "/") : "application/octet-stream";
7480
+ const subObj = rawStream.dict.get(PDFName4.of("Subtype"));
7481
+ const mimeType = subObj instanceof PDFName4 ? subObj.decodeText().replace(/#2F/gi, "/") : "application/octet-stream";
6183
7482
  out.push({
6184
- id: `att-${generateRandomId5(6)}`,
7483
+ id: `att-${generateRandomId6(6)}`,
6185
7484
  fileName,
6186
7485
  mimeType,
6187
7486
  dataBase64: bytesToBase64Pure(decoded),
@@ -6189,10 +7488,10 @@ async function extractAttachmentsFromPdfBytes(pdfBytes) {
6189
7488
  });
6190
7489
  }
6191
7490
  }
6192
- const kidsArr = doc.context.lookupMaybe(node.get(PDFName3.of("Kids")), PDFArray3);
7491
+ const kidsArr = doc.context.lookupMaybe(node.get(PDFName4.of("Kids")), PDFArray4);
6193
7492
  if (kidsArr) {
6194
7493
  for (let k = 0; k < kidsArr.size(); k++) {
6195
- const child = doc.context.lookupMaybe(kidsArr.get(k), PDFDict3);
7494
+ const child = doc.context.lookupMaybe(kidsArr.get(k), PDFDict4);
6196
7495
  if (child) collectFromNode(child);
6197
7496
  }
6198
7497
  }
@@ -6230,7 +7529,7 @@ function signPdfUnitWithDigest(unit, signerInfo) {
6230
7529
  if (!signerName) {
6231
7530
  throw new Error("[UniverPdfs] signPdfUnitWithDigest requires a non-empty signerName.");
6232
7531
  }
6233
- const next = Tools4.deepClone(unit);
7532
+ const next = Tools5.deepClone(unit);
6234
7533
  const signedAt = signerInfo.signedAt || (/* @__PURE__ */ new Date()).toISOString();
6235
7534
  const contentDigestHex = computeCanonicalUnitContentDigestHex(next);
6236
7535
  const partialEnv = {
@@ -6251,10 +7550,10 @@ function signPdfUnitWithDigest(unit, signerInfo) {
6251
7550
  ...partialEnv,
6252
7551
  envelopeDigestHex: computeSignatureEnvelopeDigestHex(partialEnv)
6253
7552
  };
6254
- next.signatureEnvelope = Tools4.deepClone(envelope);
7553
+ next.signatureEnvelope = Tools5.deepClone(envelope);
6255
7554
  next.metadata = {
6256
7555
  ...next.metadata ?? {},
6257
- signatureEnvelope: Tools4.deepClone(envelope)
7556
+ signatureEnvelope: Tools5.deepClone(envelope)
6258
7557
  };
6259
7558
  next.rev = (next.rev || 1) + 1;
6260
7559
  return next;
@@ -6323,7 +7622,7 @@ function matchPaperPresetMm(wMm, hMm, tolMm = 1.5) {
6323
7622
  }
6324
7623
  async function inspectPdfBytePageSizes(pdfBytes, options) {
6325
7624
  const loadOpts = options?.password ? { password: options.password } : { ignoreEncryption: true };
6326
- const doc = await PDFDocument3.load(pdfBytes, loadOpts);
7625
+ const doc = await PDFDocument4.load(pdfBytes, loadOpts);
6327
7626
  const pages = doc.getPages();
6328
7627
  return pages.map((page, pageIndex) => {
6329
7628
  const sz = page.getSize();
@@ -6551,7 +7850,7 @@ function isPngSignature(bytes) {
6551
7850
  return bytes.length >= 8 && bytes[0] === 137 && bytes[1] === 80 && bytes[2] === 78 && bytes[3] === 71;
6552
7851
  }
6553
7852
  async function convertImagesToPdfBytes(images, options) {
6554
- const pdfDoc = await PDFDocument3.create();
7853
+ const pdfDoc = await PDFDocument4.create();
6555
7854
  const sizeSpec = resolveConverterPageSizePt(options?.pageSize ?? "A4");
6556
7855
  const marginPt = mmToPt(Math.max(0, options?.marginMm ?? 0));
6557
7856
  if (!images.length) {
@@ -6994,7 +8293,7 @@ async function convertMarkdownToPdfBytes(markdown, options) {
6994
8293
  }
6995
8294
 
6996
8295
  // src/exporter/pdf-fidelity-samples.ts
6997
- import { Tools as Tools5 } from "@univerjs/core";
8296
+ import { Tools as Tools6 } from "@univerjs/core";
6998
8297
  function buildA4Snapshot(id, name, elements, margins = [40, 40, 40, 40]) {
6999
8298
  const base = createDefaultPdfUnitData({ id, name });
7000
8299
  const pageId = "page-1";
@@ -7463,7 +8762,7 @@ function createPdfBrowserFidelitySamples() {
7463
8762
  }
7464
8763
  }
7465
8764
  ]);
7466
- const s6MissingGlyphs = Tools5.deepClone(s1ShortCjk);
8765
+ const s6MissingGlyphs = Tools6.deepClone(s1ShortCjk);
7467
8766
  s6MissingGlyphs.id = "s6-missing-glyphs";
7468
8767
  s6MissingGlyphs.name = "S6 \u7F3A\u5B57\u4E0E\u5B57\u4F53\u5F02\u5E38\u8BCA\u65AD";
7469
8768
  s6MissingGlyphs.editState.elementsByPage["page-1"]["s6-missing-note"] = {
@@ -7482,7 +8781,7 @@ function createPdfBrowserFidelitySamples() {
7482
8781
  }
7483
8782
  };
7484
8783
  s6MissingGlyphs.editState.elementOrderByPage["page-1"].push("s6-missing-note");
7485
- const s7DefaultNoFont = Tools5.deepClone(s1ShortCjk);
8784
+ const s7DefaultNoFont = Tools6.deepClone(s1ShortCjk);
7486
8785
  s7DefaultNoFont.id = "s7-default-no-font";
7487
8786
  s7DefaultNoFont.name = "S7 \u9ED8\u8BA4\u672A\u4F20\u5B57\u4F53\u5149\u6805\u517C\u5BB9\u6A21\u5F0F";
7488
8787
  return {
@@ -7727,249 +9026,6 @@ function createPdfBrowserFidelityExpectations() {
7727
9026
  }
7728
9027
  var PDF_S1_S7_FIDELITY_EXPECTATIONS = Object.freeze(createPdfBrowserFidelityExpectations());
7729
9028
 
7730
- // src/exporter/pdf-importer.ts
7731
- import { generateRandomId as generateRandomId6, Tools as Tools6 } from "@univerjs/core";
7732
- import {
7733
- PDFArray as PDFArray4,
7734
- PDFDict as PDFDict4,
7735
- PDFDocument as PDFDocument4,
7736
- PDFHexString as PDFHexString4,
7737
- PDFName as PDFName4,
7738
- PDFNumber as PDFNumber2,
7739
- PDFRef as PDFRef4,
7740
- PDFString as PDFString4
7741
- } from "pdf-lib";
7742
- function hasPdfMagicHeader(bytes) {
7743
- if (!bytes || bytes.byteLength < 5) return false;
7744
- const maxScan = Math.min(bytes.byteLength - 5, 1024);
7745
- for (let i = 0; i <= maxScan; i++) {
7746
- if (bytes[i] === 37 && bytes[i + 1] === 80 && bytes[i + 2] === 68 && bytes[i + 3] === 70 && bytes[i + 4] === 45) {
7747
- return true;
7748
- }
7749
- }
7750
- return false;
7751
- }
7752
- function decodePdfTextValue(obj) {
7753
- if (obj instanceof PDFHexString4 || obj instanceof PDFString4 || obj instanceof PDFName4) {
7754
- return obj.decodeText();
7755
- }
7756
- return "";
7757
- }
7758
- function extractOutlinesBookmarksFromDoc(doc) {
7759
- const outlinesRef = doc.catalog.get(PDFName4.of("Outlines"));
7760
- const outlinesDict = doc.context.lookupMaybe(outlinesRef, PDFDict4);
7761
- if (!outlinesDict) return [];
7762
- const pages = doc.getPages();
7763
- const pageRefKeyToIdx = /* @__PURE__ */ new Map();
7764
- pages.forEach((p, idx) => {
7765
- pageRefKeyToIdx.set(`${p.ref.objectNumber}:${p.ref.generationNumber}`, idx);
7766
- });
7767
- const resolveDest = (itemDict) => {
7768
- let destObj = itemDict.get(PDFName4.of("Dest"));
7769
- if (!destObj) {
7770
- const actionDict = doc.context.lookupMaybe(itemDict.get(PDFName4.of("A")), PDFDict4);
7771
- if (actionDict) {
7772
- destObj = actionDict.get(PDFName4.of("D"));
7773
- }
7774
- }
7775
- const destArr = doc.context.lookupMaybe(destObj, PDFArray4);
7776
- if (!destArr || destArr.size() === 0) return { pageIndex: 0 };
7777
- const pRef = destArr.get(0);
7778
- let pageIndex = 0;
7779
- if (pRef instanceof PDFRef4) {
7780
- pageIndex = pageRefKeyToIdx.get(`${pRef.objectNumber}:${pRef.generationNumber}`) ?? 0;
7781
- } else if (pRef instanceof PDFNumber2) {
7782
- pageIndex = Math.max(0, Math.min(pages.length - 1, Math.floor(pRef.asNumber())));
7783
- }
7784
- let topPt;
7785
- if (destArr.size() >= 4) {
7786
- const yObj = destArr.get(3);
7787
- if (yObj instanceof PDFNumber2 && pages[pageIndex]) {
7788
- const pageHeight = pages[pageIndex].getHeight();
7789
- topPt = Math.round(Math.max(0, pageHeight - yObj.asNumber()) * 100) / 100;
7790
- }
7791
- }
7792
- return { pageIndex, topPt };
7793
- };
7794
- const visited = /* @__PURE__ */ new Set();
7795
- const walkLevel = (firstRef) => {
7796
- const list = [];
7797
- let cur = firstRef;
7798
- while (cur) {
7799
- if (cur instanceof PDFRef4) {
7800
- const key = `${cur.objectNumber}:${cur.generationNumber}`;
7801
- if (visited.has(key)) break;
7802
- visited.add(key);
7803
- }
7804
- const itemDict = cur instanceof PDFDict4 ? cur : doc.context.lookupMaybe(cur, PDFDict4);
7805
- if (!itemDict) break;
7806
- const title = decodePdfTextValue(itemDict.get(PDFName4.of("Title"))) || "Bookmark";
7807
- const { pageIndex, topPt } = resolveDest(itemDict);
7808
- const childFirst = itemDict.get(PDFName4.of("First"));
7809
- const children = childFirst ? walkLevel(childFirst) : [];
7810
- const bm = {
7811
- id: `bm-${generateRandomId6(6)}`,
7812
- title,
7813
- pageIndex,
7814
- ...topPt !== void 0 ? { topOffsetPt: topPt, topPt } : {},
7815
- ...children.length > 0 ? { children } : {}
7816
- };
7817
- list.push(bm);
7818
- const nextRef = itemDict.get(PDFName4.of("Next"));
7819
- if (!nextRef || nextRef === cur) break;
7820
- cur = nextRef;
7821
- }
7822
- return list;
7823
- };
7824
- return walkLevel(outlinesDict.get(PDFName4.of("First")));
7825
- }
7826
- function extractLayersFromDoc(doc) {
7827
- const ocProps = doc.context.lookupMaybe(doc.catalog.get(PDFName4.of("OCProperties")), PDFDict4);
7828
- if (!ocProps) return [];
7829
- const ocgsArr = doc.context.lookupMaybe(ocProps.get(PDFName4.of("OCGs")), PDFArray4);
7830
- if (!ocgsArr || ocgsArr.size() === 0) return [];
7831
- const defaultCfg = doc.context.lookupMaybe(ocProps.get(PDFName4.of("D")), PDFDict4);
7832
- const offRefKeys = /* @__PURE__ */ new Set();
7833
- const lockedRefKeys = /* @__PURE__ */ new Set();
7834
- if (defaultCfg) {
7835
- const offArr = doc.context.lookupMaybe(defaultCfg.get(PDFName4.of("OFF")), PDFArray4);
7836
- if (offArr) {
7837
- for (let i = 0; i < offArr.size(); i++) {
7838
- const r = offArr.get(i);
7839
- if (r instanceof PDFRef4) offRefKeys.add(`${r.objectNumber}:${r.generationNumber}`);
7840
- }
7841
- }
7842
- const lockedArr = doc.context.lookupMaybe(defaultCfg.get(PDFName4.of("Locked")), PDFArray4);
7843
- if (lockedArr) {
7844
- for (let i = 0; i < lockedArr.size(); i++) {
7845
- const r = lockedArr.get(i);
7846
- if (r instanceof PDFRef4) lockedRefKeys.add(`${r.objectNumber}:${r.generationNumber}`);
7847
- }
7848
- }
7849
- }
7850
- const out = [];
7851
- for (let i = 0; i < ocgsArr.size(); i++) {
7852
- const entry = ocgsArr.get(i);
7853
- const key = entry instanceof PDFRef4 ? `${entry.objectNumber}:${entry.generationNumber}` : "";
7854
- const dict = entry instanceof PDFDict4 ? entry : doc.context.lookupMaybe(entry, PDFDict4);
7855
- if (!dict) continue;
7856
- const name = decodePdfTextValue(dict.get(PDFName4.of("Name"))) || `Layer ${i + 1}`;
7857
- let printable = true;
7858
- const usage = doc.context.lookupMaybe(dict.get(PDFName4.of("Usage")), PDFDict4);
7859
- if (usage) {
7860
- const printDict = doc.context.lookupMaybe(usage.get(PDFName4.of("Print")), PDFDict4);
7861
- if (printDict && decodePdfTextValue(printDict.get(PDFName4.of("PrintState"))) === "OFF") {
7862
- printable = false;
7863
- }
7864
- }
7865
- out.push({
7866
- id: `layer-${generateRandomId6(6)}`,
7867
- name,
7868
- visible: key ? !offRefKeys.has(key) : true,
7869
- locked: key ? lockedRefKeys.has(key) : false,
7870
- printable
7871
- });
7872
- }
7873
- return out;
7874
- }
7875
- async function importPdfBytesToUnit(pdfBytes, options) {
7876
- if (!hasPdfMagicHeader(pdfBytes)) {
7877
- throw new Error("Invalid PDF binary: missing %PDF- header signature.");
7878
- }
7879
- const encryptionInspection = inspectPdfEncryption(pdfBytes);
7880
- const decryptedBytes = await verifyAndDecryptPdfBytes(pdfBytes, options?.password);
7881
- const unitTitle = options?.name ?? options?.title;
7882
- const unit = await importAcroFormPdfToUnit(decryptedBytes, {
7883
- unitId: options?.unitId,
7884
- title: unitTitle
7885
- });
7886
- if (options?.fileName && unit.sourceDocumentRef) {
7887
- unit.sourceDocumentRef.fileName = options.fileName;
7888
- }
7889
- try {
7890
- const doc = await PDFDocument4.load(decryptedBytes, { updateMetadata: false });
7891
- const parsedBookmarks = extractOutlinesBookmarksFromDoc(doc);
7892
- if (parsedBookmarks.length > 0) {
7893
- unit.bookmarks = Tools6.deepClone(parsedBookmarks);
7894
- unit.metadata = {
7895
- ...unit.metadata ?? {},
7896
- bookmarks: Tools6.deepClone(parsedBookmarks)
7897
- };
7898
- }
7899
- const parsedLayers = extractLayersFromDoc(doc);
7900
- if (parsedLayers.length > 0) {
7901
- unit.layers = Tools6.deepClone(parsedLayers);
7902
- }
7903
- if (unitTitle === void 0) {
7904
- const docTitle = doc.getTitle();
7905
- if (docTitle) {
7906
- unit.name = docTitle;
7907
- } else if (options?.fileName) {
7908
- unit.name = options.fileName.replace(/\.pdf$/i, "");
7909
- }
7910
- }
7911
- } catch {
7912
- }
7913
- if (encryptionInspection.encrypted) {
7914
- unit.metadata = {
7915
- ...unit.metadata ?? {},
7916
- importedEncryptionInfo: {
7917
- encrypted: true,
7918
- requiresOpenPassword: encryptionInspection.requiresOpenPassword,
7919
- keyLength: encryptionInspection.keyLength,
7920
- permissions: { ...encryptionInspection.permissions }
7921
- }
7922
- };
7923
- }
7924
- if (options?.promoteNativeTextToElements) {
7925
- const spansByPage = unit.editState.nativeTextSpansByPage ?? {};
7926
- for (const pageId of unit.document.pageOrder) {
7927
- const pageSpans = spansByPage[pageId] ?? [];
7928
- if (!unit.editState.elementsByPage[pageId]) {
7929
- unit.editState.elementsByPage[pageId] = {};
7930
- }
7931
- if (!unit.editState.elementOrderByPage[pageId]) {
7932
- unit.editState.elementOrderByPage[pageId] = [];
7933
- }
7934
- for (const span of pageSpans) {
7935
- if (span.suppressed) continue;
7936
- span.suppressed = true;
7937
- const elId = `el-${generateRandomId6(6)}`;
7938
- const textEl = {
7939
- id: elId,
7940
- type: "text" /* TEXT */,
7941
- name: "Imported Text",
7942
- content: span.text,
7943
- metadata: { promotedFromNativeSpanId: span.id },
7944
- transform: {
7945
- left: span.left,
7946
- top: span.top,
7947
- width: span.width,
7948
- height: span.height,
7949
- angle: 0
7950
- },
7951
- style: {
7952
- fontFamily: "Inter, PingFang SC, Microsoft YaHei, sans-serif",
7953
- fontSize: span.fontSize,
7954
- fontWeight: "normal",
7955
- color: "#1B1C1F",
7956
- textAlign: "left",
7957
- verticalAlign: "middle",
7958
- lineHeight: 1.2,
7959
- padding: 0
7960
- }
7961
- };
7962
- unit.editState.elementsByPage[pageId][elId] = textEl;
7963
- unit.editState.elementOrderByPage[pageId].push(elId);
7964
- }
7965
- }
7966
- if (unit.metadata?.nativeTextSpansByPage) {
7967
- unit.metadata.nativeTextSpansByPage = Tools6.deepClone(spansByPage);
7968
- }
7969
- }
7970
- return unit;
7971
- }
7972
-
7973
9029
  // src/plugin.ts
7974
9030
  import {
7975
9031
  ICommandService as ICommandService2,
@@ -9238,6 +10294,9 @@ var UniverPdfsPlugin = class extends Plugin {
9238
10294
  UpdatePdfLayerCommand,
9239
10295
  RemovePdfLayerCommand,
9240
10296
  AssignPdfElementLayerCommand,
10297
+ AddPdfAnnotationReplyCommand,
10298
+ DeletePdfAnnotationReplyCommand,
10299
+ SetPdfAnnotationReviewStatusCommand,
9241
10300
  ReplacePdfSnapshotCommand,
9242
10301
  SavePdfVersionCommand,
9243
10302
  RestorePdfVersionCommand
@@ -9255,6 +10314,7 @@ UniverPdfsPlugin = __decorateClass([
9255
10314
  export {
9256
10315
  ASPECT_RATIO_LOCKED_BARCODE_TYPES,
9257
10316
  Absolute,
10317
+ AddPdfAnnotationReplyCommand,
9258
10318
  AddPdfElementCommand,
9259
10319
  AddPdfElementMutation,
9260
10320
  AddPdfLayerCommand,
@@ -9270,6 +10330,7 @@ export {
9270
10330
  DEFAULT_PDF_CJK_FONT_FILES,
9271
10331
  DEFAULT_PDF_CJK_FONT_PACKAGE,
9272
10332
  DEFAULT_PDF_CJK_FONT_VERSION,
10333
+ DeletePdfAnnotationReplyCommand,
9273
10334
  DeleteSelectedPdfElementsCommand,
9274
10335
  DistributeSelectedPdfElementsCommand,
9275
10336
  Document,
@@ -9293,7 +10354,10 @@ export {
9293
10354
  PDF_PAGE_PRESETS,
9294
10355
  PDF_PASSWORD_PADDING,
9295
10356
  PDF_S1_S7_FIDELITY_EXPECTATIONS,
10357
+ PDF_STANDARD_STAMP_PRESETS,
10358
+ PDF_STANDARD_STAMP_PRESET_MAP,
9296
10359
  PDF_TABLE_THEME_PRESETS,
10360
+ PPTX_EMU_PER_PT,
9297
10361
  PT_PER_MM,
9298
10362
  Page,
9299
10363
  PageBreak,
@@ -9328,6 +10392,7 @@ export {
9328
10392
  RotatePdfPageCommand,
9329
10393
  Row,
9330
10394
  SavePdfVersionCommand,
10395
+ SetPdfAnnotationReviewStatusCommand,
9331
10396
  SetPdfAttachmentsCommand,
9332
10397
  SetPdfBatesConfigCommand,
9333
10398
  SetPdfBookmarksCommand,
@@ -9360,6 +10425,7 @@ export {
9360
10425
  buildMinimalTestTrueTypeFont,
9361
10426
  buildObjectEncryptionKey,
9362
10427
  buildOverlayImportCandidateSnapshot,
10428
+ buildPdfApprovalStampSvg,
9363
10429
  buildPdfTemplateFromOcrFields,
9364
10430
  bytesToHex,
9365
10431
  calculatePdfTableRowCapacity,
@@ -9394,13 +10460,17 @@ export {
9394
10460
  convertMarkdownToPdfUnit,
9395
10461
  convertPdfBytesToCsv,
9396
10462
  convertPdfBytesToDocxBytes,
10463
+ convertPdfBytesToPptxBytes,
9397
10464
  convertPdfToSheetStructure,
9398
10465
  convertPdfToWordStructure,
9399
10466
  convertPdfUnitToCsv,
10467
+ convertPdfUnitToPptxBytes,
9400
10468
  createDefaultElement,
9401
10469
  createDefaultPdfUnitData,
9402
10470
  createHttpSilentPrintAdapter,
9403
10471
  createPdfAbortError,
10472
+ createPdfApprovalStampElement,
10473
+ createPdfApprovalStampSvgElement,
9404
10474
  createPdfBrowserFidelityExpectations,
9405
10475
  createPdfBrowserFidelitySamples,
9406
10476
  createPdfCjkFontSources,
@@ -9452,15 +10522,18 @@ export {
9452
10522
  extractJsxTextContent,
9453
10523
  extractNativeTextSpansFromPdfBytes,
9454
10524
  extractPdfFormValues,
10525
+ extractSvgTextDescriptors,
9455
10526
  fillPdfFormValues,
9456
10527
  flattenJsxChildrenToNodes,
9457
10528
  formatBatesNumber,
9458
10529
  formatGs1HumanReadable,
9459
10530
  formatPdfDateTimeValue,
10531
+ formatPdfPageIndicesLabel,
9460
10532
  formatPdfTableCell,
9461
10533
  fromPdfmeTemplate,
9462
10534
  generatePdfTemplateByPrompt,
9463
10535
  getDefaultDateTimeFormat,
10536
+ getPdfStandardStampPreset,
9464
10537
  getRegisteredOcrAdapter,
9465
10538
  getTrueTypeMappedCodePoints,
9466
10539
  hexToBytes,
@@ -9505,10 +10578,12 @@ export {
9505
10578
  parsePdfColorWithAlpha,
9506
10579
  parsePdfContentStreamTextOps,
9507
10580
  parsePdfPageRange,
10581
+ parsePdfPageRangeSpec,
9508
10582
  parseSafeKeyValueRecord,
9509
10583
  parseSvgToVectorCommands,
9510
10584
  parseSvgTransformAttr,
9511
10585
  ptToMm,
10586
+ ptToPptxEmu,
9512
10587
  rc4Bytes,
9513
10588
  readJpegExifOrientation,
9514
10589
  recalculatePdfFormFields,
@@ -9534,6 +10609,7 @@ export {
9534
10609
  resolveMultiVariableText,
9535
10610
  resolvePaddingMm,
9536
10611
  resolvePageSizeMm,
10612
+ resolvePdfCropBoxPt,
9537
10613
  resolvePolygonNormalizedPoints,
9538
10614
  resolveTemplateString,
9539
10615
  rgbToCmyk,
@@ -9549,6 +10625,8 @@ export {
9549
10625
  exportSignedPdfWithAuditSeal as signPdfWithAuditDigest,
9550
10626
  smoothSignatureStrokeQuadratic,
9551
10627
  splitPdfBytes,
10628
+ splitPdfBytesByRanges,
10629
+ splitPdfUnitByRanges,
9552
10630
  stripPdfPageNativeTextInRects,
9553
10631
  subsetTrueTypeFont,
9554
10632
  svgToDataUri,