@yudaocode/univer-pdfs 0.0.0-stage → 1.6.204

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.
@@ -0,0 +1,3607 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var __decorateClass = (decorators, target, key, kind) => {
20
+ var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
21
+ for (var i = decorators.length - 1, decorator; i >= 0; i--)
22
+ if (decorator = decorators[i])
23
+ result = (kind ? decorator(target, key, result) : decorator(result)) || result;
24
+ if (kind && result) __defProp(target, key, result);
25
+ return result;
26
+ };
27
+ var __decorateParam = (index, decorator) => (target, key) => decorator(target, key, index);
28
+
29
+ // src/facade/index.ts
30
+ var facade_exports = {};
31
+ __export(facade_exports, {
32
+ FEnumPdfsMixin: () => FEnumPdfsMixin,
33
+ FEventNamePdfsMixin: () => FEventNamePdfsMixin,
34
+ FPdf: () => FPdf,
35
+ FPdfAnnotation: () => FPdfAnnotation,
36
+ FPdfDivider: () => FPdfDivider,
37
+ FPdfDocument: () => FPdf,
38
+ FPdfImage: () => FPdfImage,
39
+ FPdfImageBuilder: () => FPdfImageBuilder,
40
+ FPdfList: () => FPdfList,
41
+ FPdfPage: () => FPdfPage,
42
+ FPdfPageElement: () => FPdfPageElement,
43
+ FPdfParagraph: () => FPdfParagraph,
44
+ FPdfTable: () => FPdfTable,
45
+ FPdfTableCell: () => FPdfTableCell,
46
+ FPdfTextBox: () => FPdfTextBox,
47
+ FPdfTextSpan: () => FPdfTextSpan,
48
+ FUniverPdfsMixin: () => FUniverPdfsMixin,
49
+ wrapPdfElementFacade: () => wrapPdfElementFacade
50
+ });
51
+ module.exports = __toCommonJS(facade_exports);
52
+
53
+ // src/facade/f-enum.ts
54
+ var import_facade = require("@univerjs/core/facade");
55
+ var import_univer_pdfs = require("@yudaocode/univer-pdfs");
56
+ var FEnumPdfsMixin = class {
57
+ get PdfElementType() {
58
+ return import_univer_pdfs.PdfElementType;
59
+ }
60
+ get PdfAnnotationType() {
61
+ return import_univer_pdfs.PdfAnnotationType;
62
+ }
63
+ get PdfListKind() {
64
+ return import_univer_pdfs.PdfListKind;
65
+ }
66
+ get PdfListPresetId() {
67
+ return import_univer_pdfs.PdfListPresetId;
68
+ }
69
+ get PdfTextAnchor() {
70
+ return import_univer_pdfs.PdfTextAnchor;
71
+ }
72
+ get PdfTableCellVerticalAlign() {
73
+ return import_univer_pdfs.PdfTableCellVerticalAlign;
74
+ }
75
+ get PdfTableBorderStyle() {
76
+ return import_univer_pdfs.PdfTableBorderStyle;
77
+ }
78
+ get PdfImageSourceType() {
79
+ return import_univer_pdfs.PdfImageSourceType;
80
+ }
81
+ };
82
+ import_facade.FEnum.extend(FEnumPdfsMixin);
83
+ var cachedEnumSingleton = import_facade.FEnum._instance;
84
+ if (cachedEnumSingleton) {
85
+ cachedEnumSingleton.PdfElementType = import_univer_pdfs.PdfElementType;
86
+ cachedEnumSingleton.PdfAnnotationType = import_univer_pdfs.PdfAnnotationType;
87
+ cachedEnumSingleton.PdfListKind = import_univer_pdfs.PdfListKind;
88
+ cachedEnumSingleton.PdfListPresetId = import_univer_pdfs.PdfListPresetId;
89
+ cachedEnumSingleton.PdfTextAnchor = import_univer_pdfs.PdfTextAnchor;
90
+ cachedEnumSingleton.PdfTableCellVerticalAlign = import_univer_pdfs.PdfTableCellVerticalAlign;
91
+ cachedEnumSingleton.PdfTableBorderStyle = import_univer_pdfs.PdfTableBorderStyle;
92
+ cachedEnumSingleton.PdfImageSourceType = import_univer_pdfs.PdfImageSourceType;
93
+ }
94
+
95
+ // src/facade/f-event.ts
96
+ var import_facade2 = require("@univerjs/core/facade");
97
+ var FEventNamePdfsMixin = class {
98
+ get PdfLoaded() {
99
+ return "PdfLoaded";
100
+ }
101
+ get PdfDisposed() {
102
+ return "PdfDisposed";
103
+ }
104
+ get PdfPageChanged() {
105
+ return "PdfPageChanged";
106
+ }
107
+ get PdfElementSelected() {
108
+ return "PdfElementSelected";
109
+ }
110
+ get PdfFormFieldChanged() {
111
+ return "PdfFormFieldChanged";
112
+ }
113
+ get BeforePdfExport() {
114
+ return "BeforePdfExport";
115
+ }
116
+ get PdfExported() {
117
+ return "PdfExported";
118
+ }
119
+ get BeforePdfPrint() {
120
+ return "BeforePdfPrint";
121
+ }
122
+ };
123
+ import_facade2.FEventName.extend(FEventNamePdfsMixin);
124
+ var cachedEventNameSingleton = import_facade2.FEventName._instance;
125
+ if (cachedEventNameSingleton) {
126
+ cachedEventNameSingleton.PdfLoaded = "PdfLoaded";
127
+ cachedEventNameSingleton.PdfDisposed = "PdfDisposed";
128
+ cachedEventNameSingleton.PdfPageChanged = "PdfPageChanged";
129
+ cachedEventNameSingleton.PdfElementSelected = "PdfElementSelected";
130
+ cachedEventNameSingleton.PdfFormFieldChanged = "PdfFormFieldChanged";
131
+ cachedEventNameSingleton.BeforePdfExport = "BeforePdfExport";
132
+ cachedEventNameSingleton.PdfExported = "PdfExported";
133
+ cachedEventNameSingleton.BeforePdfPrint = "BeforePdfPrint";
134
+ }
135
+
136
+ // src/facade/f-pdf.ts
137
+ var import_core3 = require("@univerjs/core");
138
+ var import_pdf_lib = require("pdf-lib");
139
+ var import_univer_pdfs4 = require("@yudaocode/univer-pdfs");
140
+
141
+ // src/facade/f-pdf-page.ts
142
+ var import_core2 = require("@univerjs/core");
143
+ var import_univer_pdfs3 = require("@yudaocode/univer-pdfs");
144
+
145
+ // src/facade/f-pdf-elements.ts
146
+ var import_core = require("@univerjs/core");
147
+ var import_univer_pdfs2 = require("@yudaocode/univer-pdfs");
148
+ function encodeUint8ToBase64(bytes) {
149
+ if (typeof Buffer !== "undefined") {
150
+ return Buffer.from(bytes).toString("base64");
151
+ }
152
+ let bin = "";
153
+ const chunk = 32768;
154
+ for (let i = 0; i < bytes.length; i += chunk) {
155
+ bin += String.fromCharCode(...bytes.subarray(i, i + chunk));
156
+ }
157
+ return btoa(bin);
158
+ }
159
+ var FPdfPageElement = class {
160
+ constructor(_pdfModel, _commandService, _pageId, _elementId) {
161
+ this._pdfModel = _pdfModel;
162
+ this._commandService = _commandService;
163
+ this._pageId = _pageId;
164
+ this._elementId = _elementId;
165
+ }
166
+ getId() {
167
+ return this._elementId;
168
+ }
169
+ getPageId() {
170
+ return this._pageId;
171
+ }
172
+ /** @internal */
173
+ _getInternalPdfModel() {
174
+ return this._pdfModel;
175
+ }
176
+ /** @internal */
177
+ _getInternalCommandService() {
178
+ return this._commandService;
179
+ }
180
+ _readRaw() {
181
+ const el = this._pdfModel.getElementsByPage(this._pageId)[this._elementId];
182
+ if (!el) {
183
+ throw new Error(
184
+ `[UniverPdfs] Element "${this._elementId}" no longer exists on page "${this._pageId}".`
185
+ );
186
+ }
187
+ return el;
188
+ }
189
+ exists() {
190
+ return Boolean(this._pdfModel.getElementsByPage(this._pageId)[this._elementId]);
191
+ }
192
+ getType() {
193
+ return this._readRaw().type;
194
+ }
195
+ getName() {
196
+ return this._readRaw().name;
197
+ }
198
+ setName(name) {
199
+ return this.update({ name });
200
+ }
201
+ getData() {
202
+ return import_core.Tools.deepClone(this._readRaw());
203
+ }
204
+ getBounds() {
205
+ const tr = this._readRaw().transform;
206
+ return {
207
+ left: tr.left,
208
+ top: tr.top,
209
+ width: tr.width,
210
+ height: tr.height,
211
+ angle: tr.angle ?? 0
212
+ };
213
+ }
214
+ getTransform() {
215
+ return import_core.Tools.deepClone(this._readRaw().transform);
216
+ }
217
+ setTransform(patch) {
218
+ const cur = this._readRaw().transform;
219
+ return this.update({
220
+ transform: {
221
+ ...cur,
222
+ ...patch,
223
+ width: patch.width !== void 0 ? Math.max(1, patch.width) : cur.width,
224
+ height: patch.height !== void 0 ? Math.max(0, patch.height) : cur.height
225
+ }
226
+ });
227
+ }
228
+ setPosition(left, top) {
229
+ const cur = this._readRaw().transform;
230
+ return this.update({
231
+ transform: { ...cur, left, top }
232
+ });
233
+ }
234
+ setSize(width, height) {
235
+ const cur = this._readRaw().transform;
236
+ return this.update({
237
+ transform: { ...cur, width: Math.max(1, width), height: Math.max(0, height) }
238
+ });
239
+ }
240
+ setRotation(angle) {
241
+ const cur = this._readRaw().transform;
242
+ return this.update({
243
+ transform: { ...cur, angle }
244
+ });
245
+ }
246
+ setFlip(flipX, flipY) {
247
+ const raw = this._readRaw();
248
+ const nextFlipY = flipY !== void 0 ? flipY : Boolean(raw.transform.flipY ?? raw.flipY);
249
+ return this.update({
250
+ flipX,
251
+ flipY: nextFlipY,
252
+ transform: { ...raw.transform, flipX, flipY: nextFlipY }
253
+ });
254
+ }
255
+ setOpacity(opacity) {
256
+ return this.update({ opacity: Math.max(0, Math.min(1, opacity)) });
257
+ }
258
+ setLocked(locked) {
259
+ return this.update({ locked });
260
+ }
261
+ setHidden(hidden) {
262
+ return this.update({ hidden });
263
+ }
264
+ isVisible() {
265
+ return !Boolean(this._readRaw().hidden);
266
+ }
267
+ setVisible(visible) {
268
+ return this.setHidden(!visible);
269
+ }
270
+ _reorderZIndex(mode) {
271
+ this._commandService.syncExecuteCommand(import_univer_pdfs2.ReorderPdfLayerCommand.id, {
272
+ unitId: this._pdfModel.getUnitId(),
273
+ pageId: this._pageId,
274
+ elementId: this._elementId,
275
+ mode
276
+ });
277
+ return this;
278
+ }
279
+ bringForward() {
280
+ return this._reorderZIndex("forward");
281
+ }
282
+ bringToFront() {
283
+ return this._reorderZIndex("front");
284
+ }
285
+ sendBackward() {
286
+ return this._reorderZIndex("backward");
287
+ }
288
+ sendToBack() {
289
+ return this._reorderZIndex("back");
290
+ }
291
+ update(patch) {
292
+ this._commandService.syncExecuteCommand(import_univer_pdfs2.UpdatePdfElementsCommand.id, {
293
+ unitId: this._pdfModel.getUnitId(),
294
+ pageId: this._pageId,
295
+ updates: [{ id: this._elementId, patch }]
296
+ });
297
+ return this;
298
+ }
299
+ remove() {
300
+ return this._commandService.syncExecuteCommand(import_univer_pdfs2.DeleteSelectedPdfElementsCommand.id, {
301
+ unitId: this._pdfModel.getUnitId(),
302
+ pageId: this._pageId,
303
+ elementIds: [this._elementId]
304
+ });
305
+ }
306
+ };
307
+ function paragraphBlocksToRichSpans(blocks) {
308
+ return blocks.map((b) => ({
309
+ text: b.text,
310
+ ...b.style?.fontWeight === "bold" ? { bold: true } : {},
311
+ ...b.style?.italic ? { italic: true } : {},
312
+ ...b.style?.underline ? { underline: true } : {},
313
+ ...b.style?.strikethrough ? { strikethrough: true } : {},
314
+ ...b.style?.color ? { color: b.style.color } : {},
315
+ ...b.style?.backgroundColor ? { backgroundColor: b.style.backgroundColor } : {},
316
+ ...b.style?.fontSize !== void 0 ? { fontSize: b.style.fontSize } : {}
317
+ }));
318
+ }
319
+ var FPdfParagraph = class extends FPdfPageElement {
320
+ constructor(pdfModelOrTextBox, commandServiceOrIndex, pageId, elementId) {
321
+ if (pdfModelOrTextBox instanceof FPdfTextBox) {
322
+ super(
323
+ pdfModelOrTextBox._getInternalPdfModel(),
324
+ pdfModelOrTextBox._getInternalCommandService(),
325
+ pdfModelOrTextBox.getPageId(),
326
+ pdfModelOrTextBox.getId()
327
+ );
328
+ this._ownerTextBox = pdfModelOrTextBox;
329
+ this._paragraphIndex = typeof commandServiceOrIndex === "number" ? commandServiceOrIndex : 0;
330
+ } else {
331
+ super(
332
+ pdfModelOrTextBox,
333
+ commandServiceOrIndex,
334
+ pageId,
335
+ elementId
336
+ );
337
+ }
338
+ }
339
+ _readTextEl() {
340
+ const el = this._readRaw();
341
+ if (el.type !== import_univer_pdfs2.PdfElementType.TEXT) {
342
+ throw new Error(`[UniverPdfs] Element "${this._elementId}" is not a TEXT/PARAGRAPH element.`);
343
+ }
344
+ return el;
345
+ }
346
+ getIndex() {
347
+ return this._paragraphIndex ?? 0;
348
+ }
349
+ getTextBox() {
350
+ return this._ownerTextBox ?? new FPdfTextBox(this._pdfModel, this._commandService, this._pageId, this._elementId);
351
+ }
352
+ getText() {
353
+ if (this._paragraphIndex !== void 0) {
354
+ const lines = this.getTextBox().getText().split("\n");
355
+ return lines[this._paragraphIndex] ?? "";
356
+ }
357
+ return this._readTextEl().content ?? "";
358
+ }
359
+ setText(text) {
360
+ if (this._paragraphIndex !== void 0) {
361
+ const tb = this.getTextBox();
362
+ const lines = tb.getText().split("\n");
363
+ while (lines.length <= this._paragraphIndex) {
364
+ lines.push("");
365
+ }
366
+ lines[this._paragraphIndex] = text;
367
+ tb.setText(lines.join("\n"));
368
+ return this;
369
+ }
370
+ const cur = this._readTextEl();
371
+ const nextBlocks = [{ text, style: cur.style ? { ...cur.style } : void 0 }];
372
+ this._writeBlocks(nextBlocks);
373
+ return this;
374
+ }
375
+ appendText(text) {
376
+ return this.setText(`${this.getText()}${text}`);
377
+ }
378
+ getBlocks() {
379
+ const el = this._readTextEl();
380
+ const stored = el.metadata?.paragraphBlocks;
381
+ if (Array.isArray(stored) && stored.length > 0 && this._paragraphIndex === void 0) {
382
+ return import_core.Tools.deepClone(stored);
383
+ }
384
+ if (el.richSpans?.length && this._paragraphIndex === void 0) {
385
+ return el.richSpans.map((sp) => ({
386
+ text: sp.text,
387
+ style: {
388
+ ...sp.bold ? { fontWeight: "bold" } : {},
389
+ ...sp.italic ? { italic: true } : {},
390
+ ...sp.underline ? { underline: true } : {},
391
+ ...sp.strikethrough ? { strikethrough: true } : {},
392
+ ...sp.color ? { color: sp.color } : {},
393
+ ...sp.backgroundColor ? { backgroundColor: sp.backgroundColor } : {},
394
+ ...sp.fontSize !== void 0 ? { fontSize: sp.fontSize } : {}
395
+ }
396
+ }));
397
+ }
398
+ const text = this.getText();
399
+ return text ? [{ text, style: el.style ? import_core.Tools.deepClone(el.style) : void 0 }] : [];
400
+ }
401
+ _writeBlocks(blocks) {
402
+ const el = this._readTextEl();
403
+ const content = blocks.map((b) => b.text).join("");
404
+ const hasCustomStyles = blocks.some((b) => b.style && Object.keys(b.style).length > 0);
405
+ return this.update({
406
+ content,
407
+ richSpans: hasCustomStyles ? paragraphBlocksToRichSpans(blocks) : void 0,
408
+ metadata: {
409
+ ...el.metadata ?? {},
410
+ isParagraph: true,
411
+ paragraphBlocks: import_core.Tools.deepClone(blocks)
412
+ }
413
+ });
414
+ }
415
+ appendBlock(blockOrText, style) {
416
+ const blocks = this.getBlocks();
417
+ const block = typeof blockOrText === "string" ? { text: blockOrText, ...style ? { style: { ...style } } : {} } : { text: blockOrText.text, style: blockOrText.style ? { ...blockOrText.style } : void 0 };
418
+ blocks.push(block);
419
+ return this._writeBlocks(blocks);
420
+ }
421
+ insertBlock(index, blockOrText, style) {
422
+ const blocks = this.getBlocks();
423
+ const clamped = Math.max(0, Math.min(blocks.length, Math.floor(index)));
424
+ const block = typeof blockOrText === "string" ? { text: blockOrText, ...style ? { style: { ...style } } : {} } : { text: blockOrText.text, style: blockOrText.style ? { ...blockOrText.style } : void 0 };
425
+ blocks.splice(clamped, 0, block);
426
+ return this._writeBlocks(blocks);
427
+ }
428
+ removeBlock(index) {
429
+ const blocks = this.getBlocks();
430
+ if (index >= 0 && index < blocks.length) {
431
+ blocks.splice(index, 1);
432
+ this._writeBlocks(blocks);
433
+ }
434
+ return this;
435
+ }
436
+ setBlockText(index, text) {
437
+ const blocks = this.getBlocks();
438
+ if (index >= 0 && index < blocks.length) {
439
+ blocks[index] = { ...blocks[index], text };
440
+ this._writeBlocks(blocks);
441
+ }
442
+ return this;
443
+ }
444
+ setBlockStyle(index, style) {
445
+ const blocks = this.getBlocks();
446
+ if (index >= 0 && index < blocks.length) {
447
+ blocks[index] = {
448
+ ...blocks[index],
449
+ style: { ...blocks[index].style ?? {}, ...style }
450
+ };
451
+ this._writeBlocks(blocks);
452
+ }
453
+ return this;
454
+ }
455
+ };
456
+ var FPdfTextSpan = class {
457
+ constructor(_pdfModel, _commandService, _pageId, _source) {
458
+ this._pdfModel = _pdfModel;
459
+ this._commandService = _commandService;
460
+ this._pageId = _pageId;
461
+ this._source = _source;
462
+ this._stale = false;
463
+ }
464
+ getId() {
465
+ if (this._source.kind === "native" && this._source.nativeSpan) {
466
+ return `${this._source.nativeSpan.id}:${this._source.startOffset}-${this._source.endOffset}`;
467
+ }
468
+ return `${this._source.elementId ?? "span"}:${this._source.startOffset}-${this._source.endOffset}`;
469
+ }
470
+ getPageId() {
471
+ return this._pageId;
472
+ }
473
+ getText() {
474
+ return this._source.matchedText;
475
+ }
476
+ getTextRuns() {
477
+ if (this._source.kind === "element" && this._source.elementId) {
478
+ const el = this._pdfModel.getElementsByPage(this._pageId)[this._source.elementId];
479
+ if (el && el.type === import_univer_pdfs2.PdfElementType.TEXT && el.richSpans?.length) {
480
+ const sliced = [];
481
+ let cursor = 0;
482
+ for (const sp of el.richSpans) {
483
+ const nextCursor = cursor + sp.text.length;
484
+ const overlapStart = Math.max(this._source.startOffset, cursor);
485
+ const overlapEnd = Math.min(this._source.endOffset, nextCursor);
486
+ if (overlapEnd > overlapStart) {
487
+ sliced.push({
488
+ ...import_core.Tools.deepClone(sp),
489
+ text: sp.text.slice(overlapStart - cursor, overlapEnd - cursor)
490
+ });
491
+ }
492
+ cursor = nextCursor;
493
+ }
494
+ if (sliced.length > 0) return sliced;
495
+ }
496
+ if (el && el.type === import_univer_pdfs2.PdfElementType.TEXT) {
497
+ return [
498
+ {
499
+ text: this._source.matchedText,
500
+ bold: el.style?.fontWeight === "bold",
501
+ italic: el.style?.italic,
502
+ underline: el.style?.underline,
503
+ strikethrough: el.style?.strikethrough,
504
+ color: el.style?.color,
505
+ fontSize: el.style?.fontSize
506
+ }
507
+ ];
508
+ }
509
+ }
510
+ return [
511
+ {
512
+ text: this._source.matchedText,
513
+ ...this._source.nativeSpan?.fontSize !== void 0 ? { fontSize: this._source.nativeSpan.fontSize } : {}
514
+ }
515
+ ];
516
+ }
517
+ getStartOffset() {
518
+ return this._source.startOffset;
519
+ }
520
+ getEndOffset() {
521
+ return this._source.endOffset;
522
+ }
523
+ getBounds() {
524
+ return { ...this._source.bounds };
525
+ }
526
+ isStale() {
527
+ return this._stale || Boolean(this._source.siblingGroup?.invalidated);
528
+ }
529
+ /**
530
+ * Replaces this text span with `replacement`, marks the span stale so it cannot be reused with
531
+ * outdated offsets, and returns the owning/promoted `FPdfTextBox`.
532
+ */
533
+ replaceText(replacement) {
534
+ if (this.isStale()) {
535
+ throw new Error(
536
+ "[UniverPdfs] FPdfTextSpan is stale after a prior replaceText() mutation; re-query findText() before replacing again."
537
+ );
538
+ }
539
+ this._stale = true;
540
+ if (this._source.siblingGroup) {
541
+ this._source.siblingGroup.invalidated = true;
542
+ }
543
+ if (this._source.kind === "element" && this._source.elementId) {
544
+ const el = this._pdfModel.getElementsByPage(this._pageId)[this._source.elementId];
545
+ if (!el || el.type !== import_univer_pdfs2.PdfElementType.TEXT) {
546
+ throw new Error(`[UniverPdfs] Target TEXT element "${this._source.elementId}" not found.`);
547
+ }
548
+ const curContent = el.content ?? "";
549
+ const nextContent = curContent.slice(0, this._source.startOffset) + replacement + curContent.slice(this._source.endOffset);
550
+ this._commandService.syncExecuteCommand(import_univer_pdfs2.UpdatePdfElementsCommand.id, {
551
+ unitId: this._pdfModel.getUnitId(),
552
+ pageId: this._pageId,
553
+ updates: [{ id: el.id, patch: { content: nextContent } }]
554
+ });
555
+ return new FPdfTextBox(this._pdfModel, this._commandService, this._pageId, el.id);
556
+ }
557
+ if (this._source.kind === "native" && this._source.nativeSpan) {
558
+ const span = this._source.nativeSpan;
559
+ const fullSpanText = span.text ?? "";
560
+ const nextSpanText = fullSpanText.slice(0, this._source.startOffset) + replacement + fullSpanText.slice(this._source.endOffset);
561
+ const beforeOrder = new Set(this._pdfModel.getElementOrderByPage(this._pageId));
562
+ this._commandService.syncExecuteCommand(import_univer_pdfs2.ReplacePdfNativeTextCommand.id, {
563
+ unitId: this._pdfModel.getUnitId(),
564
+ pageId: this._pageId,
565
+ spanId: span.id,
566
+ newText: nextSpanText
567
+ });
568
+ const afterOrder = this._pdfModel.getElementOrderByPage(this._pageId);
569
+ const map = this._pdfModel.getElementsByPage(this._pageId);
570
+ let targetElementId = afterOrder.find((id) => !beforeOrder.has(id));
571
+ if (!targetElementId) {
572
+ const promoted = Object.values(map).find(
573
+ (e) => e.type === import_univer_pdfs2.PdfElementType.TEXT && e.metadata?.promotedFromNativeSpanId === span.id
574
+ );
575
+ targetElementId = promoted?.id;
576
+ }
577
+ if (!targetElementId) {
578
+ throw new Error(`[UniverPdfs] Failed to promote native text span "${span.id}" to FPdfTextBox.`);
579
+ }
580
+ return new FPdfTextBox(this._pdfModel, this._commandService, this._pageId, targetElementId);
581
+ }
582
+ throw new Error("[UniverPdfs] Invalid FPdfTextSpan source.");
583
+ }
584
+ };
585
+ var FPdfTextBox = class extends FPdfPageElement {
586
+ _readTextEl() {
587
+ const el = this._readRaw();
588
+ if (el.type !== import_univer_pdfs2.PdfElementType.TEXT) {
589
+ throw new Error(`[UniverPdfs] Element "${this._elementId}" is not a TEXT element.`);
590
+ }
591
+ return el;
592
+ }
593
+ getText() {
594
+ return this._readTextEl().content ?? "";
595
+ }
596
+ setText(content) {
597
+ return this.update({ content });
598
+ }
599
+ getStyle() {
600
+ return import_core.Tools.deepClone(this._readTextEl().style ?? {});
601
+ }
602
+ setStyle(stylePatch) {
603
+ const prev = this._readTextEl().style ?? {};
604
+ return this.update({
605
+ style: { ...prev, ...stylePatch }
606
+ });
607
+ }
608
+ getTextRuns() {
609
+ const el = this._readTextEl();
610
+ if (el.richSpans?.length) {
611
+ return import_core.Tools.deepClone(el.richSpans);
612
+ }
613
+ return [
614
+ {
615
+ text: el.content ?? "",
616
+ bold: el.style?.fontWeight === "bold",
617
+ italic: el.style?.italic,
618
+ underline: el.style?.underline,
619
+ strikethrough: el.style?.strikethrough,
620
+ color: el.style?.color,
621
+ backgroundColor: el.style?.backgroundColor,
622
+ fontSize: el.style?.fontSize
623
+ }
624
+ ];
625
+ }
626
+ setTextStyle(styleOrStart, endOffset, rangeStyle) {
627
+ if (typeof styleOrStart !== "number") {
628
+ return this.setStyle(styleOrStart);
629
+ }
630
+ const el = this._readTextEl();
631
+ const content = el.content ?? "";
632
+ const start = Math.max(0, Math.min(content.length, Math.floor(styleOrStart)));
633
+ const end = Math.max(start, Math.min(content.length, Math.floor(endOffset ?? content.length)));
634
+ if (start >= end || !rangeStyle) return this;
635
+ const baseRuns = this.getTextRuns();
636
+ const nextRuns = [];
637
+ let cursor = 0;
638
+ const applyPatchToSpan = (sp) => ({
639
+ ...sp,
640
+ ...rangeStyle.fontWeight !== void 0 ? { bold: rangeStyle.fontWeight === "bold" } : {},
641
+ ...rangeStyle.italic !== void 0 ? { italic: rangeStyle.italic } : {},
642
+ ...rangeStyle.underline !== void 0 ? { underline: rangeStyle.underline } : {},
643
+ ...rangeStyle.strikethrough !== void 0 ? { strikethrough: rangeStyle.strikethrough } : {},
644
+ ...rangeStyle.color !== void 0 ? { color: rangeStyle.color } : {},
645
+ ...rangeStyle.backgroundColor !== void 0 ? { backgroundColor: rangeStyle.backgroundColor } : {},
646
+ ...rangeStyle.fontSize !== void 0 ? { fontSize: rangeStyle.fontSize } : {}
647
+ });
648
+ for (const run of baseRuns) {
649
+ const runLen = run.text.length;
650
+ const runEnd = cursor + runLen;
651
+ if (runEnd <= start || cursor >= end) {
652
+ if (run.text) nextRuns.push(run);
653
+ } else {
654
+ if (cursor < start) {
655
+ nextRuns.push({ ...run, text: run.text.slice(0, start - cursor) });
656
+ }
657
+ const midStart = Math.max(cursor, start) - cursor;
658
+ const midEnd = Math.min(runEnd, end) - cursor;
659
+ if (midEnd > midStart) {
660
+ nextRuns.push(applyPatchToSpan({ ...run, text: run.text.slice(midStart, midEnd) }));
661
+ }
662
+ if (runEnd > end) {
663
+ nextRuns.push({ ...run, text: run.text.slice(end - cursor) });
664
+ }
665
+ }
666
+ cursor = runEnd;
667
+ }
668
+ return this.update({ richSpans: nextRuns });
669
+ }
670
+ setFontSize(fontSize) {
671
+ return this.setStyle({ fontSize: Math.max(4, fontSize) });
672
+ }
673
+ setFontFamily(fontFamily) {
674
+ return this.setStyle({ fontFamily });
675
+ }
676
+ setColor(color) {
677
+ return this.setStyle({ color });
678
+ }
679
+ setBold(bold) {
680
+ return this.setStyle({ fontWeight: bold ? "bold" : "normal" });
681
+ }
682
+ setItalic(italic) {
683
+ return this.setStyle({ italic });
684
+ }
685
+ setUnderline(underline) {
686
+ return this.setStyle({ underline });
687
+ }
688
+ setStrikethrough(strikethrough) {
689
+ return this.setStyle({ strikethrough });
690
+ }
691
+ setCharacterSpacing(characterSpacing) {
692
+ return this.setStyle({ characterSpacing });
693
+ }
694
+ setTextAlign(textAlign) {
695
+ return this.setStyle({ textAlign });
696
+ }
697
+ getDynamicFontSize() {
698
+ const cfg = this._readTextEl().dynamicFontSize;
699
+ return cfg ? import_core.Tools.deepClone(cfg) : void 0;
700
+ }
701
+ setDynamicFontSize(config) {
702
+ return this.update({
703
+ dynamicFontSize: config ? import_core.Tools.deepClone(config) : void 0
704
+ });
705
+ }
706
+ getAnchor() {
707
+ return this._readTextEl().anchor;
708
+ }
709
+ setAnchor(anchor) {
710
+ const verticalMap = {
711
+ top: "top",
712
+ center: "middle",
713
+ bottom: "bottom",
714
+ "top-left": "top",
715
+ "top-center": "top",
716
+ "top-right": "top",
717
+ "middle-left": "middle",
718
+ "middle-center": "middle",
719
+ "middle-right": "middle",
720
+ "bottom-left": "bottom",
721
+ "bottom-center": "bottom",
722
+ "bottom-right": "bottom"
723
+ };
724
+ const horizontalMap = {
725
+ "top-left": "left",
726
+ "middle-left": "left",
727
+ "bottom-left": "left",
728
+ "top-center": "center",
729
+ "middle-center": "center",
730
+ "bottom-center": "center",
731
+ "top-right": "right",
732
+ "middle-right": "right",
733
+ "bottom-right": "right"
734
+ };
735
+ const prevStyle = this._readTextEl().style ?? {};
736
+ return this.update({
737
+ anchor,
738
+ style: {
739
+ ...prevStyle,
740
+ verticalAlign: verticalMap[anchor] ?? prevStyle.verticalAlign,
741
+ ...horizontalMap[anchor] ? { textAlign: horizontalMap[anchor] } : {}
742
+ }
743
+ });
744
+ }
745
+ getTextAnchor() {
746
+ return this.getAnchor();
747
+ }
748
+ setTextAnchor(anchor) {
749
+ return this.setAnchor(anchor);
750
+ }
751
+ getTextFormat() {
752
+ return this._readTextEl().textFormat ?? "plain";
753
+ }
754
+ setTextFormat(textFormat) {
755
+ return this.update({ textFormat });
756
+ }
757
+ getParagraphs() {
758
+ const lines = this.getText().split("\n");
759
+ return lines.map((_, idx) => new FPdfParagraph(this, idx));
760
+ }
761
+ insertParagraph(text, index) {
762
+ const cur = this.getText();
763
+ const lines = cur === "" ? [] : cur.split("\n");
764
+ const targetIdx = index === void 0 ? lines.length : Math.max(0, Math.min(lines.length, Math.floor(index)));
765
+ lines.splice(targetIdx, 0, text);
766
+ this.setText(lines.join("\n"));
767
+ return new FPdfParagraph(this, targetIdx);
768
+ }
769
+ findText(query) {
770
+ if (!query) return [];
771
+ const textEl = this._readTextEl();
772
+ const content = textEl.content ?? "";
773
+ const spans = [];
774
+ const siblingGroup = { invalidated: false };
775
+ let searchFrom = 0;
776
+ while (searchFrom <= content.length - query.length) {
777
+ const idx = content.indexOf(query, searchFrom);
778
+ if (idx < 0) break;
779
+ spans.push(
780
+ new FPdfTextSpan(this._pdfModel, this._commandService, this._pageId, {
781
+ kind: "element",
782
+ elementId: textEl.id,
783
+ startOffset: idx,
784
+ endOffset: idx + query.length,
785
+ matchedText: query,
786
+ bounds: {
787
+ left: textEl.transform.left,
788
+ top: textEl.transform.top,
789
+ width: textEl.transform.width,
790
+ height: textEl.transform.height
791
+ },
792
+ siblingGroup
793
+ })
794
+ );
795
+ searchFrom = idx + Math.max(1, query.length);
796
+ }
797
+ return spans;
798
+ }
799
+ };
800
+ var FPdfList = class extends FPdfPageElement {
801
+ _readListEl() {
802
+ const el = this._readRaw();
803
+ if (el.type !== import_univer_pdfs2.PdfElementType.LIST) {
804
+ throw new Error(`[UniverPdfs] Element "${this._elementId}" is not a LIST element.`);
805
+ }
806
+ return el;
807
+ }
808
+ getItems() {
809
+ return [...this._readListEl().items ?? []];
810
+ }
811
+ setItems(items) {
812
+ return this.update({ items: [...items] });
813
+ }
814
+ addItem(item, index) {
815
+ return this.insertItem(item, index, 0);
816
+ }
817
+ insertItem(textOrIndex, indexOrText, levelArg = 0) {
818
+ const el = this._readListEl();
819
+ const items = [...el.items ?? []];
820
+ const levels = Array.from(
821
+ { length: items.length },
822
+ (_, i) => Math.max(0, Math.min(8, Math.floor(el.itemLevels?.[i] ?? 0)))
823
+ );
824
+ const clampedLevel = Math.max(0, Math.min(8, Math.floor(levelArg)));
825
+ let insertIdx;
826
+ let itemText;
827
+ if (typeof textOrIndex === "number") {
828
+ insertIdx = Math.max(0, Math.min(items.length, Math.floor(textOrIndex)));
829
+ itemText = String(indexOrText ?? "");
830
+ } else {
831
+ itemText = textOrIndex;
832
+ insertIdx = typeof indexOrText === "number" ? Math.max(0, Math.min(items.length, Math.floor(indexOrText))) : items.length;
833
+ }
834
+ items.splice(insertIdx, 0, itemText);
835
+ levels.splice(insertIdx, 0, clampedLevel);
836
+ return this.update({
837
+ items,
838
+ itemLevels: levels
839
+ });
840
+ }
841
+ getItemLevel(index) {
842
+ const el = this._readListEl();
843
+ return Math.max(0, Math.min(8, Math.floor(el.itemLevels?.[index] ?? 0)));
844
+ }
845
+ changeItemLevel(index, level) {
846
+ const el = this._readListEl();
847
+ const items = el.items ?? [];
848
+ if (index < 0 || index >= items.length) return this;
849
+ const levels = Array.from(
850
+ { length: items.length },
851
+ (_, i) => Math.max(0, Math.min(8, Math.floor(el.itemLevels?.[i] ?? 0)))
852
+ );
853
+ levels[index] = Math.max(0, Math.min(8, Math.floor(level)));
854
+ return this.update({ itemLevels: levels });
855
+ }
856
+ setItemText(index, text) {
857
+ const items = this.getItems();
858
+ if (index >= 0 && index < items.length) {
859
+ items[index] = text;
860
+ this.setItems(items);
861
+ }
862
+ return this;
863
+ }
864
+ removeItem(index) {
865
+ const el = this._readListEl();
866
+ const next = [...el.items ?? []];
867
+ if (index >= 0 && index < next.length) {
868
+ const levels = Array.from(
869
+ { length: next.length },
870
+ (_, i) => Math.max(0, Math.min(8, Math.floor(el.itemLevels?.[i] ?? 0)))
871
+ );
872
+ next.splice(index, 1);
873
+ levels.splice(index, 1);
874
+ this.update({ items: next, itemLevels: levels });
875
+ }
876
+ return this;
877
+ }
878
+ getStartNumber() {
879
+ return Math.max(1, Math.floor(this._readListEl().startNumber ?? 1));
880
+ }
881
+ setStartNumber(startNumber) {
882
+ return this.update({
883
+ startNumber: Math.max(1, Math.floor(startNumber))
884
+ });
885
+ }
886
+ getKind() {
887
+ const lt = this._readListEl().listType;
888
+ if (lt === "ordered") return import_univer_pdfs2.PdfListKind.ORDERED;
889
+ if (lt === "check") return import_univer_pdfs2.PdfListKind.CHECK;
890
+ return import_univer_pdfs2.PdfListKind.BULLET;
891
+ }
892
+ setKind(kind) {
893
+ return this.update({ listType: kind });
894
+ }
895
+ getPresetId() {
896
+ return this._readListEl().presetId;
897
+ }
898
+ setPreset(presetId) {
899
+ const impliedType = presetId === "decimal" || presetId === "upper-alpha" || presetId === "lower-alpha" || presetId === "upper-roman" || presetId === "lower-roman" ? "ordered" : presetId === "checklist" ? "check" : "bullet";
900
+ return this.update({
901
+ presetId,
902
+ listType: impliedType
903
+ });
904
+ }
905
+ };
906
+ var FPdfTableCell = class {
907
+ constructor(_table, _rowIndex, _colIndex) {
908
+ this._table = _table;
909
+ this._rowIndex = _rowIndex;
910
+ this._colIndex = _colIndex;
911
+ }
912
+ getTable() {
913
+ return this._table;
914
+ }
915
+ getRowIndex() {
916
+ return this._rowIndex;
917
+ }
918
+ getColIndex() {
919
+ return this._colIndex;
920
+ }
921
+ getValue() {
922
+ const rows = this._table.getRows();
923
+ return rows[this._rowIndex]?.[this._colIndex];
924
+ }
925
+ getText() {
926
+ const cols = this._table.getColumns();
927
+ const col = cols[this._colIndex];
928
+ const raw = this.getValue();
929
+ return col ? (0, import_univer_pdfs2.formatPdfTableCell)(raw, col) : String(raw ?? "");
930
+ }
931
+ setValue(value) {
932
+ const rows = this._table.getRows().map((r) => [...r]);
933
+ const colCount = Math.max(1, this._table.getColumnCount());
934
+ while (rows.length <= this._rowIndex) {
935
+ rows.push(new Array(colCount).fill(""));
936
+ }
937
+ while (rows[this._rowIndex].length <= this._colIndex) {
938
+ rows[this._rowIndex].push("");
939
+ }
940
+ rows[this._rowIndex][this._colIndex] = value;
941
+ this._table.update({ rows });
942
+ return this;
943
+ }
944
+ setText(text) {
945
+ return this.setValue(text);
946
+ }
947
+ getStyle() {
948
+ const key = `${this._rowIndex}:${this._colIndex}`;
949
+ const raw = this._table.getData();
950
+ return import_core.Tools.deepClone(raw.cellStyles?.[key] ?? {});
951
+ }
952
+ setStyle(style) {
953
+ const key = `${this._rowIndex}:${this._colIndex}`;
954
+ const raw = this._table.getData();
955
+ const prevCellStyles = raw.cellStyles ?? {};
956
+ const mergedCellStyle = {
957
+ ...prevCellStyles[key] ?? {},
958
+ ...style
959
+ };
960
+ const nextMeta = style.verticalAlign !== void 0 ? {
961
+ ...raw.metadata ?? {},
962
+ cellVerticalAligns: {
963
+ ...raw.metadata?.cellVerticalAligns ?? {},
964
+ [key]: style.verticalAlign
965
+ }
966
+ } : raw.metadata;
967
+ this._table.update({
968
+ cellStyles: {
969
+ ...prevCellStyles,
970
+ [key]: mergedCellStyle
971
+ },
972
+ ...nextMeta ? { metadata: nextMeta } : {}
973
+ });
974
+ return this;
975
+ }
976
+ getVerticalAlign() {
977
+ const key = `${this._rowIndex}:${this._colIndex}`;
978
+ const raw = this._table.getData();
979
+ if (raw.cellStyles?.[key]?.verticalAlign) {
980
+ return raw.cellStyles[key].verticalAlign;
981
+ }
982
+ const cellAligns = raw.metadata?.cellVerticalAligns ?? {};
983
+ if (cellAligns[key]) return cellAligns[key];
984
+ const col = this._table.getColumns()[this._colIndex];
985
+ return col?.verticalAlign ?? import_univer_pdfs2.PdfTableCellVerticalAlign.MIDDLE;
986
+ }
987
+ setVerticalAlign(align) {
988
+ const key = `${this._rowIndex}:${this._colIndex}`;
989
+ const raw = this._table.getData();
990
+ const prevAligns = raw.metadata?.cellVerticalAligns ?? {};
991
+ const prevCellStyles = raw.cellStyles ?? {};
992
+ this._table.update({
993
+ cellStyles: {
994
+ ...prevCellStyles,
995
+ [key]: {
996
+ ...prevCellStyles[key] ?? {},
997
+ verticalAlign: align
998
+ }
999
+ },
1000
+ metadata: {
1001
+ ...raw.metadata ?? {},
1002
+ cellVerticalAligns: {
1003
+ ...prevAligns,
1004
+ [key]: align
1005
+ }
1006
+ }
1007
+ });
1008
+ return this;
1009
+ }
1010
+ };
1011
+ var FPdfTable = class extends FPdfPageElement {
1012
+ _readTableEl() {
1013
+ const el = this._readRaw();
1014
+ if (el.type !== import_univer_pdfs2.PdfElementType.TABLE) {
1015
+ throw new Error(`[UniverPdfs] Element "${this._elementId}" is not a TABLE element.`);
1016
+ }
1017
+ return el;
1018
+ }
1019
+ getRowCount() {
1020
+ return (this._readTableEl().rows ?? []).length;
1021
+ }
1022
+ getColumnCount() {
1023
+ return (this._readTableEl().columns ?? []).length;
1024
+ }
1025
+ getColumns() {
1026
+ return import_core.Tools.deepClone(this._readTableEl().columns ?? []);
1027
+ }
1028
+ getRows() {
1029
+ return import_core.Tools.deepClone(this._readTableEl().rows ?? []);
1030
+ }
1031
+ getCell(rowIndex, colIndex) {
1032
+ return new FPdfTableCell(this, rowIndex, colIndex);
1033
+ }
1034
+ addRow(cells, index) {
1035
+ const colCount = Math.max(1, this.getColumnCount());
1036
+ const normalized = Array.from({ length: colCount }, (_, idx) => cells?.[idx] ?? "");
1037
+ const nextRows = this.getRows();
1038
+ if (index === void 0) {
1039
+ nextRows.push(normalized);
1040
+ } else {
1041
+ nextRows.splice(Math.max(0, Math.min(nextRows.length, Math.floor(index))), 0, normalized);
1042
+ }
1043
+ const cur = this._readTableEl();
1044
+ const headH = cur.showHead === false ? 0 : cur.headerHeight ?? 26;
1045
+ const nextH = headH + nextRows.length * (cur.rowHeight ?? 24);
1046
+ return this.update({
1047
+ rows: nextRows,
1048
+ transform: {
1049
+ ...cur.transform,
1050
+ height: Math.max(cur.transform.height, nextH)
1051
+ }
1052
+ });
1053
+ }
1054
+ removeRow(rowIndex) {
1055
+ const nextRows = this.getRows();
1056
+ if (rowIndex >= 0 && rowIndex < nextRows.length) {
1057
+ nextRows.splice(rowIndex, 1);
1058
+ this.update({ rows: nextRows });
1059
+ }
1060
+ return this;
1061
+ }
1062
+ addColumn(column, index) {
1063
+ const cols = this.getColumns();
1064
+ const built = {
1065
+ id: column.id || `col-${(0, import_core.generateRandomId)(5)}`,
1066
+ header: column.header,
1067
+ field: column.field || `col_${cols.length + 1}`,
1068
+ widthRatio: column.widthRatio ?? 1,
1069
+ align: column.align,
1070
+ verticalAlign: column.verticalAlign,
1071
+ format: column.format,
1072
+ currencySymbol: column.currencySymbol,
1073
+ decimals: column.decimals,
1074
+ summaryType: column.summaryType
1075
+ };
1076
+ const insertIdx = index === void 0 ? cols.length : Math.max(0, Math.min(cols.length, Math.floor(index)));
1077
+ cols.splice(insertIdx, 0, built);
1078
+ const rows = this.getRows().map((r) => {
1079
+ const copy = [...r];
1080
+ copy.splice(insertIdx, 0, "");
1081
+ return copy;
1082
+ });
1083
+ return this.update({ columns: cols, rows });
1084
+ }
1085
+ removeColumn(colIndex) {
1086
+ const cols = this.getColumns();
1087
+ if (colIndex < 0 || colIndex >= cols.length || cols.length <= 1) return this;
1088
+ cols.splice(colIndex, 1);
1089
+ const rows = this.getRows().map((r) => r.filter((_, i) => i !== colIndex));
1090
+ return this.update({ columns: cols, rows });
1091
+ }
1092
+ resize(rowCount, colCount) {
1093
+ const targetRows = Math.max(1, Math.floor(rowCount));
1094
+ const targetCols = Math.max(1, Math.floor(colCount));
1095
+ const cur = this._readTableEl();
1096
+ const cols = this.getColumns();
1097
+ while (cols.length < targetCols) {
1098
+ const idx = cols.length + 1;
1099
+ cols.push({
1100
+ id: `col-${(0, import_core.generateRandomId)(5)}`,
1101
+ header: `Column ${idx}`,
1102
+ field: `col_${idx}`,
1103
+ widthRatio: 1
1104
+ });
1105
+ }
1106
+ if (cols.length > targetCols) {
1107
+ cols.length = targetCols;
1108
+ }
1109
+ const prevRows = this.getRows();
1110
+ const nextRows = Array.from(
1111
+ { length: targetRows },
1112
+ (_, rIdx) => Array.from({ length: targetCols }, (__, cIdx) => String(prevRows[rIdx]?.[cIdx] ?? ""))
1113
+ );
1114
+ const headH = cur.showHead === false ? 0 : cur.headerHeight ?? 26;
1115
+ const nextH = headH + targetRows * (cur.rowHeight ?? 24);
1116
+ return this.update({
1117
+ columns: cols,
1118
+ rows: nextRows,
1119
+ transform: {
1120
+ ...cur.transform,
1121
+ height: Math.max(24, nextH)
1122
+ }
1123
+ });
1124
+ }
1125
+ getTheme() {
1126
+ return this._readTableEl().metadata?.themePresetId;
1127
+ }
1128
+ setTheme(presetOrId) {
1129
+ return this.applyThemePreset(presetOrId);
1130
+ }
1131
+ getStyle() {
1132
+ const cur = this._readTableEl();
1133
+ return import_core.Tools.deepClone({
1134
+ showHead: cur.showHead !== false,
1135
+ borderColor: cur.borderColor,
1136
+ borderWidth: cur.borderWidth,
1137
+ borderStyle: cur.borderStyle,
1138
+ borderWidths: cur.borderWidths,
1139
+ zebraStripeColor: cur.zebraStripeColor ?? cur.stripedColor,
1140
+ headerStyle: cur.headerStyle,
1141
+ bodyStyle: cur.bodyStyle
1142
+ });
1143
+ }
1144
+ setStyle(style) {
1145
+ const cur = this._readTableEl();
1146
+ return this.update({
1147
+ ...style.showHead !== void 0 ? { showHead: style.showHead } : {},
1148
+ ...style.borderColor !== void 0 ? { borderColor: style.borderColor } : {},
1149
+ ...style.borderWidth !== void 0 ? { borderWidth: style.borderWidth } : {},
1150
+ ...style.borderStyle !== void 0 ? { borderStyle: style.borderStyle } : {},
1151
+ ...style.borderWidths !== void 0 ? { borderWidths: style.borderWidths } : {},
1152
+ ...style.zebraStripeColor !== void 0 ? { zebraStripeColor: style.zebraStripeColor, stripedColor: style.zebraStripeColor } : {},
1153
+ ...style.headerStyle !== void 0 ? { headerStyle: { ...cur.headerStyle ?? {}, ...style.headerStyle } } : {},
1154
+ ...style.bodyStyle !== void 0 ? { bodyStyle: { ...cur.bodyStyle ?? {}, ...style.bodyStyle } } : {}
1155
+ });
1156
+ }
1157
+ getMerges() {
1158
+ return import_core.Tools.deepClone(this._readTableEl().merges ?? []);
1159
+ }
1160
+ mergeCells(row, col, rowSpan, colSpan) {
1161
+ const cur = this._readTableEl();
1162
+ const r = Math.max(0, Math.floor(row));
1163
+ const c = Math.max(0, Math.floor(col));
1164
+ const rs = Math.max(1, Math.floor(rowSpan));
1165
+ const cs = Math.max(1, Math.floor(colSpan));
1166
+ if (rs <= 1 && cs <= 1) return this;
1167
+ const filtered = (cur.merges ?? []).filter((m) => !(m.row === r && m.col === c));
1168
+ filtered.push({ row: r, col: c, rowSpan: rs, colSpan: cs });
1169
+ return this.update({ merges: filtered });
1170
+ }
1171
+ applyThemePreset(presetOrId) {
1172
+ const preset = typeof presetOrId === "string" ? import_univer_pdfs2.PDF_TABLE_THEME_PRESETS.find((p) => p.id === presetOrId) : presetOrId;
1173
+ if (!preset) {
1174
+ throw new Error(`[UniverPdfs] Unknown PDF table theme preset "${String(presetOrId)}".`);
1175
+ }
1176
+ const cur = this._readTableEl();
1177
+ return this.update({
1178
+ borderColor: preset.borderColor,
1179
+ borderWidth: preset.borderWidth,
1180
+ zebraStripeColor: preset.zebraStripeColor,
1181
+ stripedColor: preset.zebraStripeColor,
1182
+ headerStyle: {
1183
+ ...cur.headerStyle ?? {},
1184
+ backgroundColor: preset.headerBackgroundColor,
1185
+ color: preset.headerTextColor,
1186
+ fontWeight: "bold"
1187
+ },
1188
+ bodyStyle: {
1189
+ ...cur.bodyStyle ?? {},
1190
+ backgroundColor: preset.bodyBackgroundColor,
1191
+ color: preset.bodyTextColor
1192
+ },
1193
+ metadata: {
1194
+ ...cur.metadata ?? {},
1195
+ themePresetId: preset.id
1196
+ }
1197
+ });
1198
+ }
1199
+ setAvoidOrphanHeader(avoidOrphanHeader) {
1200
+ return this.update({ avoidOrphanHeader });
1201
+ }
1202
+ };
1203
+ var FPdfImage = class extends FPdfPageElement {
1204
+ _readImageEl() {
1205
+ const el = this._readRaw();
1206
+ if (el.type !== import_univer_pdfs2.PdfElementType.IMAGE) {
1207
+ throw new Error(`[UniverPdfs] Element "${this._elementId}" is not an IMAGE element.`);
1208
+ }
1209
+ return el;
1210
+ }
1211
+ getSrc() {
1212
+ return this._readImageEl().src ?? "";
1213
+ }
1214
+ setSrc(src) {
1215
+ return this.update({ src });
1216
+ }
1217
+ getSource() {
1218
+ const el = this._readImageEl();
1219
+ return el.src || el.resourceId || "";
1220
+ }
1221
+ setSource(srcOrBytes, mimeType) {
1222
+ if (typeof srcOrBytes === "string") {
1223
+ return this.update({ src: srcOrBytes });
1224
+ }
1225
+ const detectedMime = mimeType ?? (srcOrBytes.length >= 4 && srcOrBytes[0] === 137 && srcOrBytes[1] === 80 ? "image/png" : "image/jpeg");
1226
+ return this.update({
1227
+ src: `data:${detectedMime};base64,${encodeUint8ToBase64(srcOrBytes)}`
1228
+ });
1229
+ }
1230
+ getImageSourceType() {
1231
+ const el = this._readImageEl();
1232
+ if (el.src?.startsWith("data:")) return import_univer_pdfs2.PdfImageSourceType.DATA_URI;
1233
+ if (el.src) return import_univer_pdfs2.PdfImageSourceType.URL;
1234
+ if (el.resourceId) return import_univer_pdfs2.PdfImageSourceType.RESOURCE;
1235
+ return import_univer_pdfs2.PdfImageSourceType.EMPTY;
1236
+ }
1237
+ getOpacity() {
1238
+ return this._readImageEl().opacity ?? 1;
1239
+ }
1240
+ getCrop() {
1241
+ const crop = this._readImageEl().crop;
1242
+ return crop ? import_core.Tools.deepClone(crop) : void 0;
1243
+ }
1244
+ setCrop(crop) {
1245
+ return this.update({
1246
+ crop: crop ? (0, import_univer_pdfs2.normalizeImageCrop)(crop) : void 0
1247
+ });
1248
+ }
1249
+ getFit() {
1250
+ return this._readImageEl().fit ?? "contain";
1251
+ }
1252
+ setFit(fit) {
1253
+ return this.update({ fit });
1254
+ }
1255
+ getObjectPosition() {
1256
+ return this._readImageEl().objectPosition ?? "center";
1257
+ }
1258
+ setObjectPosition(objectPosition) {
1259
+ return this.update({ objectPosition });
1260
+ }
1261
+ getAltText() {
1262
+ return this._readImageEl().altText;
1263
+ }
1264
+ setAltText(altText) {
1265
+ return this.update({ altText });
1266
+ }
1267
+ toBuilder() {
1268
+ return new FPdfImageBuilder(
1269
+ this._pdfModel,
1270
+ this._commandService,
1271
+ this._pageId,
1272
+ this._readImageEl()
1273
+ );
1274
+ }
1275
+ };
1276
+ var FPdfImageBuilder = class {
1277
+ constructor(_pdfModel, _commandService, _pageId, existing) {
1278
+ this._pdfModel = _pdfModel;
1279
+ this._commandService = _commandService;
1280
+ this._pageId = _pageId;
1281
+ this._src = "";
1282
+ this._left = 48;
1283
+ this._top = 48;
1284
+ this._width = 180;
1285
+ this._height = 120;
1286
+ this._fit = "contain";
1287
+ this._objectPosition = "center";
1288
+ this._angle = 0;
1289
+ this._opacity = 1;
1290
+ if (existing) {
1291
+ if (existing instanceof FPdfImage) {
1292
+ const raw = existing.getData();
1293
+ this._src = raw.src ?? "";
1294
+ this._resourceId = raw.resourceId;
1295
+ this._left = raw.transform.left;
1296
+ this._top = raw.transform.top;
1297
+ this._width = raw.transform.width;
1298
+ this._height = raw.transform.height;
1299
+ this._angle = raw.transform.angle ?? 0;
1300
+ this._fit = raw.fit ?? "contain";
1301
+ this._objectPosition = raw.objectPosition ?? "center";
1302
+ this._crop = raw.crop ? import_core.Tools.deepClone(raw.crop) : void 0;
1303
+ this._opacity = raw.opacity ?? 1;
1304
+ this._altText = raw.altText;
1305
+ this._name = raw.name;
1306
+ } else if ("transform" in existing && existing.transform) {
1307
+ const raw = existing;
1308
+ this._src = raw.src ?? "";
1309
+ this._resourceId = raw.resourceId;
1310
+ this._left = raw.transform.left;
1311
+ this._top = raw.transform.top;
1312
+ this._width = raw.transform.width;
1313
+ this._height = raw.transform.height;
1314
+ this._angle = raw.transform.angle ?? 0;
1315
+ this._fit = raw.fit ?? "contain";
1316
+ this._objectPosition = raw.objectPosition ?? "center";
1317
+ this._crop = raw.crop ? import_core.Tools.deepClone(raw.crop) : void 0;
1318
+ this._opacity = raw.opacity ?? 1;
1319
+ this._altText = raw.altText;
1320
+ this._name = raw.name;
1321
+ } else {
1322
+ const info = existing;
1323
+ this._src = info.source ?? info.src ?? "";
1324
+ this._resourceId = info.resourceId;
1325
+ if (info.left !== void 0) this._left = info.left;
1326
+ if (info.top !== void 0) this._top = info.top;
1327
+ if (info.width !== void 0) this._width = info.width;
1328
+ if (info.height !== void 0) this._height = info.height;
1329
+ if (info.rotation !== void 0 || info.angle !== void 0) {
1330
+ this._angle = info.rotation ?? info.angle ?? 0;
1331
+ }
1332
+ if (info.fit) this._fit = info.fit;
1333
+ if (info.objectPosition) this._objectPosition = info.objectPosition;
1334
+ if (info.crop) this._crop = import_core.Tools.deepClone(info.crop);
1335
+ if (info.opacity !== void 0) this._opacity = info.opacity;
1336
+ if (info.altText !== void 0) this._altText = info.altText;
1337
+ if (info.name !== void 0) this._name = info.name;
1338
+ }
1339
+ }
1340
+ }
1341
+ setSource(srcOrBytes, mimeType) {
1342
+ if (typeof srcOrBytes === "string") {
1343
+ this._src = srcOrBytes;
1344
+ } else {
1345
+ const detectedMime = mimeType ?? (srcOrBytes.length >= 4 && srcOrBytes[0] === 137 && srcOrBytes[1] === 80 ? "image/png" : "image/jpeg");
1346
+ this._src = `data:${detectedMime};base64,${encodeUint8ToBase64(srcOrBytes)}`;
1347
+ }
1348
+ return this;
1349
+ }
1350
+ setPosition(left, top) {
1351
+ this._left = left;
1352
+ this._top = top;
1353
+ return this;
1354
+ }
1355
+ setAbsolutePosition(left, top) {
1356
+ return this.setPosition(left, top);
1357
+ }
1358
+ setSize(width, height) {
1359
+ this._width = Math.max(1, width);
1360
+ this._height = Math.max(1, height);
1361
+ return this;
1362
+ }
1363
+ setFit(fit) {
1364
+ this._fit = fit;
1365
+ return this;
1366
+ }
1367
+ setObjectPosition(objectPosition) {
1368
+ this._objectPosition = objectPosition;
1369
+ return this;
1370
+ }
1371
+ setRotation(angle) {
1372
+ this._angle = angle;
1373
+ return this;
1374
+ }
1375
+ setCrop(crop) {
1376
+ this._crop = crop ? (0, import_univer_pdfs2.normalizeImageCrop)(crop) : void 0;
1377
+ return this;
1378
+ }
1379
+ setOpacity(opacity) {
1380
+ this._opacity = Math.max(0, Math.min(1, opacity));
1381
+ return this;
1382
+ }
1383
+ setAltText(altText) {
1384
+ this._altText = altText;
1385
+ return this;
1386
+ }
1387
+ setName(name) {
1388
+ this._name = name;
1389
+ return this;
1390
+ }
1391
+ /**
1392
+ * Builds a detached `IPdfImageBuilderInfo` descriptor without mutating the page.
1393
+ * Pass the returned object to `page.insertImage(info, index?)` (or call `info.insert(index?)`) to insert.
1394
+ */
1395
+ build() {
1396
+ const snapshotSrc = this._src;
1397
+ const snapshotResourceId = this._resourceId;
1398
+ const snapshotLeft = this._left;
1399
+ const snapshotTop = this._top;
1400
+ const snapshotWidth = this._width;
1401
+ const snapshotHeight = this._height;
1402
+ const snapshotAngle = this._angle;
1403
+ const snapshotFit = this._fit;
1404
+ const snapshotObjectPos = this._objectPosition;
1405
+ const snapshotCrop = this._crop ? import_core.Tools.deepClone(this._crop) : void 0;
1406
+ const snapshotOpacity = this._opacity;
1407
+ const snapshotAltText = this._altText;
1408
+ const snapshotName = this._name;
1409
+ return {
1410
+ __isPdfImageBuilderInfo: true,
1411
+ source: snapshotSrc,
1412
+ src: snapshotSrc,
1413
+ resourceId: snapshotResourceId,
1414
+ left: snapshotLeft,
1415
+ top: snapshotTop,
1416
+ width: snapshotWidth,
1417
+ height: snapshotHeight,
1418
+ angle: snapshotAngle,
1419
+ rotation: snapshotAngle,
1420
+ fit: snapshotFit,
1421
+ objectPosition: snapshotObjectPos,
1422
+ crop: snapshotCrop,
1423
+ opacity: snapshotOpacity,
1424
+ altText: snapshotAltText,
1425
+ name: snapshotName,
1426
+ getSource: () => snapshotSrc,
1427
+ getSrc: () => snapshotSrc,
1428
+ getFit: () => snapshotFit,
1429
+ getObjectPosition: () => snapshotObjectPos,
1430
+ getOpacity: () => snapshotOpacity,
1431
+ getCrop: () => snapshotCrop ? import_core.Tools.deepClone(snapshotCrop) : void 0,
1432
+ insert: (index) => this._insertFromInfo({
1433
+ source: snapshotSrc,
1434
+ src: snapshotSrc,
1435
+ resourceId: snapshotResourceId,
1436
+ left: snapshotLeft,
1437
+ top: snapshotTop,
1438
+ width: snapshotWidth,
1439
+ height: snapshotHeight,
1440
+ angle: snapshotAngle,
1441
+ rotation: snapshotAngle,
1442
+ fit: snapshotFit,
1443
+ objectPosition: snapshotObjectPos,
1444
+ crop: snapshotCrop,
1445
+ opacity: snapshotOpacity,
1446
+ altText: snapshotAltText,
1447
+ name: snapshotName
1448
+ }, index)
1449
+ };
1450
+ }
1451
+ async buildAsync() {
1452
+ return this.build();
1453
+ }
1454
+ _insertFromInfo(info, index) {
1455
+ const id = `el-${(0, import_core.generateRandomId)(6)}`;
1456
+ this._commandService.syncExecuteCommand(import_univer_pdfs2.AddPdfElementCommand.id, {
1457
+ unitId: this._pdfModel.getUnitId(),
1458
+ pageId: this._pageId,
1459
+ elementType: import_univer_pdfs2.PdfElementType.IMAGE,
1460
+ index,
1461
+ element: {
1462
+ id,
1463
+ name: info.name,
1464
+ src: info.source || info.src,
1465
+ resourceId: info.resourceId,
1466
+ fit: info.fit,
1467
+ objectPosition: info.objectPosition,
1468
+ crop: info.crop ? import_core.Tools.deepClone(info.crop) : void 0,
1469
+ opacity: info.opacity,
1470
+ altText: info.altText,
1471
+ transform: {
1472
+ left: info.left,
1473
+ top: info.top,
1474
+ width: info.width,
1475
+ height: info.height,
1476
+ angle: info.rotation ?? info.angle ?? 0
1477
+ }
1478
+ }
1479
+ });
1480
+ return new FPdfImage(this._pdfModel, this._commandService, this._pageId, id);
1481
+ }
1482
+ /**
1483
+ * Materializes this builder directly onto the page as an `FPdfImage`.
1484
+ */
1485
+ insert(index) {
1486
+ return this.build().insert(index);
1487
+ }
1488
+ };
1489
+ var FPdfDivider = class extends FPdfPageElement {
1490
+ _readLineEl() {
1491
+ const el = this._readRaw();
1492
+ if (el.type !== import_univer_pdfs2.PdfElementType.LINE) {
1493
+ throw new Error(`[UniverPdfs] Element "${this._elementId}" is not a LINE divider element.`);
1494
+ }
1495
+ return el;
1496
+ }
1497
+ getStrokeColor() {
1498
+ return this._readLineEl().strokeColor ?? "#E3E5EA";
1499
+ }
1500
+ setStrokeColor(strokeColor) {
1501
+ return this.update({ strokeColor });
1502
+ }
1503
+ getStrokeWidth() {
1504
+ return this._readLineEl().strokeWidth ?? 1;
1505
+ }
1506
+ setStrokeWidth(strokeWidth) {
1507
+ return this.update({ strokeWidth: Math.max(0.25, strokeWidth) });
1508
+ }
1509
+ setDashArray(dashArray) {
1510
+ return this.update({ dashArray });
1511
+ }
1512
+ setArrows(startArrow, endArrow) {
1513
+ return this.update({ startArrow, endArrow });
1514
+ }
1515
+ getStroke() {
1516
+ const line = this._readLineEl();
1517
+ return {
1518
+ color: line.strokeColor ?? "#E3E5EA",
1519
+ width: line.strokeWidth ?? 1,
1520
+ ...line.dashArray ? { dashArray: [...line.dashArray] } : {},
1521
+ opacity: line.opacity ?? 1
1522
+ };
1523
+ }
1524
+ setStroke(stroke) {
1525
+ const nextColor = stroke.color ?? stroke.strokeColor;
1526
+ const nextWidth = stroke.width ?? stroke.strokeWidth;
1527
+ return this.update({
1528
+ ...nextColor !== void 0 ? { strokeColor: nextColor } : {},
1529
+ ...nextWidth !== void 0 ? { strokeWidth: Math.max(0.25, nextWidth) } : {},
1530
+ ...stroke.dashArray !== void 0 ? { dashArray: stroke.dashArray } : {},
1531
+ ...stroke.opacity !== void 0 ? { opacity: Math.max(0, Math.min(1, stroke.opacity)) } : {}
1532
+ });
1533
+ }
1534
+ };
1535
+ var FPdfAnnotation = class extends FPdfPageElement {
1536
+ _readAnnotEl() {
1537
+ const el = this._readRaw();
1538
+ if (el.type !== import_univer_pdfs2.PdfElementType.ANNOTATION) {
1539
+ throw new Error(`[UniverPdfs] Element "${this._elementId}" is not an ANNOTATION element.`);
1540
+ }
1541
+ return el;
1542
+ }
1543
+ getAnnotationType() {
1544
+ return this._readAnnotEl().annotationType;
1545
+ }
1546
+ setAnnotationType(annotationType) {
1547
+ return this.update({ annotationType });
1548
+ }
1549
+ getComment() {
1550
+ return this._readAnnotEl().comment ?? "";
1551
+ }
1552
+ setComment(comment) {
1553
+ return this.update({ comment });
1554
+ }
1555
+ getAuthor() {
1556
+ return this._readAnnotEl().author ?? "";
1557
+ }
1558
+ setAuthor(author) {
1559
+ return this.update({ author });
1560
+ }
1561
+ getStatus() {
1562
+ return this._readAnnotEl().status;
1563
+ }
1564
+ setStatus(status) {
1565
+ return this.update({ status });
1566
+ }
1567
+ setColor(color) {
1568
+ return this.update({ color });
1569
+ }
1570
+ getStyle() {
1571
+ const annot = this._readAnnotEl();
1572
+ return {
1573
+ color: annot.color,
1574
+ opacity: annot.opacity,
1575
+ annotationType: annot.annotationType
1576
+ };
1577
+ }
1578
+ setStyle(style) {
1579
+ return this.update({
1580
+ ...style.color !== void 0 ? { color: style.color } : {},
1581
+ ...style.opacity !== void 0 ? { opacity: Math.max(0, Math.min(1, style.opacity)) } : {},
1582
+ ...style.annotationType !== void 0 ? { annotationType: style.annotationType } : {}
1583
+ });
1584
+ }
1585
+ getMarkup() {
1586
+ const annot = this._readAnnotEl();
1587
+ return {
1588
+ annotationType: annot.annotationType,
1589
+ bounds: this.getBounds(),
1590
+ color: annot.color,
1591
+ opacity: annot.opacity,
1592
+ comment: annot.comment ?? "",
1593
+ author: annot.author ?? ""
1594
+ };
1595
+ }
1596
+ getInk() {
1597
+ const inkPaths = this._readAnnotEl().metadata?.inkPaths;
1598
+ return Array.isArray(inkPaths) ? import_core.Tools.deepClone(inkPaths) : [];
1599
+ }
1600
+ getReplies() {
1601
+ return import_core.Tools.deepClone(this._readAnnotEl().replies ?? []);
1602
+ }
1603
+ addReply(author, content) {
1604
+ const reply = {
1605
+ id: `rep-${(0, import_core.generateRandomId)(6)}`,
1606
+ author: author || "Reviewer",
1607
+ content,
1608
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
1609
+ };
1610
+ const nextReplies = [...this.getReplies(), reply];
1611
+ this.update({ replies: nextReplies });
1612
+ return reply;
1613
+ }
1614
+ };
1615
+ function wrapPdfElementFacade(pdfModel, commandService, pageId, el) {
1616
+ switch (el.type) {
1617
+ case import_univer_pdfs2.PdfElementType.TEXT:
1618
+ if (el.metadata?.isParagraph === true) {
1619
+ return new FPdfParagraph(pdfModel, commandService, pageId, el.id);
1620
+ }
1621
+ return new FPdfTextBox(pdfModel, commandService, pageId, el.id);
1622
+ case import_univer_pdfs2.PdfElementType.LIST:
1623
+ return new FPdfList(pdfModel, commandService, pageId, el.id);
1624
+ case import_univer_pdfs2.PdfElementType.TABLE:
1625
+ return new FPdfTable(pdfModel, commandService, pageId, el.id);
1626
+ case import_univer_pdfs2.PdfElementType.IMAGE:
1627
+ return new FPdfImage(pdfModel, commandService, pageId, el.id);
1628
+ case import_univer_pdfs2.PdfElementType.LINE:
1629
+ return new FPdfDivider(pdfModel, commandService, pageId, el.id);
1630
+ case import_univer_pdfs2.PdfElementType.ANNOTATION:
1631
+ return new FPdfAnnotation(pdfModel, commandService, pageId, el.id);
1632
+ default:
1633
+ return new FPdfPageElement(pdfModel, commandService, pageId, el.id);
1634
+ }
1635
+ }
1636
+
1637
+ // src/facade/f-pdf-page.ts
1638
+ function isDetachedImageBuilderInfo(val) {
1639
+ return Boolean(
1640
+ val && typeof val === "object" && val.__isPdfImageBuilderInfo === true
1641
+ );
1642
+ }
1643
+ var FPdfPage = class {
1644
+ constructor(_pdfModel, _commandService, _pageId) {
1645
+ this._pdfModel = _pdfModel;
1646
+ this._commandService = _commandService;
1647
+ this._pageId = _pageId;
1648
+ }
1649
+ getId() {
1650
+ return this._pageId;
1651
+ }
1652
+ _readPageMeta() {
1653
+ const page = this._pdfModel.getPage(this._pageId);
1654
+ if (!page) {
1655
+ throw new Error(`[UniverPdfs] Page "${this._pageId}" no longer exists in unit "${this._pdfModel.getUnitId()}".`);
1656
+ }
1657
+ return page;
1658
+ }
1659
+ getData() {
1660
+ return import_core2.Tools.deepClone(this._readPageMeta());
1661
+ }
1662
+ getIndex() {
1663
+ return this._pdfModel.getPageOrder().indexOf(this._pageId);
1664
+ }
1665
+ getPageNumber() {
1666
+ const idx = this.getIndex();
1667
+ return idx >= 0 ? idx + 1 : 1;
1668
+ }
1669
+ getTitle() {
1670
+ return this._readPageMeta().title ?? `Page ${this.getPageNumber()}`;
1671
+ }
1672
+ setTitle(title) {
1673
+ this._commandService.syncExecuteCommand(import_univer_pdfs3.UpdatePdfPagePropsCommand.id, {
1674
+ unitId: this._pdfModel.getUnitId(),
1675
+ pageId: this._pageId,
1676
+ patch: { title }
1677
+ });
1678
+ return this;
1679
+ }
1680
+ getSize() {
1681
+ const meta = this._readPageMeta();
1682
+ return import_core2.Tools.deepClone(meta.pageSize ?? this._pdfModel.getDocument().pageSize);
1683
+ }
1684
+ setSize(pageSize) {
1685
+ this._commandService.syncExecuteCommand(import_univer_pdfs3.UpdatePdfPagePropsCommand.id, {
1686
+ unitId: this._pdfModel.getUnitId(),
1687
+ pageId: this._pageId,
1688
+ patch: { pageSize: import_core2.Tools.deepClone(pageSize) }
1689
+ });
1690
+ return this;
1691
+ }
1692
+ getRotation() {
1693
+ return this._readPageMeta().rotation ?? 0;
1694
+ }
1695
+ setRotation(rotation) {
1696
+ this._commandService.syncExecuteCommand(import_univer_pdfs3.RotatePdfPageCommand.id, {
1697
+ unitId: this._pdfModel.getUnitId(),
1698
+ pageId: this._pageId,
1699
+ rotation
1700
+ });
1701
+ return this;
1702
+ }
1703
+ setBackgroundColor(backgroundColor) {
1704
+ this._commandService.syncExecuteCommand(import_univer_pdfs3.UpdatePdfPagePropsCommand.id, {
1705
+ unitId: this._pdfModel.getUnitId(),
1706
+ pageId: this._pageId,
1707
+ patch: { backgroundColor }
1708
+ });
1709
+ return this;
1710
+ }
1711
+ getElements() {
1712
+ const map = this._pdfModel.getElementsByPage(this._pageId);
1713
+ const order = this._pdfModel.getElementOrderByPage(this._pageId);
1714
+ const out = [];
1715
+ for (const id of order) {
1716
+ const el = map[id];
1717
+ if (el) {
1718
+ out.push(wrapPdfElementFacade(this._pdfModel, this._commandService, this._pageId, el));
1719
+ }
1720
+ }
1721
+ return out;
1722
+ }
1723
+ getElementById(elementId) {
1724
+ const el = this._pdfModel.getElementsByPage(this._pageId)[elementId];
1725
+ if (!el) return null;
1726
+ return wrapPdfElementFacade(this._pdfModel, this._commandService, this._pageId, el);
1727
+ }
1728
+ getTextBoxes() {
1729
+ return this.getElements().filter((el) => el instanceof FPdfTextBox);
1730
+ }
1731
+ getParagraphs() {
1732
+ return this.getElements().filter((el) => el instanceof FPdfParagraph);
1733
+ }
1734
+ getLists() {
1735
+ return this.getElements().filter((el) => el instanceof FPdfList);
1736
+ }
1737
+ getTables() {
1738
+ return this.getElements().filter((el) => el instanceof FPdfTable);
1739
+ }
1740
+ getImages() {
1741
+ return this.getElements().filter((el) => el instanceof FPdfImage);
1742
+ }
1743
+ getDividers() {
1744
+ return this.getElements().filter((el) => el instanceof FPdfDivider);
1745
+ }
1746
+ getAnnotations() {
1747
+ return this.getElements().filter((el) => el instanceof FPdfAnnotation);
1748
+ }
1749
+ insertTextBox(contentOrOptions, bounds, style) {
1750
+ const id = `el-${(0, import_core2.generateRandomId)(6)}`;
1751
+ if (typeof contentOrOptions === "object" && contentOrOptions !== null) {
1752
+ const opts = contentOrOptions;
1753
+ this._commandService.syncExecuteCommand(import_univer_pdfs3.AddPdfElementCommand.id, {
1754
+ unitId: this._pdfModel.getUnitId(),
1755
+ pageId: this._pageId,
1756
+ elementType: import_univer_pdfs3.PdfElementType.TEXT,
1757
+ index: opts.index,
1758
+ element: {
1759
+ id,
1760
+ name: opts.name,
1761
+ content: opts.text ?? opts.content ?? "",
1762
+ dynamicFontSize: opts.dynamicFontSize,
1763
+ linkUrl: opts.linkUrl,
1764
+ linkDest: opts.linkDest,
1765
+ style: {
1766
+ fontSize: 12,
1767
+ color: "#1B1C1F",
1768
+ ...opts.style
1769
+ },
1770
+ transform: {
1771
+ left: opts.left ?? 48,
1772
+ top: opts.top ?? 48,
1773
+ width: opts.width ?? 260,
1774
+ height: opts.height ?? 44,
1775
+ ...opts.angle !== void 0 ? { angle: opts.angle } : {}
1776
+ }
1777
+ }
1778
+ });
1779
+ return new FPdfTextBox(this._pdfModel, this._commandService, this._pageId, id);
1780
+ }
1781
+ this._commandService.syncExecuteCommand(import_univer_pdfs3.AddPdfElementCommand.id, {
1782
+ unitId: this._pdfModel.getUnitId(),
1783
+ pageId: this._pageId,
1784
+ elementType: import_univer_pdfs3.PdfElementType.TEXT,
1785
+ element: {
1786
+ id,
1787
+ content: contentOrOptions,
1788
+ style: {
1789
+ fontSize: 12,
1790
+ color: "#1B1C1F",
1791
+ ...style
1792
+ },
1793
+ transform: {
1794
+ left: bounds?.left ?? 48,
1795
+ top: bounds?.top ?? 48,
1796
+ width: bounds?.width ?? 260,
1797
+ height: bounds?.height ?? 44
1798
+ }
1799
+ }
1800
+ });
1801
+ return new FPdfTextBox(this._pdfModel, this._commandService, this._pageId, id);
1802
+ }
1803
+ insertParagraph(textOrOptions, bounds, style) {
1804
+ const id = `el-${(0, import_core2.generateRandomId)(6)}`;
1805
+ const opts = typeof textOrOptions === "object" && textOrOptions !== null ? textOrOptions : {
1806
+ text: textOrOptions,
1807
+ left: bounds?.left,
1808
+ top: bounds?.top,
1809
+ width: bounds?.width,
1810
+ height: bounds?.height,
1811
+ style
1812
+ };
1813
+ const blocks = opts.blocks?.length ? import_core2.Tools.deepClone(opts.blocks) : [{ text: opts.text ?? "", ...opts.style ? { style: { ...opts.style } } : {} }];
1814
+ const content = blocks.map((b) => b.text).join("");
1815
+ this._commandService.syncExecuteCommand(import_univer_pdfs3.AddPdfElementCommand.id, {
1816
+ unitId: this._pdfModel.getUnitId(),
1817
+ pageId: this._pageId,
1818
+ elementType: import_univer_pdfs3.PdfElementType.TEXT,
1819
+ index: opts.index,
1820
+ element: {
1821
+ id,
1822
+ name: opts.name,
1823
+ content,
1824
+ style: {
1825
+ fontSize: 12,
1826
+ color: "#1B1C1F",
1827
+ ...opts.style
1828
+ },
1829
+ metadata: {
1830
+ isParagraph: true,
1831
+ paragraphBlocks: blocks
1832
+ },
1833
+ transform: {
1834
+ left: opts.left ?? 48,
1835
+ top: opts.top ?? 48,
1836
+ width: opts.width ?? 320,
1837
+ height: opts.height ?? 52
1838
+ }
1839
+ }
1840
+ });
1841
+ const para = new FPdfParagraph(this._pdfModel, this._commandService, this._pageId, id);
1842
+ if (opts.blocks?.length) {
1843
+ const first = opts.blocks[0];
1844
+ if (first?.style) para.setBlockStyle(0, first.style);
1845
+ }
1846
+ return para;
1847
+ }
1848
+ insertList(itemsOrOptions, options) {
1849
+ const id = `el-${(0, import_core2.generateRandomId)(6)}`;
1850
+ const normalized = Array.isArray(itemsOrOptions) ? { ...options, items: itemsOrOptions } : itemsOrOptions;
1851
+ const items = [...normalized.items ?? ["Item 1"]];
1852
+ const listType = normalized.listType ?? normalized.kind ?? "bullet";
1853
+ const itemLevels = normalized.itemLevels?.map(
1854
+ (lvl) => Math.max(0, Math.min(8, Math.floor(lvl || 0)))
1855
+ );
1856
+ this._commandService.syncExecuteCommand(import_univer_pdfs3.AddPdfElementCommand.id, {
1857
+ unitId: this._pdfModel.getUnitId(),
1858
+ pageId: this._pageId,
1859
+ elementType: import_univer_pdfs3.PdfElementType.LIST,
1860
+ index: normalized.index,
1861
+ element: {
1862
+ id,
1863
+ listType,
1864
+ presetId: normalized.presetId,
1865
+ startNumber: normalized.startNumber,
1866
+ itemLevels,
1867
+ items,
1868
+ style: normalized.style,
1869
+ transform: {
1870
+ left: normalized.left ?? 48,
1871
+ top: normalized.top ?? 48,
1872
+ width: normalized.width ?? 260,
1873
+ height: normalized.height ?? Math.max(40, items.length * 20 + 10)
1874
+ }
1875
+ }
1876
+ });
1877
+ return new FPdfList(this._pdfModel, this._commandService, this._pageId, id);
1878
+ }
1879
+ insertTable(rowsOrOptions, colsOrHeaders, bounds) {
1880
+ const id = `el-${(0, import_core2.generateRandomId)(6)}`;
1881
+ const isOptsObject = typeof rowsOrOptions === "object" && rowsOrOptions !== null && !Array.isArray(rowsOrOptions);
1882
+ const rowsArg = isOptsObject ? rowsOrOptions.rows ?? 2 : rowsOrOptions;
1883
+ const colsArg = isOptsObject ? rowsOrOptions.columns ?? rowsOrOptions.headers : colsOrHeaders;
1884
+ const showHead = isOptsObject ? rowsOrOptions.showHead !== false : true;
1885
+ let columns;
1886
+ if (Array.isArray(colsArg) && colsArg.length > 0) {
1887
+ columns = colsArg.map(
1888
+ (item, idx) => typeof item === "string" ? { id: `col-${idx + 1}`, header: item, field: `col_${idx + 1}`, widthRatio: 1 } : { ...item, id: item.id || `col-${idx + 1}`, field: item.field || `col_${idx + 1}` }
1889
+ );
1890
+ } else {
1891
+ const colCount = typeof colsArg === "number" && colsArg > 0 ? Math.floor(colsArg) : Array.isArray(rowsArg) && rowsArg[0] ? Math.max(1, rowsArg[0].length) : 3;
1892
+ columns = Array.from({ length: colCount }, (_, idx) => ({
1893
+ id: `col-${idx + 1}`,
1894
+ header: `Column ${idx + 1}`,
1895
+ field: `col_${idx + 1}`,
1896
+ widthRatio: 1
1897
+ }));
1898
+ }
1899
+ const rows = Array.isArray(rowsArg) ? rowsArg.map((r) => [...r]) : Array.from(
1900
+ { length: Math.max(1, Math.floor(rowsArg || 2)) },
1901
+ () => new Array(columns.length).fill("")
1902
+ );
1903
+ const headerHeight = 26;
1904
+ const rowHeight = 24;
1905
+ const defaultHeight = (showHead ? headerHeight : 0) + rows.length * rowHeight;
1906
+ this._commandService.syncExecuteCommand(import_univer_pdfs3.AddPdfElementCommand.id, {
1907
+ unitId: this._pdfModel.getUnitId(),
1908
+ pageId: this._pageId,
1909
+ elementType: import_univer_pdfs3.PdfElementType.TABLE,
1910
+ index: isOptsObject ? rowsOrOptions.index : void 0,
1911
+ element: {
1912
+ id,
1913
+ columns,
1914
+ rows,
1915
+ showHead,
1916
+ headerHeight,
1917
+ rowHeight,
1918
+ borderColor: isOptsObject ? rowsOrOptions.borderColor : void 0,
1919
+ borderWidth: isOptsObject ? rowsOrOptions.borderWidth : void 0,
1920
+ borderStyle: isOptsObject ? rowsOrOptions.borderStyle : void 0,
1921
+ borderWidths: isOptsObject ? rowsOrOptions.borderWidths : void 0,
1922
+ merges: isOptsObject ? rowsOrOptions.merges : void 0,
1923
+ cellStyles: isOptsObject ? rowsOrOptions.cellStyles : void 0,
1924
+ avoidOrphanHeader: true,
1925
+ transform: {
1926
+ left: (isOptsObject ? rowsOrOptions.left : bounds?.left) ?? 48,
1927
+ top: (isOptsObject ? rowsOrOptions.top : bounds?.top) ?? 48,
1928
+ width: (isOptsObject ? rowsOrOptions.width : bounds?.width) ?? 420,
1929
+ height: (isOptsObject ? rowsOrOptions.height : bounds?.height) ?? defaultHeight
1930
+ }
1931
+ }
1932
+ });
1933
+ return new FPdfTable(this._pdfModel, this._commandService, this._pageId, id);
1934
+ }
1935
+ newImage(existing) {
1936
+ return new FPdfImageBuilder(this._pdfModel, this._commandService, this._pageId, existing);
1937
+ }
1938
+ insertImage(srcOrInfoOrOptions, boundsOrIndex, indexArg) {
1939
+ if (isDetachedImageBuilderInfo(srcOrInfoOrOptions)) {
1940
+ const idx2 = typeof boundsOrIndex === "number" ? boundsOrIndex : indexArg;
1941
+ return this.newImage(srcOrInfoOrOptions).insert(idx2);
1942
+ }
1943
+ if (typeof srcOrInfoOrOptions === "object" && srcOrInfoOrOptions !== null && !(srcOrInfoOrOptions instanceof Uint8Array)) {
1944
+ const opts = srcOrInfoOrOptions;
1945
+ const builder2 = this.newImage();
1946
+ const srcVal = opts.source ?? opts.src;
1947
+ if (srcVal !== void 0) builder2.setSource(srcVal);
1948
+ if (opts.left !== void 0 || opts.top !== void 0) {
1949
+ builder2.setPosition(opts.left ?? 48, opts.top ?? 48);
1950
+ }
1951
+ if (opts.width !== void 0 || opts.height !== void 0) {
1952
+ builder2.setSize(opts.width ?? 180, opts.height ?? 120);
1953
+ }
1954
+ if (opts.rotation !== void 0 || opts.angle !== void 0) {
1955
+ builder2.setRotation(opts.rotation ?? opts.angle ?? 0);
1956
+ }
1957
+ if (opts.fit) builder2.setFit(opts.fit);
1958
+ if (opts.objectPosition) builder2.setObjectPosition(opts.objectPosition);
1959
+ if (opts.crop) builder2.setCrop(opts.crop);
1960
+ if (opts.opacity !== void 0) builder2.setOpacity(opts.opacity);
1961
+ if (opts.altText !== void 0) builder2.setAltText(opts.altText);
1962
+ if (opts.name !== void 0) builder2.setName(opts.name);
1963
+ return builder2.insert(opts.index);
1964
+ }
1965
+ const bounds = typeof boundsOrIndex === "object" && boundsOrIndex !== null ? boundsOrIndex : void 0;
1966
+ const idx = typeof boundsOrIndex === "number" ? boundsOrIndex : indexArg;
1967
+ const builder = this.newImage().setSource(srcOrInfoOrOptions);
1968
+ if (bounds?.left !== void 0 || bounds?.top !== void 0) {
1969
+ builder.setPosition(bounds.left ?? 48, bounds.top ?? 48);
1970
+ }
1971
+ if (bounds?.width !== void 0 || bounds?.height !== void 0) {
1972
+ builder.setSize(bounds.width ?? 180, bounds.height ?? 120);
1973
+ }
1974
+ if (bounds?.fit) builder.setFit(bounds.fit);
1975
+ if (bounds?.objectPosition) builder.setObjectPosition(bounds.objectPosition);
1976
+ return builder.insert(idx);
1977
+ }
1978
+ async insertImageAsync(sourceOrInfo, optionsOrIndex) {
1979
+ if (isDetachedImageBuilderInfo(sourceOrInfo)) {
1980
+ const idx = typeof optionsOrIndex === "number" ? optionsOrIndex : optionsOrIndex?.index;
1981
+ return this.insertImage(sourceOrInfo, idx);
1982
+ }
1983
+ let resolvedSource;
1984
+ if (typeof sourceOrInfo === "string" || sourceOrInfo instanceof Uint8Array) {
1985
+ resolvedSource = sourceOrInfo;
1986
+ } else if (sourceOrInfo instanceof ArrayBuffer) {
1987
+ resolvedSource = new Uint8Array(sourceOrInfo);
1988
+ } else if (typeof Blob !== "undefined" && sourceOrInfo instanceof Blob) {
1989
+ const buf = await sourceOrInfo.arrayBuffer();
1990
+ const bytes = new Uint8Array(buf);
1991
+ const mime = sourceOrInfo.type || "image/png";
1992
+ resolvedSource = `data:${mime};base64,${encodeUint8ToBase64(bytes)}`;
1993
+ } else {
1994
+ resolvedSource = String(sourceOrInfo ?? "");
1995
+ }
1996
+ if (typeof optionsOrIndex === "number") {
1997
+ return this.insertImage(resolvedSource, void 0, optionsOrIndex);
1998
+ }
1999
+ return this.insertImage({
2000
+ ...optionsOrIndex ?? {},
2001
+ source: resolvedSource
2002
+ });
2003
+ }
2004
+ insertDivider(bounds) {
2005
+ const id = `el-${(0, import_core2.generateRandomId)(6)}`;
2006
+ this._commandService.syncExecuteCommand(import_univer_pdfs3.AddPdfElementCommand.id, {
2007
+ unitId: this._pdfModel.getUnitId(),
2008
+ pageId: this._pageId,
2009
+ elementType: import_univer_pdfs3.PdfElementType.LINE,
2010
+ index: bounds?.index,
2011
+ element: {
2012
+ id,
2013
+ strokeColor: bounds?.strokeColor ?? "#E3E5EA",
2014
+ strokeWidth: bounds?.strokeWidth ?? 1,
2015
+ dashArray: bounds?.dashArray,
2016
+ transform: {
2017
+ left: bounds?.left ?? 48,
2018
+ top: bounds?.top ?? 120,
2019
+ width: bounds?.width ?? 480,
2020
+ height: bounds?.height ?? 8
2021
+ }
2022
+ }
2023
+ });
2024
+ return new FPdfDivider(this._pdfModel, this._commandService, this._pageId, id);
2025
+ }
2026
+ insertAnnotation(typeOrOptions, bounds, options) {
2027
+ const id = `el-${(0, import_core2.generateRandomId)(6)}`;
2028
+ if (typeof typeOrOptions === "object" && typeOrOptions !== null) {
2029
+ const opts = typeOrOptions;
2030
+ this._commandService.syncExecuteCommand(import_univer_pdfs3.AddPdfElementCommand.id, {
2031
+ unitId: this._pdfModel.getUnitId(),
2032
+ pageId: this._pageId,
2033
+ elementType: import_univer_pdfs3.PdfElementType.ANNOTATION,
2034
+ index: opts.index,
2035
+ element: {
2036
+ id,
2037
+ annotationType: opts.annotationType ?? opts.type ?? "highlight",
2038
+ comment: opts.comment,
2039
+ author: opts.author,
2040
+ color: opts.color,
2041
+ opacity: opts.opacity,
2042
+ transform: {
2043
+ left: opts.left ?? 60,
2044
+ top: opts.top ?? 60,
2045
+ width: opts.width ?? 140,
2046
+ height: opts.height ?? 24
2047
+ }
2048
+ }
2049
+ });
2050
+ return new FPdfAnnotation(this._pdfModel, this._commandService, this._pageId, id);
2051
+ }
2052
+ this._commandService.syncExecuteCommand(import_univer_pdfs3.AddPdfElementCommand.id, {
2053
+ unitId: this._pdfModel.getUnitId(),
2054
+ pageId: this._pageId,
2055
+ elementType: import_univer_pdfs3.PdfElementType.ANNOTATION,
2056
+ element: {
2057
+ id,
2058
+ annotationType: typeOrOptions,
2059
+ comment: options?.comment,
2060
+ author: options?.author,
2061
+ color: options?.color,
2062
+ opacity: options?.opacity,
2063
+ transform: {
2064
+ left: bounds?.left ?? 60,
2065
+ top: bounds?.top ?? 60,
2066
+ width: bounds?.width ?? 140,
2067
+ height: bounds?.height ?? 24
2068
+ }
2069
+ }
2070
+ });
2071
+ return new FPdfAnnotation(this._pdfModel, this._commandService, this._pageId, id);
2072
+ }
2073
+ /**
2074
+ * Returns all text spans on this page (both editable `TEXT` / `PARAGRAPH` elements and native base-PDF text spans).
2075
+ * When `query` is provided, filters to matched substring spans via `findText(query)`.
2076
+ */
2077
+ getTextSpans(query) {
2078
+ if (query) {
2079
+ return this.findText(query);
2080
+ }
2081
+ const results = [];
2082
+ const map = this._pdfModel.getElementsByPage(this._pageId);
2083
+ const order = this._pdfModel.getElementOrderByPage(this._pageId);
2084
+ for (const id of order) {
2085
+ const el = map[id];
2086
+ if (!el || el.hidden || el.type !== import_univer_pdfs3.PdfElementType.TEXT) continue;
2087
+ const text = el.content ?? "";
2088
+ if (!text) continue;
2089
+ results.push(
2090
+ new FPdfTextSpan(this._pdfModel, this._commandService, this._pageId, {
2091
+ kind: "element",
2092
+ elementId: el.id,
2093
+ startOffset: 0,
2094
+ endOffset: text.length,
2095
+ matchedText: text,
2096
+ bounds: {
2097
+ left: el.transform.left,
2098
+ top: el.transform.top,
2099
+ width: el.transform.width,
2100
+ height: el.transform.height
2101
+ }
2102
+ })
2103
+ );
2104
+ }
2105
+ const snap = this._pdfModel.save();
2106
+ const suppressedSet = new Set(snap.editState.suppressedSourceIds ?? []);
2107
+ const nativeSpans = snap.editState.nativeTextSpansByPage?.[this._pageId] ?? snap.metadata?.nativeTextSpansByPage?.[this._pageId] ?? [];
2108
+ for (const ns of nativeSpans) {
2109
+ if (ns.suppressed || suppressedSet.has(ns.id) || !ns.text) continue;
2110
+ results.push(
2111
+ new FPdfTextSpan(this._pdfModel, this._commandService, this._pageId, {
2112
+ kind: "native",
2113
+ startOffset: 0,
2114
+ endOffset: ns.text.length,
2115
+ matchedText: ns.text,
2116
+ bounds: {
2117
+ left: ns.left,
2118
+ top: ns.top,
2119
+ width: ns.width,
2120
+ height: ns.height
2121
+ },
2122
+ nativeSpan: ns
2123
+ })
2124
+ );
2125
+ }
2126
+ return results;
2127
+ }
2128
+ /**
2129
+ * Searches both editable `TEXT`/`PARAGRAPH` elements and native imported base-PDF text spans on this page,
2130
+ * returning `FPdfTextSpan` instances that support safe `replaceText()`.
2131
+ */
2132
+ findText(query) {
2133
+ if (!query) return [];
2134
+ const results = [];
2135
+ const map = this._pdfModel.getElementsByPage(this._pageId);
2136
+ const order = this._pdfModel.getElementOrderByPage(this._pageId);
2137
+ for (const id of order) {
2138
+ const el = map[id];
2139
+ if (el && !el.hidden && el.type === import_univer_pdfs3.PdfElementType.TEXT) {
2140
+ const tb = new FPdfTextBox(this._pdfModel, this._commandService, this._pageId, el.id);
2141
+ results.push(...tb.findText(query));
2142
+ }
2143
+ }
2144
+ const snap = this._pdfModel.save();
2145
+ const suppressedSet = new Set(snap.editState.suppressedSourceIds ?? []);
2146
+ const nativeSpans = snap.editState.nativeTextSpansByPage?.[this._pageId] ?? snap.metadata?.nativeTextSpansByPage?.[this._pageId] ?? [];
2147
+ for (const ns of nativeSpans) {
2148
+ if (ns.suppressed || suppressedSet.has(ns.id) || !ns.text) continue;
2149
+ const siblingGroup = { invalidated: false };
2150
+ let from = 0;
2151
+ while (from <= ns.text.length - query.length) {
2152
+ const idx = ns.text.indexOf(query, from);
2153
+ if (idx < 0) break;
2154
+ results.push(
2155
+ new FPdfTextSpan(this._pdfModel, this._commandService, this._pageId, {
2156
+ kind: "native",
2157
+ startOffset: idx,
2158
+ endOffset: idx + query.length,
2159
+ matchedText: query,
2160
+ bounds: {
2161
+ left: ns.left,
2162
+ top: ns.top,
2163
+ width: ns.width,
2164
+ height: ns.height
2165
+ },
2166
+ nativeSpan: ns,
2167
+ siblingGroup
2168
+ })
2169
+ );
2170
+ from = idx + Math.max(1, query.length);
2171
+ }
2172
+ }
2173
+ return results;
2174
+ }
2175
+ remove() {
2176
+ return this._commandService.syncExecuteCommand(import_univer_pdfs3.RemovePdfPageCommand.id, {
2177
+ unitId: this._pdfModel.getUnitId(),
2178
+ pageId: this._pageId
2179
+ });
2180
+ }
2181
+ };
2182
+
2183
+ // src/facade/f-pdf.ts
2184
+ function bytesToBase64Safe(bytes) {
2185
+ if (typeof Buffer !== "undefined") {
2186
+ return Buffer.from(bytes).toString("base64");
2187
+ }
2188
+ let binary = "";
2189
+ const chunkSize = 32768;
2190
+ for (let i = 0; i < bytes.length; i += chunkSize) {
2191
+ binary += String.fromCharCode(...bytes.subarray(i, i + chunkSize));
2192
+ }
2193
+ return btoa(binary);
2194
+ }
2195
+ function base64OrDataUriToBytesSafe(input) {
2196
+ const commaIdx = input.indexOf(",");
2197
+ const b64 = (commaIdx >= 0 ? input.slice(commaIdx + 1) : input).trim();
2198
+ const dataUri = input.startsWith("data:") ? input : `data:application/pdf;base64,${b64}`;
2199
+ if (typeof Buffer !== "undefined") {
2200
+ return { bytes: new Uint8Array(Buffer.from(b64, "base64")), dataUri };
2201
+ }
2202
+ const bin = atob(b64);
2203
+ const bytes = new Uint8Array(bin.length);
2204
+ for (let i = 0; i < bin.length; i++) {
2205
+ bytes[i] = bin.charCodeAt(i);
2206
+ }
2207
+ return { bytes, dataUri };
2208
+ }
2209
+ var FPdf = class {
2210
+ constructor(_pdfModel, _injector, _commandService) {
2211
+ this._pdfModel = _pdfModel;
2212
+ this._injector = _injector;
2213
+ this._commandService = _commandService;
2214
+ this._isFlushingActiveEditor = false;
2215
+ }
2216
+ getId() {
2217
+ return this._pdfModel.getUnitId();
2218
+ }
2219
+ getModel() {
2220
+ return this._pdfModel;
2221
+ }
2222
+ getName() {
2223
+ return this._pdfModel.getName();
2224
+ }
2225
+ setName(name) {
2226
+ this._commandService.syncExecuteCommand(import_univer_pdfs4.UpdatePdfUnitPropsCommand.id, {
2227
+ unitId: this.getId(),
2228
+ patch: { name }
2229
+ });
2230
+ }
2231
+ /**
2232
+ * Returns immutable document structure baseline (`pages`, `pageOrder`, `pageSize`).
2233
+ */
2234
+ getDocument() {
2235
+ return this._pdfModel.getDocument();
2236
+ }
2237
+ /**
2238
+ * Returns object-oriented `FPdfPage` facades for every page in `pageOrder`.
2239
+ */
2240
+ getPages() {
2241
+ return this._pdfModel.getPageOrder().map((pageId) => new FPdfPage(this._pdfModel, this._commandService, pageId));
2242
+ }
2243
+ /**
2244
+ * Returns the `FPdfPage` facade matching `pageId`, or `null` if not found.
2245
+ */
2246
+ getPageById(pageId) {
2247
+ if (!this._pdfModel.getPage(pageId)) return null;
2248
+ return new FPdfPage(this._pdfModel, this._commandService, pageId);
2249
+ }
2250
+ /**
2251
+ * Returns the `FPdfPage` facade at 0-based `index`, or `null` if out of range.
2252
+ */
2253
+ getPageByIndex(index) {
2254
+ const order = this._pdfModel.getPageOrder();
2255
+ if (index < 0 || index >= order.length) return null;
2256
+ return new FPdfPage(this._pdfModel, this._commandService, order[index]);
2257
+ }
2258
+ /**
2259
+ * Inserts a new page at 0-based `index` (or at the end when omitted) via `ICommandService`
2260
+ * and returns its `FPdfPage` facade.
2261
+ */
2262
+ insertPage(index, page) {
2263
+ let createdPageId = "";
2264
+ this._commandService.syncExecuteCommand(import_univer_pdfs4.AddPdfPageCommand.id, {
2265
+ unitId: this.getId(),
2266
+ index,
2267
+ page,
2268
+ onCreated: (pid) => {
2269
+ createdPageId = pid;
2270
+ }
2271
+ });
2272
+ if (!createdPageId) {
2273
+ const order = this._pdfModel.getPageOrder();
2274
+ createdPageId = order[order.length - 1];
2275
+ }
2276
+ return new FPdfPage(this._pdfModel, this._commandService, createdPageId);
2277
+ }
2278
+ /**
2279
+ * Appends pages from another PDF binary (`Uint8Array`, `ArrayBuffer`, `Blob`, Base64/Data URI)
2280
+ * or another `IPdfUnitData` snapshot onto the end of this document (Undo/Redo-safe),
2281
+ * returning the newly appended `FPdfPage[]` instances.
2282
+ */
2283
+ async appendPdf(source, options) {
2284
+ const currentSnap = this.save();
2285
+ if (source && typeof source === "object" && !(source instanceof Uint8Array) && !(source instanceof ArrayBuffer) && !(typeof Blob !== "undefined" && source instanceof Blob) && "document" in source && "editState" in source) {
2286
+ const srcSnap = source;
2287
+ const next2 = import_core3.Tools.deepClone(currentSnap);
2288
+ const appendedIds = [];
2289
+ let sourceOffset = 0;
2290
+ if (srcSnap.sourceDocumentRef?.dataUri) {
2291
+ if (next2.sourceDocumentRef?.dataUri) {
2292
+ const curBase = base64OrDataUriToBytesSafe(next2.sourceDocumentRef.dataUri).bytes;
2293
+ const addBase = base64OrDataUriToBytesSafe(srcSnap.sourceDocumentRef.dataUri).bytes;
2294
+ const curDoc = await import_pdf_lib.PDFDocument.load(curBase, { ignoreEncryption: true });
2295
+ sourceOffset = curDoc.getPageCount();
2296
+ const merged = await (0, import_univer_pdfs4.mergePdfBytes)([curBase, addBase]);
2297
+ next2.sourceDocumentRef = {
2298
+ ...next2.sourceDocumentRef,
2299
+ dataUri: `data:application/pdf;base64,${bytesToBase64Safe(merged)}`
2300
+ };
2301
+ } else {
2302
+ next2.sourceDocumentRef = import_core3.Tools.deepClone(srcSnap.sourceDocumentRef);
2303
+ }
2304
+ }
2305
+ for (const srcPageId of srcSnap.document.pageOrder) {
2306
+ const srcMeta = srcSnap.document.pages[srcPageId];
2307
+ if (!srcMeta) continue;
2308
+ const newPageId = `page-${(0, import_core3.generateRandomId)(6)}`;
2309
+ appendedIds.push(newPageId);
2310
+ next2.document.pages[newPageId] = {
2311
+ ...import_core3.Tools.deepClone(srcMeta),
2312
+ id: newPageId,
2313
+ ...srcMeta.sourcePageNumber ? { sourcePageNumber: srcMeta.sourcePageNumber + sourceOffset } : {}
2314
+ };
2315
+ next2.document.pageOrder.push(newPageId);
2316
+ const srcMap = srcSnap.editState.elementsByPage[srcPageId] ?? {};
2317
+ const srcOrder = srcSnap.editState.elementOrderByPage[srcPageId] ?? Object.keys(srcMap);
2318
+ const clonedMap = {};
2319
+ const clonedOrder = [];
2320
+ for (const eid of srcOrder) {
2321
+ const el = srcMap[eid];
2322
+ if (!el) continue;
2323
+ const newElId = `el-${(0, import_core3.generateRandomId)(6)}`;
2324
+ clonedMap[newElId] = { ...import_core3.Tools.deepClone(el), id: newElId };
2325
+ clonedOrder.push(newElId);
2326
+ }
2327
+ next2.editState.elementsByPage[newPageId] = clonedMap;
2328
+ next2.editState.elementOrderByPage[newPageId] = clonedOrder;
2329
+ }
2330
+ this.loadSnapshot(next2);
2331
+ return appendedIds.map((pid) => new FPdfPage(this._pdfModel, this._commandService, pid));
2332
+ }
2333
+ const imported = await (0, import_univer_pdfs4.importPdfSource)(
2334
+ source,
2335
+ { password: options?.password }
2336
+ );
2337
+ const next = import_core3.Tools.deepClone(currentSnap);
2338
+ let basePageOffset = 0;
2339
+ if (next.sourceDocumentRef?.dataUri) {
2340
+ const existingBytes = base64OrDataUriToBytesSafe(next.sourceDocumentRef.dataUri).bytes;
2341
+ const existingDoc = await import_pdf_lib.PDFDocument.load(existingBytes, { ignoreEncryption: true });
2342
+ basePageOffset = existingDoc.getPageCount();
2343
+ const mergedBytes = await (0, import_univer_pdfs4.mergePdfBytes)([existingBytes, imported.bytes]);
2344
+ next.sourceDocumentRef = {
2345
+ ...next.sourceDocumentRef,
2346
+ dataUri: `data:application/pdf;base64,${bytesToBase64Safe(mergedBytes)}`
2347
+ };
2348
+ } else {
2349
+ const curRendered = await (0, import_univer_pdfs4.exportPdfBytes)(currentSnap);
2350
+ const curDoc = await import_pdf_lib.PDFDocument.load(curRendered, { ignoreEncryption: true });
2351
+ basePageOffset = curDoc.getPageCount();
2352
+ const mergedBytes = await (0, import_univer_pdfs4.mergePdfBytes)([curRendered, imported.bytes]);
2353
+ next.sourceDocumentRef = {
2354
+ ...imported.sourceDocumentRef,
2355
+ dataUri: `data:application/pdf;base64,${bytesToBase64Safe(mergedBytes)}`
2356
+ };
2357
+ }
2358
+ const appendedPageIds = imported.pageSizes.map(() => `page-${(0, import_core3.generateRandomId)(6)}`);
2359
+ const extractedNative = await (0, import_univer_pdfs4.extractNativeTextSpansFromPdfBytes)(imported.bytes, appendedPageIds);
2360
+ next.editState.nativeTextSpansByPage = {
2361
+ ...next.editState.nativeTextSpansByPage ?? {},
2362
+ ...extractedNative
2363
+ };
2364
+ next.metadata = {
2365
+ ...next.metadata ?? {},
2366
+ nativeTextSpansByPage: {
2367
+ ...next.metadata?.nativeTextSpansByPage ?? {},
2368
+ ...extractedNative
2369
+ }
2370
+ };
2371
+ imported.pageSizes.forEach((sz, idx) => {
2372
+ const pid = appendedPageIds[idx];
2373
+ next.document.pages[pid] = {
2374
+ id: pid,
2375
+ title: `Page ${next.document.pageOrder.length + 1}`,
2376
+ backgroundColor: "#ffffff",
2377
+ sourcePageNumber: basePageOffset + idx + 1,
2378
+ pageSize: { ...sz }
2379
+ };
2380
+ next.document.pageOrder.push(pid);
2381
+ next.editState.elementsByPage[pid] = {};
2382
+ next.editState.elementOrderByPage[pid] = [];
2383
+ });
2384
+ this.loadSnapshot(next);
2385
+ return appendedPageIds.map((pid) => new FPdfPage(this._pdfModel, this._commandService, pid));
2386
+ }
2387
+ /**
2388
+ * Validates this document's template schema structure, field names, element types, and page bounds.
2389
+ */
2390
+ validateTemplate(options) {
2391
+ return (0, import_univer_pdfs4.validatePdfTemplateSchema)(this.save(), options);
2392
+ }
2393
+ /**
2394
+ * Runs a full template doctor health check (schema validation, font & CJK coverage, required variables, and input contracts).
2395
+ */
2396
+ diagnoseHealth(options) {
2397
+ const snap = this.save();
2398
+ const schema = (0, import_univer_pdfs4.validatePdfTemplateSchema)(snap, { strict: options?.strict });
2399
+ const fonts = (0, import_univer_pdfs4.diagnosePdfFonts)(snap, options);
2400
+ const variables = (0, import_univer_pdfs4.validatePdfTemplateVariables)(snap);
2401
+ const cjk = (0, import_univer_pdfs4.detectCJKInPdfTemplate)(snap);
2402
+ const contractHints = (0, import_univer_pdfs4.collectPdfInputContractHints)(snap);
2403
+ return {
2404
+ healthy: schema.valid && fonts.healthy && variables.valid,
2405
+ schema,
2406
+ fonts,
2407
+ variables,
2408
+ cjk,
2409
+ contractHints
2410
+ };
2411
+ }
2412
+ _flushActiveEditingIfNeeded() {
2413
+ if (this._isFlushingActiveEditor) return;
2414
+ this._isFlushingActiveEditor = true;
2415
+ try {
2416
+ if (this._injector.has(import_univer_pdfs4.IPdfSelectionService)) {
2417
+ this._injector.get(import_univer_pdfs4.IPdfSelectionService).commitActiveEditing();
2418
+ }
2419
+ } catch {
2420
+ } finally {
2421
+ this._isFlushingActiveEditor = false;
2422
+ }
2423
+ }
2424
+ /**
2425
+ * Compiles and returns the complete `IPdfUnitData` snapshot (baseline + durable `editState`),
2426
+ * committing any active inline element editor first.
2427
+ */
2428
+ save() {
2429
+ this._flushActiveEditingIfNeeded();
2430
+ return this._pdfModel.save();
2431
+ }
2432
+ /**
2433
+ * Triggers the configured `IPdfIoAdapter.onSave` hook to persist the snapshot to a backend host.
2434
+ * Returns `true` if a host save hook was executed, or `false` if none was configured.
2435
+ */
2436
+ async saveToHost() {
2437
+ return this._injector.get(import_univer_pdfs4.IPdfIoService).saveToHost({
2438
+ unitId: this.getId(),
2439
+ snapshot: this.save()
2440
+ });
2441
+ }
2442
+ getActivePageId() {
2443
+ return this._injector.get(import_univer_pdfs4.IPdfSelectionService).getActivePageId();
2444
+ }
2445
+ setActivePage(pageId) {
2446
+ this._injector.get(import_univer_pdfs4.IPdfSelectionService).setActivePage(pageId);
2447
+ }
2448
+ setPageSize(pageSize) {
2449
+ return this._commandService.syncExecuteCommand(import_univer_pdfs4.SetPdfPageSizeCommand.id, {
2450
+ unitId: this.getId(),
2451
+ pageSize
2452
+ });
2453
+ }
2454
+ addPage(page) {
2455
+ return this._commandService.syncExecuteCommand(import_univer_pdfs4.AddPdfPageCommand.id, {
2456
+ unitId: this.getId(),
2457
+ page
2458
+ });
2459
+ }
2460
+ addElement(elementType, element, pageId) {
2461
+ return this._commandService.syncExecuteCommand(import_univer_pdfs4.AddPdfElementCommand.id, {
2462
+ unitId: this.getId(),
2463
+ pageId,
2464
+ elementType,
2465
+ element
2466
+ });
2467
+ }
2468
+ updateElement(elementId, patch, pageId) {
2469
+ return this._commandService.syncExecuteCommand(import_univer_pdfs4.UpdatePdfElementsCommand.id, {
2470
+ unitId: this.getId(),
2471
+ pageId,
2472
+ updates: [{ id: elementId, patch }]
2473
+ });
2474
+ }
2475
+ deleteElements(elementIds, pageId) {
2476
+ return this._commandService.syncExecuteCommand(import_univer_pdfs4.DeleteSelectedPdfElementsCommand.id, {
2477
+ unitId: this.getId(),
2478
+ pageId,
2479
+ elementIds
2480
+ });
2481
+ }
2482
+ /**
2483
+ * Distributes 3+ selected (or explicitly listed) unlocked elements with equal spacing
2484
+ * along the `'horizontal'` or `'vertical'` axis (Undo/Redo-safe).
2485
+ */
2486
+ distributeElements(direction, elementIds, pageId) {
2487
+ return this._commandService.syncExecuteCommand(import_univer_pdfs4.DistributeSelectedPdfElementsCommand.id, {
2488
+ unitId: this.getId(),
2489
+ pageId,
2490
+ direction,
2491
+ elementIds
2492
+ });
2493
+ }
2494
+ /**
2495
+ * Generates a `1mm / 5mm / 10mm` millimeter calibration ruler & crosshair test-sheet PDF
2496
+ * matching this document's paper size (or an explicit `pageSize` override).
2497
+ */
2498
+ async exportCalibrationGridPdf(pageSize) {
2499
+ return (0, import_univer_pdfs4.exportCalibrationGridPdfBytes)(pageSize ?? this.getDocument().pageSize);
2500
+ }
2501
+ /**
2502
+ * Exports a tamper-evident PDF binary embedded with a deterministic SHA-256 cryptographic audit seal.
2503
+ */
2504
+ async exportSignedPdf(sealOptions, data) {
2505
+ return (0, import_univer_pdfs4.exportSignedPdfWithAuditSeal)(this.save(), data, sealOptions);
2506
+ }
2507
+ /**
2508
+ * Verifies the SHA-256 cryptographic audit seal and page content stream integrity of a signed PDF binary.
2509
+ */
2510
+ async verifySignedPdf(pdfBytes) {
2511
+ return (0, import_univer_pdfs4.verifyPdfAuditSeal)(pdfBytes);
2512
+ }
2513
+ /**
2514
+ * Validates required template variables across all pages of this PDF document against `data`.
2515
+ */
2516
+ validateVariables(data) {
2517
+ return (0, import_univer_pdfs4.validatePdfTemplateVariables)(this.save(), data);
2518
+ }
2519
+ loadSnapshot(snapshot) {
2520
+ return this._commandService.syncExecuteCommand(import_univer_pdfs4.ReplacePdfSnapshotCommand.id, {
2521
+ unitId: this.getId(),
2522
+ snapshot
2523
+ });
2524
+ }
2525
+ getIoCapabilities() {
2526
+ return this._injector.get(import_univer_pdfs4.IPdfIoService).getIoCapabilities();
2527
+ }
2528
+ async importPdfFile(file, options) {
2529
+ const ioService = this._injector.get(import_univer_pdfs4.IPdfIoService);
2530
+ const outcome = await ioService.importPdf(file, {
2531
+ unitId: this.getId(),
2532
+ snapshot: this.save(),
2533
+ target: options?.target
2534
+ });
2535
+ if (outcome.mode === "snapshot") {
2536
+ this.loadSnapshot(outcome.snapshot);
2537
+ } else {
2538
+ this._commandService.syncExecuteCommand(import_univer_pdfs4.ImportPdfSourceCommand.id, {
2539
+ unitId: this.getId(),
2540
+ sourceDocumentRef: outcome.sourceDocumentRef,
2541
+ pageSizes: outcome.pageSizes
2542
+ });
2543
+ }
2544
+ return outcome;
2545
+ }
2546
+ /**
2547
+ * Generates standard PDF binary bytes (`Uint8Array`) with optional dynamic dataset data and export options.
2548
+ * Supports explicit per-operation `options.target` (`'browser' | 'server' | 'auto'`) without mutating adapter state.
2549
+ */
2550
+ async exportPdf(data, options) {
2551
+ return this._injector.get(import_univer_pdfs4.IPdfIoService).exportPdf({
2552
+ unitId: this.getId(),
2553
+ snapshot: this.save(),
2554
+ data,
2555
+ options,
2556
+ target: options?.target
2557
+ });
2558
+ }
2559
+ /**
2560
+ * Exports standard PDF bytes with interactive `AcroForm` widgets (`PDFTextField`, `PDFCheckBox`,
2561
+ * `PDFRadioGroup`, `PDFDropdown`) enabled.
2562
+ */
2563
+ async exportInteractiveFormPdf(data, options) {
2564
+ const snap = this.save();
2565
+ const mergedOptions = {
2566
+ ...options,
2567
+ interactiveForm: true
2568
+ };
2569
+ const ioService = this._injector.get(import_univer_pdfs4.IPdfIoService);
2570
+ const cancelled = ioService.runBeforeExportHooks({
2571
+ unitId: this.getId(),
2572
+ snapshot: snap,
2573
+ data,
2574
+ options: mergedOptions,
2575
+ cancel: false
2576
+ });
2577
+ if (cancelled) {
2578
+ throw new import_core3.CanceledError();
2579
+ }
2580
+ const bytes = await (0, import_univer_pdfs4.exportPdfBytes)(snap, data, mergedOptions);
2581
+ ioService.notifyExported({
2582
+ unitId: this.getId(),
2583
+ bytes,
2584
+ byteLength: bytes.byteLength,
2585
+ options: mergedOptions
2586
+ });
2587
+ return bytes;
2588
+ }
2589
+ /**
2590
+ * Extracts user-filled `AcroForm` field values from an interactive PDF binary and populates them
2591
+ * into the current `FPdf` document snapshot (undoable).
2592
+ */
2593
+ async importAcroFormValues(pdfBytes) {
2594
+ const values = await (0, import_univer_pdfs4.extractAcroFormValuesFromPdfBytes)(pdfBytes);
2595
+ if (Object.keys(values).length > 0) {
2596
+ this.fillFormValues(values);
2597
+ }
2598
+ return values;
2599
+ }
2600
+ /**
2601
+ * Dispatches silent hardware printing via the configured `IPdfIoAdapter.onSilentPrint` bridge
2602
+ * (e.g. Lodop / QZ-Tray / Yudao Print Agent). Throws `PdfIoTargetError` if unconfigured.
2603
+ */
2604
+ async silentPrint(options) {
2605
+ return this._injector.get(import_univer_pdfs4.IPdfIoService).silentPrint({
2606
+ unitId: this.getId(),
2607
+ snapshot: this.save(),
2608
+ options
2609
+ });
2610
+ }
2611
+ /**
2612
+ * Generates a millimeter-aligned receipt/waybill/voucher template from a natural-language prompt
2613
+ * via `IPdfAiCopilotAdapter` (or built-in smart millimeter layout engine) and applies it to this document.
2614
+ */
2615
+ async generateTemplateByAi(prompt) {
2616
+ const generated = await this._injector.get(import_univer_pdfs4.IPdfIoService).generateTemplateByAi(prompt);
2617
+ const nextSnapshot = {
2618
+ ...generated,
2619
+ id: this.getId()
2620
+ };
2621
+ this.loadSnapshot(nextSnapshot);
2622
+ return this.save();
2623
+ }
2624
+ toPdfmeTemplate() {
2625
+ return (0, import_univer_pdfs4.toPdfmeTemplate)(this.save());
2626
+ }
2627
+ loadPdfmeTemplate(template) {
2628
+ const snapshot = (0, import_univer_pdfs4.fromPdfmeTemplate)(template, { id: this.getId(), name: this.getName() });
2629
+ return this.loadSnapshot(snapshot);
2630
+ }
2631
+ getInteractionMode() {
2632
+ return this._injector.get(import_univer_pdfs4.IPdfSelectionService).getInteractionMode();
2633
+ }
2634
+ setInteractionMode(mode) {
2635
+ this._injector.get(import_univer_pdfs4.IPdfSelectionService).setInteractionMode(mode);
2636
+ }
2637
+ getFormValues() {
2638
+ return (0, import_univer_pdfs4.extractPdfFormValues)(this.save());
2639
+ }
2640
+ fillFormValues(values) {
2641
+ const filled = (0, import_univer_pdfs4.fillPdfFormValues)(this.save(), values);
2642
+ return this.loadSnapshot(filled);
2643
+ }
2644
+ async exportBatchPdf(records, options) {
2645
+ const snap = this.save();
2646
+ const ioService = this._injector.get(import_univer_pdfs4.IPdfIoService);
2647
+ const cancelled = ioService.runBeforeExportHooks({
2648
+ unitId: this.getId(),
2649
+ snapshot: snap,
2650
+ options,
2651
+ cancel: false
2652
+ });
2653
+ if (cancelled) {
2654
+ throw new import_core3.CanceledError();
2655
+ }
2656
+ const bytes = await (0, import_univer_pdfs4.exportBatchPdfBytes)(snap, records, options);
2657
+ ioService.notifyExported({
2658
+ unitId: this.getId(),
2659
+ bytes,
2660
+ byteLength: bytes.byteLength,
2661
+ options
2662
+ });
2663
+ return bytes;
2664
+ }
2665
+ saveVersion(label) {
2666
+ return this._injector.get(import_univer_pdfs4.IPdfSelectionService).saveVersionSnapshot(this.getId(), label);
2667
+ }
2668
+ getVersions() {
2669
+ return this._injector.get(import_univer_pdfs4.IPdfSelectionService).listVersionSnapshots(this.getId());
2670
+ }
2671
+ restoreVersion(versionId) {
2672
+ return this._commandService.syncExecuteCommand(import_univer_pdfs4.RestorePdfVersionCommand.id, {
2673
+ unitId: this.getId(),
2674
+ versionId
2675
+ });
2676
+ }
2677
+ /**
2678
+ * Loads an imported base PDF (`Uint8Array` or Base64 / Data URI string), extracts all native text spans
2679
+ * across pages, and stores both the base PDF background and `nativeTextSpansByPage` undoably.
2680
+ */
2681
+ async loadBasePdfWithNativeText(pdfBytes) {
2682
+ const normalized = typeof pdfBytes === "string" ? base64OrDataUriToBytesSafe(pdfBytes) : {
2683
+ bytes: pdfBytes,
2684
+ dataUri: `data:application/pdf;base64,${bytesToBase64Safe(pdfBytes)}`
2685
+ };
2686
+ const doc = await import_pdf_lib.PDFDocument.load(normalized.bytes, { ignoreEncryption: true });
2687
+ const pages = doc.getPages();
2688
+ const pageSizes = pages.length > 0 ? pages.map((p) => {
2689
+ const { width, height } = p.getSize();
2690
+ return { width, height, preset: "CUSTOM" };
2691
+ }) : [{ ...this.getDocument().pageSize }];
2692
+ const existingOrder = this._pdfModel.getPageOrder();
2693
+ const targetPageIds = pageSizes.map((_, idx) => existingOrder[idx] || `page-${(0, import_core3.generateRandomId)(6)}`);
2694
+ const nativeTextSpansByPage = await (0, import_univer_pdfs4.extractNativeTextSpansFromPdfBytes)(normalized.bytes, targetPageIds);
2695
+ this._commandService.syncExecuteCommand(import_univer_pdfs4.SetPdfNativeTextSpansCommand.id, {
2696
+ unitId: this.getId(),
2697
+ sourceDocumentRef: {
2698
+ id: `src-${(0, import_core3.generateRandomId)(6)}`,
2699
+ fileName: "base-document.pdf",
2700
+ mimeType: "application/pdf",
2701
+ dataUri: normalized.dataUri,
2702
+ pageCount: pageSizes.length
2703
+ },
2704
+ pageSizes,
2705
+ targetPageIds,
2706
+ nativeTextSpansByPage
2707
+ });
2708
+ return this.getNativeTextSpans();
2709
+ }
2710
+ /**
2711
+ * Returns non-suppressed native text spans extracted from the base PDF (filtered by `pageId` when provided).
2712
+ */
2713
+ getNativeTextSpans(pageId) {
2714
+ const snap = this.save();
2715
+ const spansByPage = snap.metadata?.nativeTextSpansByPage ?? snap.editState.nativeTextSpansByPage ?? {};
2716
+ const suppressedSet = new Set(snap.editState.suppressedSourceIds ?? []);
2717
+ if (pageId) {
2718
+ return (spansByPage[pageId] ?? []).filter((s) => !s.suppressed && !suppressedSet.has(s.id)).map((s) => import_core3.Tools.deepClone(s));
2719
+ }
2720
+ const all = [];
2721
+ for (const pid of snap.document.pageOrder) {
2722
+ for (const s of spansByPage[pid] ?? []) {
2723
+ if (!s.suppressed && !suppressedSet.has(s.id)) {
2724
+ all.push(import_core3.Tools.deepClone(s));
2725
+ }
2726
+ }
2727
+ }
2728
+ return all;
2729
+ }
2730
+ /**
2731
+ * Atomically suppresses a native base-PDF text span, covers its original bounding box,
2732
+ * and inserts an editable `TEXT` element at the exact `{ left, top, width, height }`, returning the new element ID.
2733
+ */
2734
+ replaceNativeText(spanId, newText, style) {
2735
+ const newElementId = `el-${(0, import_core3.generateRandomId)(6)}`;
2736
+ const ok = this._commandService.syncExecuteCommand(import_univer_pdfs4.ReplacePdfNativeTextCommand.id, {
2737
+ unitId: this.getId(),
2738
+ spanId,
2739
+ newText,
2740
+ style,
2741
+ newElementId
2742
+ });
2743
+ return ok ? newElementId : null;
2744
+ }
2745
+ /**
2746
+ * Searches and replaces text across all `TEXT` elements and (by default) native base-PDF text spans
2747
+ * in a single undoable operation, returning the total replacement count.
2748
+ */
2749
+ findAndReplaceText(query, replacement, options) {
2750
+ let replacedCount = 0;
2751
+ this._commandService.syncExecuteCommand(import_univer_pdfs4.FindAndReplacePdfTextCommand.id, {
2752
+ unitId: this.getId(),
2753
+ query,
2754
+ replacement,
2755
+ matchCase: options?.matchCase,
2756
+ includeNativeText: options?.includeNativeText,
2757
+ onResult: (count) => {
2758
+ replacedCount = count;
2759
+ }
2760
+ });
2761
+ return replacedCount;
2762
+ }
2763
+ /**
2764
+ * Inserts a review annotation (`highlight`, `underline`, `strikeout`, `squiggly`, or `stickyNote`)
2765
+ * onto `pageId` (Undo/Redo-safe) and returns its created element ID.
2766
+ */
2767
+ insertAnnotation(pageId, spec) {
2768
+ if (!this._pdfModel.getPage(pageId)) return null;
2769
+ const elementId = spec.id || `annot-${(0, import_core3.generateRandomId)(6)}`;
2770
+ const isSticky = spec.annotationType === "stickyNote";
2771
+ const transform = spec.transform ?? {
2772
+ left: spec.left ?? 72,
2773
+ top: spec.top ?? 72,
2774
+ width: spec.width ?? (isSticky ? 28 : 160),
2775
+ height: spec.height ?? (isSticky ? 28 : 22),
2776
+ angle: 0
2777
+ };
2778
+ const ok = this._commandService.syncExecuteCommand(import_univer_pdfs4.AddPdfElementCommand.id, {
2779
+ unitId: this.getId(),
2780
+ pageId,
2781
+ elementType: import_univer_pdfs4.PdfElementType.ANNOTATION,
2782
+ element: {
2783
+ ...spec,
2784
+ id: elementId,
2785
+ type: import_univer_pdfs4.PdfElementType.ANNOTATION,
2786
+ transform
2787
+ }
2788
+ });
2789
+ return ok ? elementId : null;
2790
+ }
2791
+ /**
2792
+ * Appends a threaded reply to an existing review annotation (Undo/Redo-safe).
2793
+ */
2794
+ addAnnotationReply(pageId, elementId, reply) {
2795
+ const existing = this._pdfModel.getElement(pageId, elementId);
2796
+ if (!existing || existing.type !== import_univer_pdfs4.PdfElementType.ANNOTATION) return null;
2797
+ const builtReply = {
2798
+ id: reply.id || `reply-${(0, import_core3.generateRandomId)(6)}`,
2799
+ author: reply.author || "Reviewer",
2800
+ content: reply.content,
2801
+ createdAt: reply.createdAt || (/* @__PURE__ */ new Date()).toISOString()
2802
+ };
2803
+ const ok = this._commandService.syncExecuteCommand(import_univer_pdfs4.UpdatePdfElementsCommand.id, {
2804
+ unitId: this.getId(),
2805
+ pageId,
2806
+ updates: [
2807
+ {
2808
+ id: elementId,
2809
+ patch: {
2810
+ replies: [...existing.replies ?? [], builtReply]
2811
+ }
2812
+ }
2813
+ ]
2814
+ });
2815
+ return ok ? builtReply : null;
2816
+ }
2817
+ /**
2818
+ * Updates the review workflow status (`open` | `accepted` | `rejected` | `resolved`) of an annotation (Undo/Redo-safe).
2819
+ */
2820
+ setAnnotationStatus(pageId, elementId, status) {
2821
+ const existing = this._pdfModel.getElement(pageId, elementId);
2822
+ if (!existing || existing.type !== import_univer_pdfs4.PdfElementType.ANNOTATION) return false;
2823
+ return this._commandService.syncExecuteCommand(import_univer_pdfs4.UpdatePdfElementsCommand.id, {
2824
+ unitId: this.getId(),
2825
+ pageId,
2826
+ updates: [
2827
+ {
2828
+ id: elementId,
2829
+ patch: { status }
2830
+ }
2831
+ ]
2832
+ });
2833
+ }
2834
+ /**
2835
+ * Returns all review annotations across `pageId` (or all pages in `pageOrder` when omitted).
2836
+ */
2837
+ getAnnotations(pageId) {
2838
+ const targetPageIds = pageId ? [pageId] : this._pdfModel.getPageOrder();
2839
+ const out = [];
2840
+ for (const pid of targetPageIds) {
2841
+ for (const el of this._pdfModel.getPageElementsOrdered(pid)) {
2842
+ if (!el.hidden && el.type === import_univer_pdfs4.PdfElementType.ANNOTATION) {
2843
+ out.push(import_core3.Tools.deepClone(el));
2844
+ }
2845
+ }
2846
+ }
2847
+ return out;
2848
+ }
2849
+ /**
2850
+ * Inserts a permanent redaction blackout box onto `pageId` (Undo/Redo-safe), which draws an opaque
2851
+ * redaction cover and strips intersecting `TEXT` / native base-PDF text on PDF export.
2852
+ */
2853
+ insertRedaction(pageId, rect, overlayLabel, fillColor) {
2854
+ if (!this._pdfModel.getPage(pageId)) return null;
2855
+ const elementId = `redact-${(0, import_core3.generateRandomId)(6)}`;
2856
+ const ok = this._commandService.syncExecuteCommand(import_univer_pdfs4.AddPdfElementCommand.id, {
2857
+ unitId: this.getId(),
2858
+ pageId,
2859
+ elementType: import_univer_pdfs4.PdfElementType.REDACTION,
2860
+ element: {
2861
+ id: elementId,
2862
+ type: import_univer_pdfs4.PdfElementType.REDACTION,
2863
+ fillColor: fillColor ?? "#000000",
2864
+ overlayLabel: overlayLabel ?? "[CONFIDENTIAL]",
2865
+ transform: {
2866
+ left: rect.left,
2867
+ top: rect.top,
2868
+ width: rect.width,
2869
+ height: rect.height,
2870
+ angle: 0
2871
+ }
2872
+ }
2873
+ });
2874
+ return ok ? elementId : null;
2875
+ }
2876
+ /**
2877
+ * Sets clockwise page rotation (`0 | 90 | 180 | 270`) on `pageId` (Undo/Redo-safe).
2878
+ */
2879
+ rotatePage(pageId, rotation) {
2880
+ return this._commandService.syncExecuteCommand(import_univer_pdfs4.RotatePdfPageCommand.id, {
2881
+ unitId: this.getId(),
2882
+ pageId,
2883
+ rotation
2884
+ });
2885
+ }
2886
+ /**
2887
+ * Reorders document pages according to `newPageOrder` (Undo/Redo-safe).
2888
+ */
2889
+ reorderPages(newPageOrder) {
2890
+ return this._commandService.syncExecuteCommand(import_univer_pdfs4.ReorderPdfPagesCommand.id, {
2891
+ unitId: this.getId(),
2892
+ pageOrder: newPageOrder
2893
+ });
2894
+ }
2895
+ /**
2896
+ * Sets or clears the page `CropBox` (`{ left, top, width, height }` in pt) on `pageId` (Undo/Redo-safe).
2897
+ */
2898
+ setPageCropBox(pageId, cropBox) {
2899
+ return this._commandService.syncExecuteCommand(import_univer_pdfs4.SetPdfPageCropBoxCommand.id, {
2900
+ unitId: this.getId(),
2901
+ pageId,
2902
+ cropBox
2903
+ });
2904
+ }
2905
+ /**
2906
+ * Exports a 1-based inclusive page range `[startPage..endPage]` of this document as standard PDF bytes.
2907
+ */
2908
+ async exportPageRangePdfBytes(startPage, endPage, data, options) {
2909
+ const fullBytes = await this.exportPdf(data, options);
2910
+ const [rangeBytes] = await (0, import_univer_pdfs4.splitPdfBytes)(fullBytes, [{ startPage, endPage }]);
2911
+ return rangeBytes;
2912
+ }
2913
+ /**
2914
+ * Configures navigable PDF `/Outlines` bookmarks tree on this document (Undo/Redo-safe).
2915
+ */
2916
+ setBookmarks(bookmarks) {
2917
+ return this._commandService.syncExecuteCommand(import_univer_pdfs4.SetPdfBookmarksCommand.id, {
2918
+ unitId: this.getId(),
2919
+ bookmarks
2920
+ });
2921
+ }
2922
+ /**
2923
+ * Returns the configured PDF `/Outlines` bookmarks tree.
2924
+ */
2925
+ getBookmarks() {
2926
+ return import_core3.Tools.deepClone(this.save().metadata?.bookmarks ?? []);
2927
+ }
2928
+ /**
2929
+ * Configures or clears legal/archive Bates numbering (`metadata.batesConfig`, Undo/Redo-safe).
2930
+ */
2931
+ setBatesConfig(batesConfig) {
2932
+ return this._commandService.syncExecuteCommand(import_univer_pdfs4.SetPdfBatesConfigCommand.id, {
2933
+ unitId: this.getId(),
2934
+ batesConfig
2935
+ });
2936
+ }
2937
+ /**
2938
+ * Returns the current Bates numbering configuration, if any.
2939
+ */
2940
+ getBatesConfig() {
2941
+ const cfg = this.save().metadata?.batesConfig;
2942
+ return cfg ? import_core3.Tools.deepClone(cfg) : void 0;
2943
+ }
2944
+ // =========================================================================
2945
+ // Wave 2: Named PDF Layers (`/OCProperties`), Header/Footer & Watermark
2946
+ // =========================================================================
2947
+ /**
2948
+ * Adds a named Optional Content Group (`/OCProperties`) layer (Undo/Redo-safe).
2949
+ */
2950
+ addLayer(layer) {
2951
+ const spec = typeof layer === "string" ? { name: layer } : layer;
2952
+ let created = null;
2953
+ this._commandService.syncExecuteCommand(import_univer_pdfs4.AddPdfLayerCommand.id, {
2954
+ unitId: this.getId(),
2955
+ layer: spec,
2956
+ onCreated: (l) => {
2957
+ created = l;
2958
+ }
2959
+ });
2960
+ return created;
2961
+ }
2962
+ /**
2963
+ * Updates `visible`, `locked`, `printable`, or `name` on an existing PDF layer (Undo/Redo-safe).
2964
+ */
2965
+ updateLayer(layerId, patch) {
2966
+ return this._commandService.syncExecuteCommand(import_univer_pdfs4.UpdatePdfLayerCommand.id, {
2967
+ unitId: this.getId(),
2968
+ layerId,
2969
+ patch
2970
+ });
2971
+ }
2972
+ /**
2973
+ * Removes a named PDF layer and unassigns elements referencing it (Undo/Redo-safe).
2974
+ */
2975
+ removeLayer(layerId) {
2976
+ return this._commandService.syncExecuteCommand(import_univer_pdfs4.RemovePdfLayerCommand.id, {
2977
+ unitId: this.getId(),
2978
+ layerId
2979
+ });
2980
+ }
2981
+ /**
2982
+ * Lists all named PDF Optional Content Group layers on this document.
2983
+ */
2984
+ getLayers() {
2985
+ return this._pdfModel.getLayers();
2986
+ }
2987
+ /**
2988
+ * Assigns one or more elements to `layerId` (or clears assignment when `layerId` is undefined, Undo/Redo-safe).
2989
+ */
2990
+ assignElementLayer(elementIdOrIds, layerId, pageId) {
2991
+ const elementIds = Array.isArray(elementIdOrIds) ? elementIdOrIds : [elementIdOrIds];
2992
+ return this._commandService.syncExecuteCommand(import_univer_pdfs4.AssignPdfElementLayerCommand.id, {
2993
+ unitId: this.getId(),
2994
+ pageId,
2995
+ elementIds,
2996
+ layerId
2997
+ });
2998
+ }
2999
+ setHeaderFooterConfig(headerFooterConfig) {
3000
+ return this._commandService.syncExecuteCommand(import_univer_pdfs4.SetPdfHeaderFooterConfigCommand.id, {
3001
+ unitId: this.getId(),
3002
+ headerFooterConfig
3003
+ });
3004
+ }
3005
+ getHeaderFooterConfig() {
3006
+ const cfg = this.save().metadata?.headerFooterConfig;
3007
+ return cfg ? import_core3.Tools.deepClone(cfg) : void 0;
3008
+ }
3009
+ setWatermarkConfig(watermarkConfig) {
3010
+ return this._commandService.syncExecuteCommand(import_univer_pdfs4.SetPdfWatermarkConfigCommand.id, {
3011
+ unitId: this.getId(),
3012
+ watermarkConfig
3013
+ });
3014
+ }
3015
+ getWatermarkConfig() {
3016
+ const cfg = this.save().metadata?.watermarkConfig;
3017
+ return cfg ? import_core3.Tools.deepClone(cfg) : void 0;
3018
+ }
3019
+ // =========================================================================
3020
+ // Wave 2: Comparison, AcroForm Importer/Auto-Detect, Calculation & XFDF/FDF
3021
+ // =========================================================================
3022
+ /**
3023
+ * Compares this PDF document against another `IPdfDocumentData` snapshot or `FPdf` instance.
3024
+ */
3025
+ compareWith(other) {
3026
+ const otherSnap = other instanceof FPdf ? other.save() : other;
3027
+ return (0, import_univer_pdfs4.comparePdfUnits)(this.save(), otherSnap);
3028
+ }
3029
+ /**
3030
+ * Imports an existing interactive AcroForm PDF binary into this unit as editable form fields + `basePdf` (Undo/Redo-safe).
3031
+ */
3032
+ async importAcroFormPdf(pdfBytes, options) {
3033
+ const imported = await (0, import_univer_pdfs4.importAcroFormPdfToUnit)(pdfBytes, {
3034
+ unitId: this.getId(),
3035
+ title: options?.title ?? this.getName()
3036
+ });
3037
+ this.loadSnapshot(imported);
3038
+ return this.save();
3039
+ }
3040
+ /**
3041
+ * Auto-detects form fields on `pageIndex` (default `0` or active page) from native text labels
3042
+ * ending with `:` / `:` or `____` underlines (Undo/Redo-safe).
3043
+ */
3044
+ autoDetectFormFields(pageIndex) {
3045
+ const snap = this.save();
3046
+ const activeId = this.getActivePageId();
3047
+ const resolvedIdx = pageIndex !== void 0 ? pageIndex : activeId ? Math.max(0, snap.document.pageOrder.indexOf(activeId)) : 0;
3048
+ const detected = (0, import_univer_pdfs4.detectFormFieldsFromPageSpans)(snap, resolvedIdx);
3049
+ if (detected.length === 0) return [];
3050
+ const updated = (0, import_univer_pdfs4.autoDetectFormFieldsOnPage)(snap, resolvedIdx);
3051
+ this.loadSnapshot(updated);
3052
+ return detected;
3053
+ }
3054
+ /**
3055
+ * Evaluates all `calcExpression` formulas across named PDF form fields (Undo/Redo-safe).
3056
+ */
3057
+ recalculateFormFields() {
3058
+ const recalculated = (0, import_univer_pdfs4.recalculatePdfFormFields)(this.save());
3059
+ this.loadSnapshot(recalculated);
3060
+ return (0, import_univer_pdfs4.extractPdfFormValues)(this.save());
3061
+ }
3062
+ /**
3063
+ * Validates `required` and `validationPattern` constraints across all PDF form fields.
3064
+ */
3065
+ validateFormFields() {
3066
+ return (0, import_univer_pdfs4.validatePdfFormFields)(this.save());
3067
+ }
3068
+ exportFormDataToXfdf() {
3069
+ return (0, import_univer_pdfs4.exportFormDataToXfdf)(this.save());
3070
+ }
3071
+ importFormDataFromXfdf(xfdfXml) {
3072
+ const next = (0, import_univer_pdfs4.importFormDataFromXfdf)(this.save(), xfdfXml);
3073
+ return this.loadSnapshot(next);
3074
+ }
3075
+ exportFormDataToFdf() {
3076
+ return (0, import_univer_pdfs4.exportFormDataToFdf)(this.save());
3077
+ }
3078
+ importFormDataFromFdf(fdfContent) {
3079
+ const next = (0, import_univer_pdfs4.importFormDataFromFdf)(this.save(), fdfContent);
3080
+ return this.loadSnapshot(next);
3081
+ }
3082
+ // =========================================================================
3083
+ // Wave 2: OCR SPI, Word/Sheet Conversion, Sanitization, Attachments & Signing
3084
+ // =========================================================================
3085
+ registerOcrAdapter(adapter) {
3086
+ this._injector.get(import_univer_pdfs4.IPdfIoService).setOcrAdapter(adapter);
3087
+ }
3088
+ /**
3089
+ * Runs the registered `IPdfOcrAdapter` on `pageIndex` in either `'searchable'` (`3 Tr` invisible text)
3090
+ * or `'editable'` (`PdfElementType.TEXT` boxes) mode with full Undo/Redo support.
3091
+ */
3092
+ async applyOcrToPage(pageIndex, mode, adapter) {
3093
+ const activeAdapter = adapter ?? this._injector.get(import_univer_pdfs4.IPdfIoService).getOcrAdapter() ?? void 0;
3094
+ const { unit: nextUnit, blocks } = await (0, import_univer_pdfs4.applyOcrToUnitPage)(this.save(), pageIndex, mode, activeAdapter);
3095
+ this.loadSnapshot(nextUnit);
3096
+ return blocks;
3097
+ }
3098
+ exportToDocxSnapshot() {
3099
+ return (0, import_univer_pdfs4.exportPdfToDocxSnapshot)(this.save());
3100
+ }
3101
+ exportToWorkbookSnapshot() {
3102
+ return (0, import_univer_pdfs4.exportPdfToWorkbookSnapshot)(this.save());
3103
+ }
3104
+ async exportToDocxBytes() {
3105
+ return (0, import_univer_pdfs4.convertPdfBytesToDocxBytes)(this.save());
3106
+ }
3107
+ exportToCsv() {
3108
+ return (0, import_univer_pdfs4.convertPdfUnitToCsv)(this.save());
3109
+ }
3110
+ sanitize(options) {
3111
+ const sanitized = (0, import_univer_pdfs4.sanitizePdfUnit)(this.save(), options);
3112
+ this.loadSnapshot(sanitized);
3113
+ return this.save();
3114
+ }
3115
+ optimize(options) {
3116
+ const optimized = (0, import_univer_pdfs4.optimizePdfUnit)(this.save(), options);
3117
+ this.loadSnapshot(optimized);
3118
+ return this.save();
3119
+ }
3120
+ getAttachments() {
3121
+ const snap = this.save();
3122
+ return import_core3.Tools.deepClone(snap.attachments ?? snap.metadata?.attachments ?? []);
3123
+ }
3124
+ setAttachments(attachments) {
3125
+ return this._commandService.syncExecuteCommand(import_univer_pdfs4.SetPdfAttachmentsCommand.id, {
3126
+ unitId: this.getId(),
3127
+ attachments
3128
+ });
3129
+ }
3130
+ addAttachment(spec) {
3131
+ const built = {
3132
+ id: spec.id || `att-${(0, import_core3.generateRandomId)(6)}`,
3133
+ fileName: spec.fileName,
3134
+ mimeType: spec.mimeType || "application/octet-stream",
3135
+ dataBase64: spec.dataBase64,
3136
+ ...spec.description ? { description: spec.description } : {}
3137
+ };
3138
+ const next = [...this.getAttachments().filter((a) => a.id !== built.id), built];
3139
+ return this.setAttachments(next) ? built : null;
3140
+ }
3141
+ removeAttachment(attachmentId) {
3142
+ const cur = this.getAttachments();
3143
+ const next = cur.filter((a) => a.id !== attachmentId);
3144
+ if (next.length === cur.length) return false;
3145
+ return this.setAttachments(next);
3146
+ }
3147
+ signWithDigest(signerInfo) {
3148
+ const signed = (0, import_univer_pdfs4.signPdfUnitWithDigest)(this.save(), signerInfo);
3149
+ this.loadSnapshot(signed);
3150
+ return this.save();
3151
+ }
3152
+ verifySignature() {
3153
+ return (0, import_univer_pdfs4.verifyPdfUnitSignature)(this.save());
3154
+ }
3155
+ setSecurityPermissions(securityPermissions) {
3156
+ const next = import_core3.Tools.deepClone(this.save());
3157
+ next.securityPermissions = securityPermissions ? import_core3.Tools.deepClone(securityPermissions) : void 0;
3158
+ next.metadata = {
3159
+ ...next.metadata ?? {},
3160
+ securityPermissions: securityPermissions ? import_core3.Tools.deepClone(securityPermissions) : void 0
3161
+ };
3162
+ return this.loadSnapshot(next);
3163
+ }
3164
+ setComplianceOptions(opts) {
3165
+ const next = import_core3.Tools.deepClone(this.save());
3166
+ if (opts.pdfACompliant !== void 0) {
3167
+ next.pdfACompliant = opts.pdfACompliant;
3168
+ next.metadata = { ...next.metadata ?? {}, pdfACompliant: opts.pdfACompliant };
3169
+ }
3170
+ if (opts.accessibilityTagged !== void 0) {
3171
+ next.accessibilityTagged = opts.accessibilityTagged;
3172
+ next.metadata = { ...next.metadata ?? {}, accessibilityTagged: opts.accessibilityTagged };
3173
+ }
3174
+ return this.loadSnapshot(next);
3175
+ }
3176
+ };
3177
+ FPdf = __decorateClass([
3178
+ __decorateParam(1, (0, import_core3.Inject)(import_core3.Injector)),
3179
+ __decorateParam(2, import_core3.ICommandService)
3180
+ ], FPdf);
3181
+
3182
+ // src/facade/f-univer.ts
3183
+ var import_core4 = require("@univerjs/core");
3184
+ var import_facade3 = require("@univerjs/core/facade");
3185
+ var import_rxjs = require("rxjs");
3186
+ var import_univer_pdfs5 = require("@yudaocode/univer-pdfs");
3187
+ function isBinaryOrSnapshotAppendSource(val) {
3188
+ if (!val || typeof val !== "object") return false;
3189
+ if (val instanceof Uint8Array || val instanceof ArrayBuffer) return true;
3190
+ if (typeof Blob !== "undefined" && val instanceof Blob) return true;
3191
+ if ("document" in val && "editState" in val) return true;
3192
+ return false;
3193
+ }
3194
+ function isFormFieldElement(el) {
3195
+ return el.type === import_univer_pdfs5.PdfElementType.CHECKBOX || el.type === import_univer_pdfs5.PdfElementType.CIRCLE_MARK || el.type === import_univer_pdfs5.PdfElementType.DATE_TIME || el.type === import_univer_pdfs5.PdfElementType.RADIO_GROUP || el.type === import_univer_pdfs5.PdfElementType.SELECT || el.type === import_univer_pdfs5.PdfElementType.SIGNATURE || el.type === import_univer_pdfs5.PdfElementType.TEXT && Boolean(el.formFieldName || el.fieldKey || el.bindingField);
3196
+ }
3197
+ function readElementFormValue(el) {
3198
+ if (el.type === import_univer_pdfs5.PdfElementType.CHECKBOX || el.type === import_univer_pdfs5.PdfElementType.CIRCLE_MARK) {
3199
+ return Boolean(el.checked);
3200
+ }
3201
+ if (el.type === import_univer_pdfs5.PdfElementType.DATE_TIME || el.type === import_univer_pdfs5.PdfElementType.RADIO_GROUP || el.type === import_univer_pdfs5.PdfElementType.SELECT) {
3202
+ return el.value ?? "";
3203
+ }
3204
+ if (el.type === import_univer_pdfs5.PdfElementType.SIGNATURE) {
3205
+ return el.signatureDataUri || el.signerName || "";
3206
+ }
3207
+ if (el.type === import_univer_pdfs5.PdfElementType.TEXT) {
3208
+ return el.content ?? "";
3209
+ }
3210
+ return void 0;
3211
+ }
3212
+ var FUniverPdfsMixin = class extends import_facade3.FUniver {
3213
+ _getFormValuesByUnit() {
3214
+ if (!this._lastFormValuesByUnit) {
3215
+ this._lastFormValuesByUnit = /* @__PURE__ */ new Map();
3216
+ }
3217
+ return this._lastFormValuesByUnit;
3218
+ }
3219
+ _ensurePdfServiceEventWiring(injector = this._injector) {
3220
+ if (this._pdfServiceEventsWired) return;
3221
+ if (!injector.has(import_univer_pdfs5.IPdfIoService) || !injector.has(import_univer_pdfs5.IPdfSelectionService)) return;
3222
+ this._pdfServiceEventsWired = true;
3223
+ const ioService = injector.get(import_univer_pdfs5.IPdfIoService);
3224
+ const selectionService = injector.get(import_univer_pdfs5.IPdfSelectionService);
3225
+ const initialState = selectionService.getState();
3226
+ let prevPageId = initialState.activePageId;
3227
+ let prevSelectedKey = initialState.selectedElementIds.join("\0");
3228
+ const stateSub = selectionService.state$.pipe((0, import_rxjs.skip)(1)).subscribe((state) => {
3229
+ const pdf = (state.unitId ? this.getPdf(state.unitId) : null) ?? this.getActivePdf();
3230
+ if (!pdf) {
3231
+ prevPageId = state.activePageId;
3232
+ prevSelectedKey = state.selectedElementIds.join("\0");
3233
+ return;
3234
+ }
3235
+ if (state.activePageId !== prevPageId) {
3236
+ prevPageId = state.activePageId;
3237
+ this.fireEvent(this.Event.PdfPageChanged, {
3238
+ pdf,
3239
+ unitId: pdf.getId(),
3240
+ pageId: state.activePageId,
3241
+ page: state.activePageId ? pdf.getPageById(state.activePageId) : null
3242
+ });
3243
+ }
3244
+ const nextSelectedKey = state.selectedElementIds.join("\0");
3245
+ if (nextSelectedKey !== prevSelectedKey) {
3246
+ prevSelectedKey = nextSelectedKey;
3247
+ const pageId = state.activePageId ?? pdf.getDocument().pageOrder[0] ?? null;
3248
+ const page = pageId ? pdf.getPageById(pageId) : null;
3249
+ const elements = page ? state.selectedElementIds.map((id) => page.getElementById(id)).filter((item) => item !== null) : [];
3250
+ this.fireEvent(this.Event.PdfElementSelected, {
3251
+ pdf,
3252
+ unitId: pdf.getId(),
3253
+ pageId,
3254
+ elementIds: [...state.selectedElementIds],
3255
+ elements
3256
+ });
3257
+ }
3258
+ });
3259
+ this.disposeWithMe((0, import_core4.toDisposable)(() => stateSub.unsubscribe()));
3260
+ const beforeExpDisp = ioService.registerBeforeExportHook((hookParams) => {
3261
+ const eventParams = {
3262
+ pdf: this.getPdf(hookParams.unitId) ?? void 0,
3263
+ unitId: hookParams.unitId,
3264
+ snapshot: hookParams.snapshot,
3265
+ data: hookParams.data,
3266
+ options: hookParams.options,
3267
+ cancel: false
3268
+ };
3269
+ this.fireEvent(this.Event.BeforePdfExport, eventParams);
3270
+ if (eventParams.cancel) {
3271
+ hookParams.cancel = true;
3272
+ }
3273
+ });
3274
+ this.disposeWithMe(beforeExpDisp);
3275
+ const expSub = ioService.exported$.subscribe((info) => {
3276
+ this.fireEvent(this.Event.PdfExported, {
3277
+ pdf: this.getPdf(info.unitId) ?? void 0,
3278
+ unitId: info.unitId,
3279
+ bytes: info.bytes,
3280
+ byteLength: info.byteLength
3281
+ });
3282
+ });
3283
+ this.disposeWithMe((0, import_core4.toDisposable)(() => expSub.unsubscribe()));
3284
+ const beforePrintDisp = ioService.registerBeforePrintHook((hookParams) => {
3285
+ const eventParams = {
3286
+ pdf: this.getPdf(hookParams.unitId) ?? void 0,
3287
+ unitId: hookParams.unitId,
3288
+ snapshot: hookParams.snapshot,
3289
+ mode: hookParams.mode,
3290
+ options: hookParams.options,
3291
+ cancel: false
3292
+ };
3293
+ this.fireEvent(this.Event.BeforePdfPrint, eventParams);
3294
+ if (eventParams.cancel) {
3295
+ hookParams.cancel = true;
3296
+ }
3297
+ });
3298
+ this.disposeWithMe(beforePrintDisp);
3299
+ }
3300
+ _initialize(injector) {
3301
+ this._ensurePdfServiceEventWiring(injector);
3302
+ const addedSub = this._univerInstanceService.getTypeOfUnitAdded$(import_core4.UniverInstanceType.UNIVER_PDF).subscribe((evtOrModel) => {
3303
+ this._ensurePdfServiceEventWiring(injector);
3304
+ const model = evtOrModel && typeof evtOrModel === "object" && "unit" in evtOrModel ? evtOrModel.unit : evtOrModel;
3305
+ if (!model || typeof model.getUnitId !== "function") return;
3306
+ const unitId = model.getUnitId();
3307
+ this._getFormValuesByUnit().set(unitId, (0, import_univer_pdfs5.extractPdfFormValues)(model.save()));
3308
+ const pdf = injector.createInstance(FPdf, model);
3309
+ this.fireEvent(this.Event.PdfLoaded, {
3310
+ pdf,
3311
+ unitId
3312
+ });
3313
+ });
3314
+ this.disposeWithMe((0, import_core4.toDisposable)(() => addedSub.unsubscribe()));
3315
+ const disposedSub = this._univerInstanceService.getTypeOfUnitDisposed$(import_core4.UniverInstanceType.UNIVER_PDF).subscribe((evtOrModel) => {
3316
+ const model = evtOrModel && typeof evtOrModel === "object" && "unit" in evtOrModel ? evtOrModel.unit : evtOrModel;
3317
+ if (!model || typeof model.getUnitId !== "function") return;
3318
+ const unitId = model.getUnitId();
3319
+ this._getFormValuesByUnit().delete(unitId);
3320
+ this.fireEvent(this.Event.PdfDisposed, {
3321
+ unitId
3322
+ });
3323
+ });
3324
+ this.disposeWithMe((0, import_core4.toDisposable)(() => disposedSub.unsubscribe()));
3325
+ const commandService = injector.get(import_core4.ICommandService);
3326
+ this.disposeWithMe(
3327
+ commandService.onCommandExecuted((cmdInfo) => {
3328
+ if (cmdInfo.id === import_univer_pdfs5.UpdatePdfElementsCommand.id && cmdInfo.params) {
3329
+ const params = cmdInfo.params;
3330
+ const model = params.unitId ? this._univerInstanceService.getUnit(
3331
+ params.unitId,
3332
+ import_core4.UniverInstanceType.UNIVER_PDF
3333
+ ) : this._univerInstanceService.getCurrentUnitOfType(
3334
+ import_core4.UniverInstanceType.UNIVER_PDF
3335
+ );
3336
+ if (!model) return;
3337
+ const unitId = model.getUnitId();
3338
+ const pageId = params.pageId ?? (injector.has(import_univer_pdfs5.IPdfSelectionService) ? injector.get(import_univer_pdfs5.IPdfSelectionService).getActivePageId() : null) ?? model.getPageOrder()[0];
3339
+ if (!pageId) return;
3340
+ const elementsMap = model.getElementsByPage(pageId);
3341
+ const pdf = injector.createInstance(FPdf, model);
3342
+ for (const upd of params.updates ?? []) {
3343
+ const el = elementsMap[upd.id];
3344
+ if (!el || !isFormFieldElement(el)) continue;
3345
+ const p = upd.patch;
3346
+ if (!("checked" in p) && !("value" in p) && !("content" in p) && !("signerName" in p) && !("signatureDataUri" in p)) {
3347
+ continue;
3348
+ }
3349
+ const fieldName = el.formFieldName || el.fieldKey || el.bindingField || el.name || el.id;
3350
+ const value = readElementFormValue(el);
3351
+ const prevMap = this._getFormValuesByUnit().get(unitId) ?? {};
3352
+ prevMap[fieldName] = typeof value === "boolean" ? value : String(value ?? "");
3353
+ this._getFormValuesByUnit().set(unitId, prevMap);
3354
+ this.fireEvent(this.Event.PdfFormFieldChanged, {
3355
+ pdf,
3356
+ unitId,
3357
+ pageId,
3358
+ elementId: el.id,
3359
+ fieldName,
3360
+ value
3361
+ });
3362
+ }
3363
+ } else if (cmdInfo.id === import_univer_pdfs5.ReplacePdfSnapshotCommand.id && cmdInfo.params) {
3364
+ const params = cmdInfo.params;
3365
+ const model = params.unitId ? this._univerInstanceService.getUnit(
3366
+ params.unitId,
3367
+ import_core4.UniverInstanceType.UNIVER_PDF
3368
+ ) : this._univerInstanceService.getCurrentUnitOfType(
3369
+ import_core4.UniverInstanceType.UNIVER_PDF
3370
+ );
3371
+ if (!model) return;
3372
+ const unitId = model.getUnitId();
3373
+ const prevValues = this._getFormValuesByUnit().get(unitId) ?? {};
3374
+ const nextSnap = model.save();
3375
+ const nextValues = (0, import_univer_pdfs5.extractPdfFormValues)(nextSnap);
3376
+ this._getFormValuesByUnit().set(unitId, nextValues);
3377
+ const pdf = injector.createInstance(FPdf, model);
3378
+ for (const pid of nextSnap.document.pageOrder) {
3379
+ const map = nextSnap.editState.elementsByPage[pid] ?? {};
3380
+ for (const el of Object.values(map)) {
3381
+ if (!el || el.hidden || !isFormFieldElement(el)) continue;
3382
+ const fieldName = el.formFieldName || el.fieldKey || el.bindingField || el.name || el.id;
3383
+ if (Object.prototype.hasOwnProperty.call(nextValues, fieldName) && prevValues[fieldName] !== nextValues[fieldName]) {
3384
+ this.fireEvent(this.Event.PdfFormFieldChanged, {
3385
+ pdf,
3386
+ unitId,
3387
+ pageId: pid,
3388
+ elementId: el.id,
3389
+ fieldName,
3390
+ value: nextValues[fieldName]
3391
+ });
3392
+ }
3393
+ }
3394
+ }
3395
+ }
3396
+ })
3397
+ );
3398
+ }
3399
+ createPdf(data, options) {
3400
+ this._ensurePdfServiceEventWiring();
3401
+ const model = this._univerInstanceService.createUnit(
3402
+ import_core4.UniverInstanceType.UNIVER_PDF,
3403
+ data ?? {},
3404
+ options
3405
+ );
3406
+ return this._injector.createInstance(FPdf, model);
3407
+ }
3408
+ getActivePdf() {
3409
+ this._ensurePdfServiceEventWiring();
3410
+ const model = this._univerInstanceService.getCurrentUnitOfType(
3411
+ import_core4.UniverInstanceType.UNIVER_PDF
3412
+ );
3413
+ if (!model) return null;
3414
+ return this._injector.createInstance(FPdf, model);
3415
+ }
3416
+ getPdf(unitId) {
3417
+ this._ensurePdfServiceEventWiring();
3418
+ const model = this._univerInstanceService.getUnit(
3419
+ unitId,
3420
+ import_core4.UniverInstanceType.UNIVER_PDF
3421
+ );
3422
+ if (!model) return null;
3423
+ return this._injector.createInstance(FPdf, model);
3424
+ }
3425
+ setPdfIoAdapter(adapter) {
3426
+ this._ensurePdfServiceEventWiring();
3427
+ this._injector.get(import_univer_pdfs5.IPdfIoService).setAdapter(adapter);
3428
+ }
3429
+ getPdfIoAdapter() {
3430
+ this._ensurePdfServiceEventWiring();
3431
+ return this._injector.get(import_univer_pdfs5.IPdfIoService).getAdapter();
3432
+ }
3433
+ setPdfAiCopilotAdapter(adapter) {
3434
+ this._ensurePdfServiceEventWiring();
3435
+ this._injector.get(import_univer_pdfs5.IPdfIoService).setAiCopilotAdapter(adapter);
3436
+ }
3437
+ getPdfAiCopilotAdapter() {
3438
+ this._ensurePdfServiceEventWiring();
3439
+ return this._injector.get(import_univer_pdfs5.IPdfIoService).getAiCopilotAdapter();
3440
+ }
3441
+ async generateTemplateByAi(prompt, options) {
3442
+ this._ensurePdfServiceEventWiring();
3443
+ const snapshot = await this._injector.get(import_univer_pdfs5.IPdfIoService).generateTemplateByAi(prompt);
3444
+ return this.createPdf(snapshot, options);
3445
+ }
3446
+ registerOcrAdapter(adapter) {
3447
+ this._ensurePdfServiceEventWiring();
3448
+ this._injector.get(import_univer_pdfs5.IPdfIoService).setOcrAdapter(adapter);
3449
+ }
3450
+ async importAcroFormPdf(pdfBytes, options, createOptions) {
3451
+ const snapshot = await (0, import_univer_pdfs5.importAcroFormPdfToUnit)(pdfBytes, options);
3452
+ return this.createPdf(snapshot, createOptions);
3453
+ }
3454
+ async importPdfToSnapshotAsync(source, options) {
3455
+ const imported = await (0, import_univer_pdfs5.importPdfSource)(source, options);
3456
+ if (options?.importAcroForm) {
3457
+ return await (0, import_univer_pdfs5.importAcroFormPdfToUnit)(imported.bytes, {
3458
+ unitId: options.unitId,
3459
+ title: options.fileName || imported.sourceDocumentRef.fileName
3460
+ });
3461
+ }
3462
+ const pageOrder = imported.pageSizes.map((_, idx) => `page-${idx + 1}`);
3463
+ const pages = {};
3464
+ const elementsByPage = {};
3465
+ const elementOrderByPage = {};
3466
+ imported.pageSizes.forEach((sz, idx) => {
3467
+ const pid = pageOrder[idx];
3468
+ pages[pid] = {
3469
+ id: pid,
3470
+ title: `Page ${idx + 1}`,
3471
+ backgroundColor: "#ffffff",
3472
+ sourcePageNumber: idx + 1,
3473
+ pageSize: { ...sz }
3474
+ };
3475
+ elementsByPage[pid] = {};
3476
+ elementOrderByPage[pid] = [];
3477
+ });
3478
+ const nativeTextSpansByPage = options?.extractNativeText !== false ? await (0, import_univer_pdfs5.extractNativeTextSpansFromPdfBytes)(imported.bytes, pageOrder) : void 0;
3479
+ return (0, import_univer_pdfs5.createDefaultPdfUnitData)({
3480
+ id: options?.unitId || `pdf-${(0, import_core4.generateRandomId)(6)}`,
3481
+ name: (options?.fileName || imported.sourceDocumentRef.fileName || "Imported PDF").replace(
3482
+ /\.pdf$/i,
3483
+ ""
3484
+ ),
3485
+ sourceDocumentRef: imported.sourceDocumentRef,
3486
+ document: {
3487
+ pageSize: { ...imported.pageSizes[0] ?? { width: 595.28, height: 841.89 } },
3488
+ pages,
3489
+ pageOrder
3490
+ },
3491
+ editState: {
3492
+ elementsByPage,
3493
+ elementOrderByPage,
3494
+ ...nativeTextSpansByPage ? { nativeTextSpansByPage } : {}
3495
+ },
3496
+ metadata: nativeTextSpansByPage ? { nativeTextSpansByPage } : {}
3497
+ });
3498
+ }
3499
+ async importPdfToUnitIdAsync(source, options) {
3500
+ const snapshot = await this.importPdfToSnapshotAsync(source, options);
3501
+ const pdf = this.createPdf(snapshot, {
3502
+ makeCurrent: options?.makeCurrent ?? true
3503
+ });
3504
+ return pdf.getId();
3505
+ }
3506
+ async exportPdfBySnapshotAsync(snapshot, data, options) {
3507
+ this._ensurePdfServiceEventWiring();
3508
+ if (this._injector.has(import_univer_pdfs5.IPdfIoService)) {
3509
+ const ioService = this._injector.get(import_univer_pdfs5.IPdfIoService);
3510
+ const cancelled = ioService.runBeforeExportHooks({
3511
+ unitId: snapshot.id,
3512
+ snapshot,
3513
+ data,
3514
+ options,
3515
+ cancel: false
3516
+ });
3517
+ if (cancelled) {
3518
+ throw new import_core4.CanceledError();
3519
+ }
3520
+ const bytes = await (0, import_univer_pdfs5.exportPdfBytes)(snapshot, data, options);
3521
+ ioService.notifyExported({
3522
+ unitId: snapshot.id,
3523
+ bytes,
3524
+ byteLength: bytes.byteLength,
3525
+ options
3526
+ });
3527
+ return bytes;
3528
+ }
3529
+ return await (0, import_univer_pdfs5.exportPdfBytes)(snapshot, data, options);
3530
+ }
3531
+ async exportPdfByUnitIdAsync(unitId, data, options) {
3532
+ this._ensurePdfServiceEventWiring();
3533
+ const pdf = this.getPdf(unitId);
3534
+ if (!pdf) {
3535
+ throw new Error(`[UniverPdfs] PDF unit "${unitId}" was not found.`);
3536
+ }
3537
+ return await pdf.exportPdf(data, options);
3538
+ }
3539
+ async appendPdfAsync(arg1, arg2, options) {
3540
+ this._ensurePdfServiceEventWiring();
3541
+ if (arg1 instanceof FPdf) {
3542
+ if (arg2 === void 0) {
3543
+ throw new Error("[UniverPdfs] appendPdfAsync(pdf, source) requires a PDF source.");
3544
+ }
3545
+ return await arg1.appendPdf(arg2, options);
3546
+ }
3547
+ if (isBinaryOrSnapshotAppendSource(arg1)) {
3548
+ const targetUnitId = typeof arg2 === "string" ? arg2 : void 0;
3549
+ const target = targetUnitId ? this.getPdf(targetUnitId) : this.getActivePdf();
3550
+ if (!target) {
3551
+ throw new Error(
3552
+ targetUnitId ? `[UniverPdfs] Target PDF unit "${targetUnitId}" was not found.` : "[UniverPdfs] No active PDF unit found for appendPdfAsync()."
3553
+ );
3554
+ }
3555
+ return await target.appendPdf(arg1, options);
3556
+ }
3557
+ if (typeof arg1 === "string") {
3558
+ const asTarget = arg2 !== void 0 ? this.getPdf(arg1) : null;
3559
+ if (asTarget && arg2 !== void 0) {
3560
+ return await asTarget.appendPdf(arg2, options);
3561
+ }
3562
+ const targetUnitId = typeof arg2 === "string" ? arg2 : void 0;
3563
+ const target = targetUnitId ? this.getPdf(targetUnitId) : this.getActivePdf();
3564
+ if (!target) {
3565
+ throw new Error(
3566
+ arg2 !== void 0 && !targetUnitId ? `[UniverPdfs] Target PDF unit "${arg1}" was not found.` : `[UniverPdfs] Target PDF unit "${targetUnitId ?? arg1}" was not found.`
3567
+ );
3568
+ }
3569
+ return await target.appendPdf(arg1, options);
3570
+ }
3571
+ throw new Error("[UniverPdfs] Invalid arguments passed to appendPdfAsync().");
3572
+ }
3573
+ async exportPdfAsync(unitIdOrPdf, data, options) {
3574
+ this._ensurePdfServiceEventWiring();
3575
+ const target = typeof unitIdOrPdf === "string" ? this.getPdf(unitIdOrPdf) : unitIdOrPdf ?? this.getActivePdf();
3576
+ if (!target) {
3577
+ throw new Error("[UniverPdfs] No active or matching PDF unit found for exportPdfAsync().");
3578
+ }
3579
+ return await target.exportPdf(data, options);
3580
+ }
3581
+ getPdfTableThemePresets() {
3582
+ return import_core4.Tools.deepClone([...import_univer_pdfs5.PDF_TABLE_THEME_PRESETS]);
3583
+ }
3584
+ };
3585
+ import_facade3.FUniver.extend(FUniverPdfsMixin);
3586
+ // Annotate the CommonJS export names for ESM import in node:
3587
+ 0 && (module.exports = {
3588
+ FEnumPdfsMixin,
3589
+ FEventNamePdfsMixin,
3590
+ FPdf,
3591
+ FPdfAnnotation,
3592
+ FPdfDivider,
3593
+ FPdfDocument,
3594
+ FPdfImage,
3595
+ FPdfImageBuilder,
3596
+ FPdfList,
3597
+ FPdfPage,
3598
+ FPdfPageElement,
3599
+ FPdfParagraph,
3600
+ FPdfTable,
3601
+ FPdfTableCell,
3602
+ FPdfTextBox,
3603
+ FPdfTextSpan,
3604
+ FUniverPdfsMixin,
3605
+ wrapPdfElementFacade
3606
+ });
3607
+ //# sourceMappingURL=index.js.map