@windoc/core 0.3.24 → 0.3.26

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -78,7 +78,7 @@ __export(index_exports, {
78
78
  module.exports = __toCommonJS(index_exports);
79
79
 
80
80
  // src/version.ts
81
- var version = "0.3.24";
81
+ var version = "0.3.26";
82
82
 
83
83
  // src/dataset/enum/Common.ts
84
84
  var MaxHeightRatio = /* @__PURE__ */ ((MaxHeightRatio2) => {
@@ -256,6 +256,13 @@ function downloadFile(href, fileName) {
256
256
  a.download = fileName;
257
257
  a.click();
258
258
  }
259
+ function downloadBlob(blob, fileName) {
260
+ const href = URL.createObjectURL(blob);
261
+ downloadFile(href, fileName);
262
+ window.setTimeout(() => {
263
+ URL.revokeObjectURL(href);
264
+ }, 0);
265
+ }
259
266
  function threeClick(dom, fn) {
260
267
  nClickEvent(3, dom, fn);
261
268
  }
@@ -3881,23 +3888,23 @@ var ListStyle = /* @__PURE__ */ ((ListStyle3) => {
3881
3888
  ListStyle3["CHECKBOX"] = "checkbox" /* CHECKBOX */;
3882
3889
  return ListStyle3;
3883
3890
  })(ListStyle || {});
3884
- var OlPreset = /* @__PURE__ */ ((OlPreset2) => {
3885
- OlPreset2["DEFAULT"] = "olDefault";
3886
- OlPreset2["PARENTHESIS"] = "olParen";
3887
- OlPreset2["OUTLINE"] = "olOutline";
3888
- OlPreset2["UPPER_ALPHA"] = "olUpperA";
3889
- OlPreset2["ROMAN"] = "olRoman";
3890
- OlPreset2["ZERO_PAD"] = "olZeroPad";
3891
- return OlPreset2;
3891
+ var OlPreset = /* @__PURE__ */ ((OlPreset3) => {
3892
+ OlPreset3["DEFAULT"] = "olDefault";
3893
+ OlPreset3["PARENTHESIS"] = "olParen";
3894
+ OlPreset3["OUTLINE"] = "olOutline";
3895
+ OlPreset3["UPPER_ALPHA"] = "olUpperA";
3896
+ OlPreset3["ROMAN"] = "olRoman";
3897
+ OlPreset3["ZERO_PAD"] = "olZeroPad";
3898
+ return OlPreset3;
3892
3899
  })(OlPreset || {});
3893
- var UlPreset = /* @__PURE__ */ ((UlPreset2) => {
3894
- UlPreset2["DEFAULT"] = "ulDefault";
3895
- UlPreset2["DIAMOND"] = "ulDiamond";
3896
- UlPreset2["HOLLOW_SQ"] = "ulHollowSq";
3897
- UlPreset2["ARROW"] = "ulArrow";
3898
- UlPreset2["STAR"] = "ulStar";
3899
- UlPreset2["CHECK_ARROW"] = "ulCheckArr";
3900
- return UlPreset2;
3900
+ var UlPreset = /* @__PURE__ */ ((UlPreset3) => {
3901
+ UlPreset3["DEFAULT"] = "ulDefault";
3902
+ UlPreset3["DIAMOND"] = "ulDiamond";
3903
+ UlPreset3["HOLLOW_SQ"] = "ulHollowSq";
3904
+ UlPreset3["ARROW"] = "ulArrow";
3905
+ UlPreset3["STAR"] = "ulStar";
3906
+ UlPreset3["CHECK_ARROW"] = "ulCheckArr";
3907
+ return UlPreset3;
3901
3908
  })(UlPreset || {});
3902
3909
 
3903
3910
  // src/dataset/constant/List.ts
@@ -24337,6 +24344,8 @@ var Command = class {
24337
24344
  this.executeSearchNavigateNext = adapt.searchNavigateNext.bind(adapt);
24338
24345
  this.executeReplace = adapt.replace.bind(adapt);
24339
24346
  this.executePrint = adapt.print.bind(adapt);
24347
+ this.executeExportDocx = adapt.exportDocx.bind(adapt);
24348
+ this.executeExportPdf = adapt.exportPdf.bind(adapt);
24340
24349
  this.executeReplaceImageElement = adapt.replaceImageElement.bind(adapt);
24341
24350
  this.executeSaveAsImageElement = adapt.saveAsImageElement.bind(adapt);
24342
24351
  this.executeSetImageCrop = adapt.setImageCrop.bind(adapt);
@@ -24417,172 +24426,3314 @@ var Command = class {
24417
24426
  }
24418
24427
  };
24419
24428
 
24420
- // src/utils/print.ts
24421
- function convertPxToPaperSize(width, height) {
24422
- if (width === 1125 && height === 1593) {
24423
- return {
24424
- size: "a3",
24425
- width: "297mm",
24426
- height: "420mm"
24427
- };
24428
- }
24429
- if (width === 794 && height === 1123) {
24430
- return {
24431
- size: "a4",
24432
- width: "210mm",
24433
- height: "297mm"
24434
- };
24435
- }
24436
- if (width === 565 && height === 796) {
24437
- return {
24438
- size: "a5",
24439
- width: "148mm",
24440
- height: "210mm"
24441
- };
24442
- }
24429
+ // src/utils/docx.ts
24430
+ var import_docx = require("docx");
24431
+ var DEFAULT_DOCX_FILE_NAME = "document.docx";
24432
+ var DEFAULT_IMAGE_WIDTH = 320;
24433
+ var DEFAULT_IMAGE_HEIGHT = 180;
24434
+ var DEFAULT_LINE_HEIGHT = 1.15;
24435
+ var DOCX_FOOTER_TEXT_COLOR = "#000000";
24436
+ var docxBulletCharMap = {
24437
+ ["disc" /* DISC */]: "\u2022",
24438
+ ["circle" /* CIRCLE */]: "\u25E6",
24439
+ ["square" /* SQUARE */]: "\u25A0",
24440
+ ["checkbox" /* CHECKBOX */]: "\u2611"
24441
+ };
24442
+ var titleHeadingMap = {
24443
+ ["first" /* FIRST */]: import_docx.HeadingLevel.HEADING_1,
24444
+ ["second" /* SECOND */]: import_docx.HeadingLevel.HEADING_2,
24445
+ ["third" /* THIRD */]: import_docx.HeadingLevel.HEADING_3,
24446
+ ["fourth" /* FOURTH */]: import_docx.HeadingLevel.HEADING_4,
24447
+ ["fifth" /* FIFTH */]: import_docx.HeadingLevel.HEADING_5,
24448
+ ["sixth" /* SIXTH */]: import_docx.HeadingLevel.HEADING_6
24449
+ };
24450
+ var orderedStyleFormatMap = {
24451
+ ["decimal" /* DECIMAL */]: import_docx.LevelFormat.DECIMAL,
24452
+ ["lowerAlpha" /* LOWER_ALPHA */]: import_docx.LevelFormat.LOWER_LETTER,
24453
+ ["upperAlpha" /* UPPER_ALPHA */]: import_docx.LevelFormat.UPPER_LETTER,
24454
+ ["lowerRoman" /* LOWER_ROMAN */]: import_docx.LevelFormat.LOWER_ROMAN,
24455
+ ["upperRoman" /* UPPER_ROMAN */]: import_docx.LevelFormat.UPPER_ROMAN,
24456
+ ["decimalParen" /* DECIMAL_PAREN */]: import_docx.LevelFormat.DECIMAL,
24457
+ decimalZero: import_docx.LevelFormat.DECIMAL_ZERO,
24458
+ lowerAlphaParen: import_docx.LevelFormat.LOWER_LETTER,
24459
+ lowerRomanParen: import_docx.LevelFormat.LOWER_ROMAN,
24460
+ outline: import_docx.LevelFormat.DECIMAL
24461
+ };
24462
+ async function exportEditorDataToDocx(payload, options = {}) {
24463
+ const fileName = normalizeDocxFileName(options.fileName);
24464
+ const file = await createDocxDocument(payload);
24465
+ const blob = await import_docx.Packer.toBlob(file);
24443
24466
  return {
24444
- size: "",
24445
- width: `${width}px`,
24446
- height: `${height}px`
24467
+ blob,
24468
+ fileName
24447
24469
  };
24448
24470
  }
24449
- function printImageBase64(base64List, options) {
24450
- const { width, height, direction = "vertical" /* VERTICAL */ } = options;
24451
- const iframe = document.createElement("iframe");
24452
- iframe.style.visibility = "hidden";
24453
- iframe.style.position = "absolute";
24454
- iframe.style.left = "0";
24455
- iframe.style.top = "0";
24456
- iframe.style.width = "0";
24457
- iframe.style.height = "0";
24458
- iframe.style.border = "none";
24459
- document.body.append(iframe);
24460
- const contentWindow = iframe.contentWindow;
24461
- const doc = contentWindow.document;
24462
- doc.open();
24463
- const container = document.createElement("div");
24464
- const paperSize = convertPxToPaperSize(width, height);
24465
- base64List.forEach((base64) => {
24466
- const image = document.createElement("img");
24467
- image.style.width = direction === "horizontal" /* HORIZONTAL */ ? paperSize.height : paperSize.width;
24468
- image.style.height = direction === "horizontal" /* HORIZONTAL */ ? paperSize.width : paperSize.height;
24469
- image.src = base64;
24470
- container.append(image);
24471
- });
24472
- const style = document.createElement("style");
24473
- const stylesheet = `
24474
- * {
24475
- margin: 0;
24476
- padding: 0;
24471
+ async function createDocxDocument(payload) {
24472
+ const { data: data2, options } = payload;
24473
+ const editorOptions = options;
24474
+ const context = createSerializeContext();
24475
+ const headerChildren = editorOptions.header.disabled ? [] : await serializeElementList(data2.header || [], editorOptions, context);
24476
+ const docxFooterElementList = forceDocxFooterTextColor(data2.footer || []);
24477
+ const footerChildren = editorOptions.footer.disabled ? [] : await serializeElementList(
24478
+ docxFooterElementList,
24479
+ editorOptions,
24480
+ context
24481
+ );
24482
+ const pageNumberParagraph = createPageNumberParagraph(
24483
+ {
24484
+ ...editorOptions.pageNumber,
24485
+ color: DOCX_FOOTER_TEXT_COLOR
24486
+ }
24487
+ );
24488
+ if (pageNumberParagraph) {
24489
+ footerChildren.push(pageNumberParagraph);
24477
24490
  }
24478
- @page {
24479
- margin: 0;
24480
- size: ${paperSize.size} ${direction === "horizontal" /* HORIZONTAL */ ? `landscape` : `portrait`};
24481
- }`;
24482
- style.append(document.createTextNode(stylesheet));
24483
- setTimeout(() => {
24484
- doc.write(`${style.outerHTML}${container.innerHTML}`);
24485
- contentWindow.print();
24486
- doc.close();
24487
- window.addEventListener(
24488
- "mouseover",
24489
- () => {
24490
- iframe?.remove();
24491
- },
24491
+ const sectionChildren = await serializeElementList(
24492
+ data2.main,
24493
+ editorOptions,
24494
+ context
24495
+ );
24496
+ const { width, height, paperDirection } = editorOptions;
24497
+ const pageWidth = paperDirection === "horizontal" /* HORIZONTAL */ ? height : width;
24498
+ const pageHeight = paperDirection === "horizontal" /* HORIZONTAL */ ? width : height;
24499
+ return new import_docx.Document({
24500
+ features: {
24501
+ updateFields: true
24502
+ },
24503
+ numbering: {
24504
+ config: createNumberingConfig()
24505
+ },
24506
+ sections: [
24492
24507
  {
24493
- once: true
24508
+ properties: {
24509
+ page: {
24510
+ size: {
24511
+ width: pxToTwips(pageWidth),
24512
+ height: pxToTwips(pageHeight),
24513
+ orientation: paperDirection === "horizontal" /* HORIZONTAL */ ? import_docx.PageOrientation.LANDSCAPE : import_docx.PageOrientation.PORTRAIT
24514
+ },
24515
+ margin: {
24516
+ top: pxToTwips(editorOptions.margins[0]),
24517
+ right: pxToTwips(editorOptions.margins[1]),
24518
+ bottom: pxToTwips(editorOptions.margins[2]),
24519
+ left: pxToTwips(editorOptions.margins[3]),
24520
+ header: pxToTwips(editorOptions.header.top),
24521
+ footer: pxToTwips(editorOptions.footer.bottom)
24522
+ },
24523
+ pageNumbers: !editorOptions.pageNumber.disabled && editorOptions.pageNumber.fromPageNo === 0 ? {
24524
+ start: editorOptions.pageNumber.startPageNo
24525
+ } : void 0
24526
+ }
24527
+ },
24528
+ headers: headerChildren.length > 0 ? {
24529
+ default: new import_docx.Header({
24530
+ children: headerChildren
24531
+ })
24532
+ } : void 0,
24533
+ footers: footerChildren.length > 0 ? {
24534
+ default: new import_docx.Footer({
24535
+ children: footerChildren
24536
+ })
24537
+ } : void 0,
24538
+ children: sectionChildren.length ? sectionChildren : [new import_docx.Paragraph({})]
24494
24539
  }
24495
- );
24540
+ ]
24496
24541
  });
24497
24542
  }
24498
-
24499
- // src/core/command/CommandAdapt.ts
24500
- var CommandAdapt = class {
24501
- constructor(draw) {
24502
- this.draw = draw;
24503
- this.range = draw.getRange();
24504
- this.position = draw.getPosition();
24505
- this.historyManager = draw.getHistoryManager();
24506
- this.canvasEvent = draw.getCanvasEvent();
24507
- this.options = draw.getOptions();
24508
- this.control = draw.getControl();
24509
- this.workerManager = draw.getWorkerManager();
24510
- this.searchManager = draw.getSearch();
24511
- this.i18n = draw.getI18n();
24512
- this.zone = draw.getZone();
24513
- this.tableOperate = draw.getTableOperate();
24543
+ async function serializeElementList(elementList, options, context) {
24544
+ const blocks = [];
24545
+ let inlineBuffer = [];
24546
+ const flushInlineBuffer = async () => {
24547
+ if (!inlineBuffer.length) return;
24548
+ blocks.push(
24549
+ ...await serializeInlineElements(inlineBuffer, options, context)
24550
+ );
24551
+ inlineBuffer = [];
24552
+ };
24553
+ for (let i = 0; i < elementList.length; i++) {
24554
+ const element = elementList[i];
24555
+ if (element.type === "area" /* AREA */ && element.valueList?.length) {
24556
+ await flushInlineBuffer();
24557
+ blocks.push(
24558
+ ...await serializeElementList(element.valueList, options, context)
24559
+ );
24560
+ continue;
24561
+ }
24562
+ if (element.type === "title" /* TITLE */ && element.valueList?.length) {
24563
+ await flushInlineBuffer();
24564
+ blocks.push(
24565
+ ...await serializeInlineElements(element.valueList, options, context, {
24566
+ heading: titleHeadingMap[element.level || "first" /* FIRST */]
24567
+ })
24568
+ );
24569
+ continue;
24570
+ }
24571
+ if (element.type === "list" /* LIST */ && element.valueList?.length) {
24572
+ await flushInlineBuffer();
24573
+ blocks.push(...await serializeListElement(element, options, context));
24574
+ continue;
24575
+ }
24576
+ if (element.type === "table" /* TABLE */ && element.trList?.length) {
24577
+ await flushInlineBuffer();
24578
+ blocks.push(await serializeTableElement(element, options, context));
24579
+ continue;
24580
+ }
24581
+ if (element.type === "pageBreak" /* PAGE_BREAK */) {
24582
+ await flushInlineBuffer();
24583
+ blocks.push(
24584
+ new import_docx.Paragraph({
24585
+ children: [new import_docx.PageBreak()]
24586
+ })
24587
+ );
24588
+ continue;
24589
+ }
24590
+ if (element.type === "separator" /* SEPARATOR */) {
24591
+ await flushInlineBuffer();
24592
+ blocks.push(
24593
+ new import_docx.Paragraph({
24594
+ thematicBreak: true
24595
+ })
24596
+ );
24597
+ continue;
24598
+ }
24599
+ if (element.type === "image" /* IMAGE */ && element.imgDisplay && element.imgDisplay !== "inline") {
24600
+ await flushInlineBuffer();
24601
+ blocks.push(...await serializeInlineElements([element], options));
24602
+ continue;
24603
+ }
24604
+ if (element.type === "block" /* BLOCK */) {
24605
+ await flushInlineBuffer();
24606
+ const blockText = getBlockFallbackText(element);
24607
+ if (blockText) {
24608
+ blocks.push(
24609
+ ...await serializeInlineElements(
24610
+ [{ value: blockText }],
24611
+ options,
24612
+ context
24613
+ )
24614
+ );
24615
+ }
24616
+ continue;
24617
+ }
24618
+ inlineBuffer.push(element);
24514
24619
  }
24515
- getStyleSelectionElementList(options = {}) {
24516
- const selection = this.range.getSelectionElementList();
24517
- if (!selection?.length) return null;
24518
- const { textLikeOnly = false } = options;
24519
- const result = [];
24520
- const collect = (elementList) => {
24521
- for (let i = 0; i < elementList.length; i++) {
24522
- const element = elementList[i];
24523
- if (element.type === "table" /* TABLE */ && element.trList?.length) {
24524
- for (let t = 0; t < element.trList.length; t++) {
24525
- const tr = element.trList[t];
24526
- for (let d = 0; d < tr.tdList.length; d++) {
24527
- collect(tr.tdList[d].value);
24528
- }
24529
- }
24530
- continue;
24620
+ await flushInlineBuffer();
24621
+ return blocks;
24622
+ }
24623
+ async function serializeInlineElements(elementList, options, _context, overrides = {}) {
24624
+ const paragraphs = [];
24625
+ let current = null;
24626
+ const getParagraphContext = (element) => ({
24627
+ heading: overrides.heading,
24628
+ numbering: overrides.numbering,
24629
+ alignment: overrides.alignment !== void 0 ? overrides.alignment : mapRowFlexToAlignment(element?.rowFlex),
24630
+ rowMargin: overrides.rowMargin !== void 0 ? overrides.rowMargin : element?.rowMargin
24631
+ });
24632
+ const flushParagraph = (context) => {
24633
+ if (!current) {
24634
+ if (!context) return;
24635
+ paragraphs.push(createParagraph([], context, options.defaultRowMargin));
24636
+ return;
24637
+ }
24638
+ paragraphs.push(
24639
+ createParagraph(
24640
+ current.children,
24641
+ current.context,
24642
+ options.defaultRowMargin
24643
+ )
24644
+ );
24645
+ current = null;
24646
+ };
24647
+ const ensureParagraph = (element) => {
24648
+ if (!current) {
24649
+ current = {
24650
+ children: [],
24651
+ context: getParagraphContext(element)
24652
+ };
24653
+ }
24654
+ return current;
24655
+ };
24656
+ const appendText = (element, text, childFactory, preserveTrailingBreak = false) => {
24657
+ const normalized = normalizeText(text);
24658
+ const parts = normalized.split("\n");
24659
+ let lastSeparatorFlushedContent = false;
24660
+ for (let i = 0; i < parts.length; i++) {
24661
+ const segment = parts[i];
24662
+ if (segment) {
24663
+ ensureParagraph(element).children.push(childFactory(segment));
24664
+ }
24665
+ if (i < parts.length - 1) {
24666
+ if (!current) {
24667
+ paragraphs.push(
24668
+ createParagraph(
24669
+ [],
24670
+ getParagraphContext(element),
24671
+ options.defaultRowMargin
24672
+ )
24673
+ );
24674
+ lastSeparatorFlushedContent = false;
24675
+ } else {
24676
+ flushParagraph();
24677
+ lastSeparatorFlushedContent = true;
24531
24678
  }
24532
- result.push(element);
24533
24679
  }
24534
- };
24535
- collect(selection);
24536
- if (!textLikeOnly) {
24537
- return result;
24538
24680
  }
24539
- return result.filter(
24540
- (element) => isTextLikeElement(element) || element.type === "label" /* LABEL */
24681
+ if (preserveTrailingBreak && normalized.endsWith("\n") && lastSeparatorFlushedContent) {
24682
+ paragraphs.push(
24683
+ createParagraph(
24684
+ [],
24685
+ getParagraphContext(element),
24686
+ options.defaultRowMargin
24687
+ )
24688
+ );
24689
+ }
24690
+ };
24691
+ for (let i = 0; i < elementList.length; i++) {
24692
+ const element = elementList[i];
24693
+ if (element.type === "hyperlink" /* HYPERLINK */ && element.valueList?.length) {
24694
+ const hyperlink = await createHyperlinkChild(element, options);
24695
+ if (hyperlink) {
24696
+ ensureParagraph(element).children.push(hyperlink);
24697
+ }
24698
+ continue;
24699
+ }
24700
+ if (element.type === "image" /* IMAGE */) {
24701
+ const imageChild = await createImageChild(element);
24702
+ if (!imageChild) {
24703
+ appendText(
24704
+ element,
24705
+ "[Image unavailable]",
24706
+ (segment) => createTextRun(
24707
+ segment,
24708
+ element,
24709
+ options.defaultSize,
24710
+ options.defaultFont
24711
+ ),
24712
+ i === elementList.length - 1
24713
+ );
24714
+ continue;
24715
+ }
24716
+ ensureParagraph(element).children.push(imageChild);
24717
+ continue;
24718
+ }
24719
+ if (element.type === "columnBreak" /* COLUMN_BREAK */) {
24720
+ ensureParagraph(element).children.push(new import_docx.ColumnBreak());
24721
+ continue;
24722
+ }
24723
+ if (element.type === "tab" /* TAB */) {
24724
+ appendText(
24725
+ element,
24726
+ " ",
24727
+ (segment) => createTextRun(
24728
+ segment,
24729
+ element,
24730
+ options.defaultSize,
24731
+ options.defaultFont
24732
+ ),
24733
+ i === elementList.length - 1
24734
+ );
24735
+ continue;
24736
+ }
24737
+ const textValue = getInlineElementText(element);
24738
+ if (!textValue) {
24739
+ continue;
24740
+ }
24741
+ appendText(
24742
+ element,
24743
+ textValue,
24744
+ (segment) => createTextRun(
24745
+ segment,
24746
+ element,
24747
+ options.defaultSize,
24748
+ options.defaultFont
24749
+ ),
24750
+ i === elementList.length - 1
24541
24751
  );
24542
24752
  }
24543
- mode(payload) {
24544
- this.draw.setMode(payload);
24753
+ if (current) {
24754
+ flushParagraph();
24545
24755
  }
24546
- async cut() {
24547
- const isDisabled = this.draw.isReadonly() || this.draw.isDisabled();
24548
- if (isDisabled) return;
24549
- await this.canvasEvent.cut();
24756
+ return paragraphs.length ? paragraphs : [createParagraph([], overrides, options.defaultRowMargin)];
24757
+ }
24758
+ async function serializeListElement(element, options, context) {
24759
+ const zipList = zipElementList(element.valueList || []);
24760
+ const listItemMap = splitListElement(zipList);
24761
+ const paragraphs = [];
24762
+ const listInstance = createListInstance(context);
24763
+ for (const listItemElements of listItemMap.values()) {
24764
+ const numbering = getListNumbering(
24765
+ getListItemNumberingElement(listItemElements, element),
24766
+ listInstance
24767
+ );
24768
+ paragraphs.push(
24769
+ ...await serializeInlineElements(listItemElements, options, context, {
24770
+ numbering
24771
+ })
24772
+ );
24550
24773
  }
24551
- async copy(payload) {
24552
- await this.canvasEvent.copy(payload);
24774
+ return paragraphs;
24775
+ }
24776
+ async function serializeTableElement(element, options, context) {
24777
+ const rows = [];
24778
+ const trList = element.trList || [];
24779
+ const tableContext = createTableSerializeContext(element);
24780
+ for (let i = 0; i < trList.length; i++) {
24781
+ rows.push(
24782
+ await serializeTableRow(trList[i], options, context, tableContext)
24783
+ );
24553
24784
  }
24554
- paste(payload) {
24555
- const isDisabled = this.draw.isReadonly() || this.draw.isDisabled();
24556
- if (isDisabled) return;
24557
- pasteByApi(this.canvasEvent, payload);
24785
+ const tableWidth = getTableWidthFromColgroup(element.colgroup);
24786
+ return new import_docx.Table({
24787
+ rows,
24788
+ width: tableWidth ? {
24789
+ size: pxToTwips(tableWidth),
24790
+ type: import_docx.WidthType.DXA
24791
+ } : {
24792
+ size: 100,
24793
+ type: import_docx.WidthType.PERCENTAGE
24794
+ },
24795
+ columnWidths: element.colgroup?.map((col) => pxToTwips(col.width)),
24796
+ layout: import_docx.TableLayoutType.FIXED,
24797
+ borders: createTableBorders(element)
24798
+ });
24799
+ }
24800
+ async function serializeTableRow(tr, options, context, tableContext) {
24801
+ const children = [];
24802
+ for (let i = 0; i < tr.tdList.length; i++) {
24803
+ children.push(
24804
+ await serializeTableCell(tr.tdList[i], options, context, tableContext)
24805
+ );
24558
24806
  }
24559
- selectAll() {
24560
- this.canvasEvent.selectAll();
24807
+ return new import_docx.TableRow({
24808
+ children
24809
+ });
24810
+ }
24811
+ async function serializeTableCell(td, options, context, tableContext) {
24812
+ const children = await serializeElementList(td.value, options, context);
24813
+ const shadingFill = td.backgroundColor ? normalizeHexColor(td.backgroundColor) : void 0;
24814
+ const cellWidth = tableContext.cellLayoutMap.get(td)?.width || td.width;
24815
+ return new import_docx.TableCell({
24816
+ children: children.length ? children : [new import_docx.Paragraph({})],
24817
+ columnSpan: td.colspan > 1 ? td.colspan : void 0,
24818
+ rowSpan: td.rowspan > 1 ? td.rowspan : void 0,
24819
+ verticalAlign: mapCellVerticalAlign(td.verticalAlign),
24820
+ width: cellWidth ? {
24821
+ size: pxToTwips(cellWidth),
24822
+ type: import_docx.WidthType.DXA
24823
+ } : void 0,
24824
+ shading: shadingFill ? {
24825
+ fill: shadingFill,
24826
+ type: import_docx.ShadingType.CLEAR
24827
+ } : void 0,
24828
+ margins: mapPaddingToTableMargins(td.padding),
24829
+ borders: createTableCellBorders(
24830
+ td,
24831
+ tableContext.borderColor,
24832
+ tableContext.borderWidth
24833
+ )
24834
+ });
24835
+ }
24836
+ function createParagraph(children, context, defaultRowMargin) {
24837
+ return new import_docx.Paragraph({
24838
+ children,
24839
+ heading: context.heading,
24840
+ numbering: context.numbering,
24841
+ alignment: context.alignment,
24842
+ spacing: {
24843
+ line: Math.round(
24844
+ 240 * (context.rowMargin || defaultRowMargin || DEFAULT_LINE_HEIGHT)
24845
+ ),
24846
+ lineRule: import_docx.LineRuleType.AUTO
24847
+ }
24848
+ });
24849
+ }
24850
+ function createTextRun(text, element, defaultSize, defaultFont) {
24851
+ const color = element.color ? normalizeHexColor(element.color, "000000") : void 0;
24852
+ const highlightFill = element.highlight ? normalizeHexColor(element.highlight) : void 0;
24853
+ return new import_docx.TextRun({
24854
+ text,
24855
+ bold: !!element.bold,
24856
+ italics: !!element.italic,
24857
+ strike: !!element.strikeout,
24858
+ subScript: element.type === "subscript" /* SUBSCRIPT */,
24859
+ superScript: element.type === "superscript" /* SUPERSCRIPT */,
24860
+ color,
24861
+ shading: highlightFill ? {
24862
+ fill: highlightFill,
24863
+ type: import_docx.ShadingType.CLEAR
24864
+ } : void 0,
24865
+ underline: element.underline ? {
24866
+ type: mapUnderlineType(element.textDecoration?.style)
24867
+ } : void 0,
24868
+ font: element.font || defaultFont,
24869
+ size: Math.round((element.size || defaultSize) * 2)
24870
+ });
24871
+ }
24872
+ async function createHyperlinkChild(element, options) {
24873
+ if (!element.url) {
24874
+ const fallbackText = getTextFromElementList(element.valueList || []);
24875
+ return fallbackText ? createTextRun(
24876
+ fallbackText,
24877
+ element.valueList?.[0] || element,
24878
+ options.defaultSize,
24879
+ options.defaultFont
24880
+ ) : null;
24881
+ }
24882
+ const children = await createHyperlinkRuns(
24883
+ element.valueList || [],
24884
+ options.defaultSize,
24885
+ options.defaultFont
24886
+ );
24887
+ if (!children.length) {
24888
+ return null;
24561
24889
  }
24562
- backspace() {
24563
- const isDisabled = this.draw.isReadonly() || this.draw.isDisabled();
24564
- if (isDisabled) return;
24565
- const elementList = this.draw.getElementList();
24566
- const { startIndex, endIndex } = this.range.getRange();
24567
- const isCollapsed = startIndex === endIndex;
24568
- if (isCollapsed && elementList[startIndex].value === ZERO && startIndex === 0) {
24569
- return;
24890
+ return new import_docx.ExternalHyperlink({
24891
+ link: element.url,
24892
+ children
24893
+ });
24894
+ }
24895
+ async function createHyperlinkRuns(valueList, defaultSize, defaultFont) {
24896
+ const children = [];
24897
+ for (let i = 0; i < valueList.length; i++) {
24898
+ const element = valueList[i];
24899
+ if (element.type === "tab" /* TAB */) {
24900
+ children.push(createTextRun(" ", element, defaultSize, defaultFont));
24901
+ continue;
24570
24902
  }
24571
- if (!isCollapsed) {
24572
- this.draw.spliceElementList(
24573
- elementList,
24574
- startIndex + 1,
24575
- endIndex - startIndex
24576
- );
24577
- } else {
24578
- this.draw.spliceElementList(elementList, startIndex, 1);
24903
+ const text = normalizeText(getInlineElementText(element)).replace(
24904
+ /\n/g,
24905
+ " "
24906
+ );
24907
+ if (text) {
24908
+ children.push(createTextRun(text, element, defaultSize, defaultFont));
24579
24909
  }
24580
- const curIndex = isCollapsed ? startIndex - 1 : startIndex;
24581
- this.range.setRange(curIndex, curIndex);
24582
- this.draw.render({ curIndex });
24583
24910
  }
24584
- setRange(startIndex, endIndex, tableId, startTdIndex, endTdIndex, startTrIndex, endTrIndex) {
24585
- if (startIndex < 0 || endIndex < 0 || endIndex < startIndex) return;
24911
+ return children;
24912
+ }
24913
+ async function createImageChild(element) {
24914
+ try {
24915
+ const image = await loadImagePayload(element.value);
24916
+ const width = Math.max(1, Math.round(element.width || DEFAULT_IMAGE_WIDTH));
24917
+ const height = Math.max(
24918
+ 1,
24919
+ Math.round(element.height || DEFAULT_IMAGE_HEIGHT)
24920
+ );
24921
+ if (image.type === "svg" && image.fallbackPng) {
24922
+ return new import_docx.ImageRun({
24923
+ type: "svg",
24924
+ data: image.data,
24925
+ fallback: {
24926
+ type: "png",
24927
+ data: image.fallbackPng
24928
+ },
24929
+ transformation: {
24930
+ width,
24931
+ height
24932
+ }
24933
+ });
24934
+ }
24935
+ return new import_docx.ImageRun({
24936
+ type: image.type,
24937
+ data: image.data,
24938
+ transformation: {
24939
+ width,
24940
+ height
24941
+ }
24942
+ });
24943
+ } catch {
24944
+ return null;
24945
+ }
24946
+ }
24947
+ async function loadImagePayload(src) {
24948
+ const source = src.trim();
24949
+ if (source.startsWith("data:")) {
24950
+ return getImagePayloadFromDataUrl(source);
24951
+ }
24952
+ const response = await fetch(source);
24953
+ if (!response.ok) {
24954
+ throw new Error(`Image request failed: ${response.status}`);
24955
+ }
24956
+ const contentType = response.headers.get("content-type") || "";
24957
+ const data2 = await response.arrayBuffer();
24958
+ return normalizeImagePayload(data2, contentType);
24959
+ }
24960
+ async function getImagePayloadFromDataUrl(src) {
24961
+ const [, meta = "", encoded = ""] = src.match(/^data:([^,]*),(.*)$/) || [];
24962
+ const mime = meta.split(";")[0] || "";
24963
+ const isBase64 = meta.includes(";base64");
24964
+ const text = isBase64 ? atob(encoded) : decodeURIComponent(encoded);
24965
+ const bytes = new Uint8Array(text.length);
24966
+ for (let i = 0; i < text.length; i++) {
24967
+ bytes[i] = text.charCodeAt(i);
24968
+ }
24969
+ return normalizeImagePayload(bytes.buffer, mime);
24970
+ }
24971
+ async function normalizeImagePayload(data2, mime) {
24972
+ const type = getRegularImageType(mime);
24973
+ if (type) {
24974
+ return {
24975
+ type,
24976
+ data: data2
24977
+ };
24978
+ }
24979
+ if (mime.includes("svg")) {
24980
+ return {
24981
+ type: "svg",
24982
+ data: data2,
24983
+ fallbackPng: await rasterizeSvgToPng(data2)
24984
+ };
24985
+ }
24986
+ const fallbackPng = await rasterizeImageToPng(data2, mime);
24987
+ return {
24988
+ type: "png",
24989
+ data: fallbackPng
24990
+ };
24991
+ }
24992
+ async function rasterizeSvgToPng(data2) {
24993
+ return rasterizeImageToPng(data2, "image/svg+xml");
24994
+ }
24995
+ async function rasterizeImageToPng(data2, mime) {
24996
+ const blob = new Blob([data2], {
24997
+ type: mime || "image/png"
24998
+ });
24999
+ const url = URL.createObjectURL(blob);
25000
+ try {
25001
+ const image = await loadHtmlImage(url);
25002
+ const canvas = document.createElement("canvas");
25003
+ canvas.width = image.naturalWidth || DEFAULT_IMAGE_WIDTH;
25004
+ canvas.height = image.naturalHeight || DEFAULT_IMAGE_HEIGHT;
25005
+ const context = canvas.getContext("2d");
25006
+ if (!context) {
25007
+ throw new Error("Canvas context is unavailable");
25008
+ }
25009
+ context.drawImage(image, 0, 0, canvas.width, canvas.height);
25010
+ const pngBlob = await new Promise((resolve, reject) => {
25011
+ canvas.toBlob((output) => {
25012
+ if (output) {
25013
+ resolve(output);
25014
+ } else {
25015
+ reject(new Error("Failed to create PNG blob"));
25016
+ }
25017
+ }, "image/png");
25018
+ });
25019
+ return await pngBlob.arrayBuffer();
25020
+ } finally {
25021
+ URL.revokeObjectURL(url);
25022
+ }
25023
+ }
25024
+ function loadHtmlImage(src) {
25025
+ return new Promise((resolve, reject) => {
25026
+ const image = new Image();
25027
+ image.onload = () => resolve(image);
25028
+ image.onerror = () => reject(new Error("Failed to load image"));
25029
+ image.src = src;
25030
+ });
25031
+ }
25032
+ function createPageNumberParagraph(pageNumber) {
25033
+ if (pageNumber.disabled || pageNumber.fromPageNo > 0) {
25034
+ return null;
25035
+ }
25036
+ const children = [];
25037
+ const format = pageNumber.format || FORMAT_PLACEHOLDER.PAGE_NO;
25038
+ const tokens = format.split(/(\{pageNo\}|\{pageCount\})/);
25039
+ for (let i = 0; i < tokens.length; i++) {
25040
+ const token = tokens[i];
25041
+ if (!token) continue;
25042
+ const runChildren = token === FORMAT_PLACEHOLDER.PAGE_NO ? [import_docx.PageNumber.CURRENT] : token === FORMAT_PLACEHOLDER.PAGE_COUNT ? [import_docx.PageNumber.TOTAL_PAGES] : void 0;
25043
+ children.push(
25044
+ new import_docx.TextRun({
25045
+ text: runChildren ? void 0 : token,
25046
+ children: runChildren,
25047
+ color: normalizeHexColor(pageNumber.color || "#000000", "000000"),
25048
+ font: pageNumber.font,
25049
+ size: Math.round((pageNumber.size || 12) * 2)
25050
+ })
25051
+ );
25052
+ }
25053
+ return new import_docx.Paragraph({
25054
+ children,
25055
+ alignment: mapRowFlexToAlignment(pageNumber.rowFlex)
25056
+ });
25057
+ }
25058
+ function forceDocxFooterTextColor(elementList) {
25059
+ const footerElementList = deepClone(elementList);
25060
+ forceColorValue(footerElementList);
25061
+ return footerElementList;
25062
+ }
25063
+ function forceColorValue(value) {
25064
+ if (!value || typeof value !== "object") {
25065
+ return;
25066
+ }
25067
+ if (Array.isArray(value)) {
25068
+ for (let i = 0; i < value.length; i++) {
25069
+ forceColorValue(value[i]);
25070
+ }
25071
+ return;
25072
+ }
25073
+ const record = value;
25074
+ if ("color" in record) {
25075
+ record.color = DOCX_FOOTER_TEXT_COLOR;
25076
+ }
25077
+ const keys = Object.keys(record);
25078
+ for (let i = 0; i < keys.length; i++) {
25079
+ forceColorValue(record[keys[i]]);
25080
+ }
25081
+ }
25082
+ function createNumberingConfig() {
25083
+ const config = [
25084
+ createOrderedReference("windoc-ol-decimal", Array(9).fill("decimal" /* DECIMAL */)),
25085
+ createOrderedReference(
25086
+ "windoc-ol-lower-alpha",
25087
+ Array(9).fill("lowerAlpha" /* LOWER_ALPHA */)
25088
+ ),
25089
+ createOrderedReference(
25090
+ "windoc-ol-upper-alpha",
25091
+ Array(9).fill("upperAlpha" /* UPPER_ALPHA */)
25092
+ ),
25093
+ createOrderedReference(
25094
+ "windoc-ol-lower-roman",
25095
+ Array(9).fill("lowerRoman" /* LOWER_ROMAN */)
25096
+ ),
25097
+ createOrderedReference(
25098
+ "windoc-ol-upper-roman",
25099
+ Array(9).fill("upperRoman" /* UPPER_ROMAN */)
25100
+ ),
25101
+ createOrderedReference(
25102
+ "windoc-ol-decimal-paren",
25103
+ Array(9).fill("decimalParen" /* DECIMAL_PAREN */)
25104
+ ),
25105
+ createOrderedReference(
25106
+ `windoc-ol-${"olDefault" /* DEFAULT */}`,
25107
+ createCycleList(olPresetCycles["olDefault" /* DEFAULT */], 9)
25108
+ ),
25109
+ createOrderedReference(
25110
+ `windoc-ol-${"olParen" /* PARENTHESIS */}`,
25111
+ createCycleList(olPresetCycles["olParen" /* PARENTHESIS */], 9)
25112
+ ),
25113
+ createOrderedReference(
25114
+ `windoc-ol-${"olOutline" /* OUTLINE */}`,
25115
+ createCycleList(olPresetCycles["olOutline" /* OUTLINE */], 9)
25116
+ ),
25117
+ createOrderedReference(
25118
+ `windoc-ol-${"olUpperA" /* UPPER_ALPHA */}`,
25119
+ createCycleList(olPresetCycles["olUpperA" /* UPPER_ALPHA */], 9)
25120
+ ),
25121
+ createOrderedReference(
25122
+ `windoc-ol-${"olRoman" /* ROMAN */}`,
25123
+ createCycleList(olPresetCycles["olRoman" /* ROMAN */], 9)
25124
+ ),
25125
+ createOrderedReference(
25126
+ `windoc-ol-${"olZeroPad" /* ZERO_PAD */}`,
25127
+ createCycleList(olPresetCycles["olZeroPad" /* ZERO_PAD */], 9)
25128
+ ),
25129
+ createBulletReference(
25130
+ "windoc-ul-disc",
25131
+ Array(9).fill(docxBulletCharMap["disc" /* DISC */])
25132
+ ),
25133
+ createBulletReference(
25134
+ "windoc-ul-circle",
25135
+ Array(9).fill(docxBulletCharMap["circle" /* CIRCLE */])
25136
+ ),
25137
+ createBulletReference(
25138
+ "windoc-ul-square",
25139
+ Array(9).fill(docxBulletCharMap["square" /* SQUARE */])
25140
+ ),
25141
+ createBulletReference(
25142
+ "windoc-ul-checkbox",
25143
+ Array(9).fill(docxBulletCharMap["checkbox" /* CHECKBOX */])
25144
+ ),
25145
+ createBulletReference(
25146
+ `windoc-ul-${"ulDefault" /* DEFAULT */}`,
25147
+ createCycleList(ulPresetCycles["ulDefault" /* DEFAULT */], 9)
25148
+ ),
25149
+ createBulletReference(
25150
+ `windoc-ul-${"ulDiamond" /* DIAMOND */}`,
25151
+ createCycleList(ulPresetCycles["ulDiamond" /* DIAMOND */], 9)
25152
+ ),
25153
+ createBulletReference(
25154
+ `windoc-ul-${"ulHollowSq" /* HOLLOW_SQ */}`,
25155
+ createCycleList(ulPresetCycles["ulHollowSq" /* HOLLOW_SQ */], 9)
25156
+ ),
25157
+ createBulletReference(
25158
+ `windoc-ul-${"ulArrow" /* ARROW */}`,
25159
+ createCycleList(ulPresetCycles["ulArrow" /* ARROW */], 9)
25160
+ ),
25161
+ createBulletReference(
25162
+ `windoc-ul-${"ulStar" /* STAR */}`,
25163
+ createCycleList(ulPresetCycles["ulStar" /* STAR */], 9)
25164
+ ),
25165
+ createBulletReference(
25166
+ `windoc-ul-${"ulCheckArr" /* CHECK_ARROW */}`,
25167
+ createCycleList(ulPresetCycles["ulCheckArr" /* CHECK_ARROW */], 9)
25168
+ )
25169
+ ];
25170
+ return config;
25171
+ }
25172
+ function createOrderedReference(reference, styles) {
25173
+ return {
25174
+ reference,
25175
+ levels: styles.map((style, level) => ({
25176
+ level,
25177
+ format: orderedStyleFormatMap[style] || import_docx.LevelFormat.DECIMAL,
25178
+ text: getOrderedLevelText(style, level),
25179
+ alignment: import_docx.AlignmentType.START,
25180
+ style: {
25181
+ paragraph: {
25182
+ indent: {
25183
+ left: 720 * (level + 1),
25184
+ hanging: 360
25185
+ }
25186
+ }
25187
+ }
25188
+ }))
25189
+ };
25190
+ }
25191
+ function createBulletReference(reference, bullets) {
25192
+ return {
25193
+ reference,
25194
+ levels: bullets.map((bullet, level) => ({
25195
+ level,
25196
+ format: import_docx.LevelFormat.BULLET,
25197
+ text: bullet,
25198
+ alignment: import_docx.AlignmentType.START,
25199
+ style: {
25200
+ paragraph: {
25201
+ indent: {
25202
+ left: 720 * (level + 1),
25203
+ hanging: 360
25204
+ }
25205
+ }
25206
+ }
25207
+ }))
25208
+ };
25209
+ }
25210
+ function getOrderedLevelText(style, level) {
25211
+ const placeholder = `%${level + 1}`;
25212
+ if (style === "outline") {
25213
+ return Array.from({ length: level + 1 }, (_, index) => `%${index + 1}`).join(
25214
+ "."
25215
+ ) + ".";
25216
+ }
25217
+ if (style.endsWith("Paren") || style === "decimalParen" /* DECIMAL_PAREN */) {
25218
+ return `${placeholder})`;
25219
+ }
25220
+ return `${placeholder}.`;
25221
+ }
25222
+ function createCycleList(source = [], size) {
25223
+ const result = [];
25224
+ for (let i = 0; i < size; i++) {
25225
+ result.push(source[i % source.length]);
25226
+ }
25227
+ return result;
25228
+ }
25229
+ function getListNumbering(element, instance) {
25230
+ const level = Math.max(0, Math.min(element.listLevel || 0, 8));
25231
+ if (element.listType === "ul" /* UL */) {
25232
+ const reference2 = element.listPreset ? `windoc-ul-${element.listPreset}` : `windoc-ul-${element.listStyle || "disc" /* DISC */}`;
25233
+ return {
25234
+ reference: reference2,
25235
+ level,
25236
+ instance
25237
+ };
25238
+ }
25239
+ const reference = element.listPreset ? `windoc-ol-${element.listPreset}` : getOrderedReferenceFromStyle(element.listStyle);
25240
+ return {
25241
+ reference,
25242
+ level,
25243
+ instance
25244
+ };
25245
+ }
25246
+ function getOrderedReferenceFromStyle(style) {
25247
+ switch (style) {
25248
+ case "lowerAlpha" /* LOWER_ALPHA */:
25249
+ return "windoc-ol-lower-alpha";
25250
+ case "upperAlpha" /* UPPER_ALPHA */:
25251
+ return "windoc-ol-upper-alpha";
25252
+ case "lowerRoman" /* LOWER_ROMAN */:
25253
+ return "windoc-ol-lower-roman";
25254
+ case "upperRoman" /* UPPER_ROMAN */:
25255
+ return "windoc-ol-upper-roman";
25256
+ case "decimalParen" /* DECIMAL_PAREN */:
25257
+ return "windoc-ol-decimal-paren";
25258
+ default:
25259
+ return "windoc-ol-decimal";
25260
+ }
25261
+ }
25262
+ function createTableBorders(element) {
25263
+ const outerBorder = createBorder(
25264
+ element.borderColor,
25265
+ import_docx.BorderStyle.SINGLE,
25266
+ element.borderExternalWidth || element.borderWidth
25267
+ );
25268
+ const innerBorder = createBorder(
25269
+ element.borderColor,
25270
+ import_docx.BorderStyle.SINGLE,
25271
+ element.borderWidth
25272
+ );
25273
+ switch (element.borderType) {
25274
+ case "empty" /* EMPTY */:
25275
+ return {
25276
+ top: noneBorder(),
25277
+ bottom: noneBorder(),
25278
+ left: noneBorder(),
25279
+ right: noneBorder(),
25280
+ insideHorizontal: noneBorder(),
25281
+ insideVertical: noneBorder()
25282
+ };
25283
+ case "external" /* EXTERNAL */:
25284
+ return {
25285
+ top: outerBorder,
25286
+ bottom: outerBorder,
25287
+ left: outerBorder,
25288
+ right: outerBorder,
25289
+ insideHorizontal: noneBorder(),
25290
+ insideVertical: noneBorder()
25291
+ };
25292
+ case "internal" /* INTERNAL */:
25293
+ return {
25294
+ top: noneBorder(),
25295
+ bottom: noneBorder(),
25296
+ left: noneBorder(),
25297
+ right: noneBorder(),
25298
+ insideHorizontal: innerBorder,
25299
+ insideVertical: innerBorder
25300
+ };
25301
+ case "dash" /* DASH */:
25302
+ return {
25303
+ top: createBorder(
25304
+ element.borderColor,
25305
+ import_docx.BorderStyle.DASHED,
25306
+ element.borderExternalWidth || element.borderWidth
25307
+ ),
25308
+ bottom: createBorder(
25309
+ element.borderColor,
25310
+ import_docx.BorderStyle.DASHED,
25311
+ element.borderExternalWidth || element.borderWidth
25312
+ ),
25313
+ left: createBorder(
25314
+ element.borderColor,
25315
+ import_docx.BorderStyle.DASHED,
25316
+ element.borderExternalWidth || element.borderWidth
25317
+ ),
25318
+ right: createBorder(
25319
+ element.borderColor,
25320
+ import_docx.BorderStyle.DASHED,
25321
+ element.borderExternalWidth || element.borderWidth
25322
+ ),
25323
+ insideHorizontal: createBorder(
25324
+ element.borderColor,
25325
+ import_docx.BorderStyle.DASHED,
25326
+ element.borderWidth
25327
+ ),
25328
+ insideVertical: createBorder(
25329
+ element.borderColor,
25330
+ import_docx.BorderStyle.DASHED,
25331
+ element.borderWidth
25332
+ )
25333
+ };
25334
+ default:
25335
+ return {
25336
+ top: outerBorder,
25337
+ bottom: outerBorder,
25338
+ left: outerBorder,
25339
+ right: outerBorder,
25340
+ insideHorizontal: innerBorder,
25341
+ insideVertical: innerBorder
25342
+ };
25343
+ }
25344
+ }
25345
+ function createTableCellBorders(td, inheritedColor, inheritedWidth) {
25346
+ if (!td.borderTypes?.length && !td.borderColor) {
25347
+ return void 0;
25348
+ }
25349
+ const color = td.borderColor || inheritedColor;
25350
+ const createCellBorder = () => createBorder(color, import_docx.BorderStyle.SINGLE, inheritedWidth);
25351
+ if (td.borderColor && !td.borderTypes?.length) {
25352
+ return {
25353
+ top: createCellBorder(),
25354
+ right: createCellBorder(),
25355
+ bottom: createCellBorder(),
25356
+ left: createCellBorder()
25357
+ };
25358
+ }
25359
+ const top = td.borderTypes?.includes("top" /* TOP */) ? createCellBorder() : noneBorder();
25360
+ const right2 = td.borderTypes?.includes("right" /* RIGHT */) ? createCellBorder() : noneBorder();
25361
+ const bottom = td.borderTypes?.includes("bottom" /* BOTTOM */) ? createCellBorder() : noneBorder();
25362
+ const left2 = td.borderTypes?.includes("left" /* LEFT */) ? createCellBorder() : noneBorder();
25363
+ return {
25364
+ top,
25365
+ right: right2,
25366
+ bottom,
25367
+ left: left2
25368
+ };
25369
+ }
25370
+ function createBorder(color = "#000000", style = import_docx.BorderStyle.SINGLE, width = 1) {
25371
+ return {
25372
+ style,
25373
+ color: normalizeHexColor(color, "000000") || "000000",
25374
+ size: pxBorderToDocxSize(width)
25375
+ };
25376
+ }
25377
+ function noneBorder() {
25378
+ return {
25379
+ style: import_docx.BorderStyle.NONE,
25380
+ size: 0,
25381
+ color: "FFFFFF"
25382
+ };
25383
+ }
25384
+ function mapPaddingToTableMargins(padding) {
25385
+ if (!padding) return void 0;
25386
+ return {
25387
+ top: pxToTwips(padding[0]),
25388
+ right: pxToTwips(padding[1]),
25389
+ bottom: pxToTwips(padding[2]),
25390
+ left: pxToTwips(padding[3]),
25391
+ marginUnitType: import_docx.WidthType.DXA
25392
+ };
25393
+ }
25394
+ function mapCellVerticalAlign(verticalAlign) {
25395
+ switch (verticalAlign) {
25396
+ case VerticalAlign.CENTER:
25397
+ return import_docx.VerticalAlign.CENTER;
25398
+ case "bottom" /* BOTTOM */:
25399
+ return import_docx.VerticalAlign.BOTTOM;
25400
+ default:
25401
+ return import_docx.VerticalAlign.TOP;
25402
+ }
25403
+ }
25404
+ function mapRowFlexToAlignment(rowFlex) {
25405
+ switch (rowFlex) {
25406
+ case "center" /* CENTER */:
25407
+ return import_docx.AlignmentType.CENTER;
25408
+ case "right" /* RIGHT */:
25409
+ return import_docx.AlignmentType.RIGHT;
25410
+ case "alignment" /* ALIGNMENT */:
25411
+ case "justify" /* JUSTIFY */:
25412
+ return import_docx.AlignmentType.JUSTIFIED;
25413
+ default:
25414
+ return import_docx.AlignmentType.LEFT;
25415
+ }
25416
+ }
25417
+ function mapUnderlineType(style) {
25418
+ switch (style) {
25419
+ case "double" /* DOUBLE */:
25420
+ return import_docx.UnderlineType.DOUBLE;
25421
+ case "dashed" /* DASHED */:
25422
+ return import_docx.UnderlineType.DASH;
25423
+ case "dotted" /* DOTTED */:
25424
+ return import_docx.UnderlineType.DOTTED;
25425
+ case "wavy" /* WAVY */:
25426
+ return import_docx.UnderlineType.WAVE;
25427
+ default:
25428
+ return import_docx.UnderlineType.SINGLE;
25429
+ }
25430
+ }
25431
+ function getInlineElementText(element) {
25432
+ switch (element.type) {
25433
+ case "control" /* CONTROL */:
25434
+ return getControlText(element.control);
25435
+ case "date" /* DATE */:
25436
+ return element.valueList?.length ? getTextFromElementList(element.valueList) : element.value;
25437
+ case "checkbox" /* CHECKBOX */:
25438
+ return element.checkbox?.value ? "\u2611" : "\u2610";
25439
+ case "radio" /* RADIO */:
25440
+ return element.radio?.value ? "\u25C9" : "\u25CB";
25441
+ case "label" /* LABEL */:
25442
+ case "latex" /* LATEX */:
25443
+ case "subscript" /* SUBSCRIPT */:
25444
+ case "superscript" /* SUPERSCRIPT */:
25445
+ return element.value;
25446
+ default:
25447
+ return element.value;
25448
+ }
25449
+ }
25450
+ function getControlText(control) {
25451
+ if (!control) return "";
25452
+ if (control.type === "text" /* TEXT */ || control.type === "date" /* DATE */ || control.type === "number" /* NUMBER */) {
25453
+ const value = control.value?.length ? getTextFromElementList(control.value) : "";
25454
+ const content = value || control.placeholder || "";
25455
+ return `${control.preText || ""}${content}${control.postText || ""}`;
25456
+ }
25457
+ if (control.type === "select" /* SELECT */) {
25458
+ const labels = getSelectedControlLabels(control.code, control.valueSets);
25459
+ const content = labels.length ? labels.join(control.multiSelectDelimiter || ", ") : control.placeholder || "";
25460
+ return `${control.preText || ""}${content}${control.postText || ""}`;
25461
+ }
25462
+ if (control.type === "checkbox" /* CHECKBOX */ || control.type === "radio" /* RADIO */) {
25463
+ const isRadio = control.type === "radio" /* RADIO */;
25464
+ return (control.valueSets || []).map((valueSet) => {
25465
+ const checked = control.code?.split(",").includes(valueSet.code) || false;
25466
+ return `${checked ? isRadio ? "\u25C9" : "\u2611" : isRadio ? "\u25CB" : "\u2610"} ${valueSet.value}`;
25467
+ }).join(" ");
25468
+ }
25469
+ return "";
25470
+ }
25471
+ function getSelectedControlLabels(code, valueSets) {
25472
+ if (!code || !valueSets?.length) return [];
25473
+ return code.split(",").map(
25474
+ (selectCode) => valueSets.find((valueSet) => valueSet.code === selectCode)?.value
25475
+ ).filter((value) => !!value);
25476
+ }
25477
+ function getBlockFallbackText(element) {
25478
+ if (element.block?.iframeBlock?.src) {
25479
+ return element.block.iframeBlock.src;
25480
+ }
25481
+ if (element.block?.videoBlock?.src) {
25482
+ return element.block.videoBlock.src;
25483
+ }
25484
+ return "";
25485
+ }
25486
+ function normalizeText(text = "") {
25487
+ return text.replace(new RegExp(ZERO, "g"), "").replace(/\r\n/g, "\n");
25488
+ }
25489
+ function createSerializeContext() {
25490
+ return {
25491
+ nextListInstance: 1
25492
+ };
25493
+ }
25494
+ function getListItemNumberingElement(listItemElements, fallback) {
25495
+ return listItemElements.find(
25496
+ (listItem) => listItem.listId || listItem.listLevel !== void 0 || !!listItem.listPreset || !!listItem.listStyle || !!listItem.listType
25497
+ ) || fallback;
25498
+ }
25499
+ function createListInstance(context) {
25500
+ return context.nextListInstance++;
25501
+ }
25502
+ function createTableSerializeContext(element) {
25503
+ return {
25504
+ cellLayoutMap: computeTableCellLayout(
25505
+ element.trList || [],
25506
+ element.colgroup || []
25507
+ ),
25508
+ borderColor: element.borderColor,
25509
+ borderWidth: element.borderWidth,
25510
+ borderExternalWidth: element.borderExternalWidth
25511
+ };
25512
+ }
25513
+ function computeTableCellLayout(trList, colgroup) {
25514
+ const cellLayoutMap = /* @__PURE__ */ new WeakMap();
25515
+ if (!trList.length || !colgroup.length) {
25516
+ return cellLayoutMap;
25517
+ }
25518
+ const occupiedUntilRow = Array(colgroup.length).fill(0);
25519
+ for (let rowIndex = 0; rowIndex < trList.length; rowIndex++) {
25520
+ const tr = trList[rowIndex];
25521
+ let colIndex = 0;
25522
+ for (let tdIndex = 0; tdIndex < tr.tdList.length; tdIndex++) {
25523
+ while (colIndex < colgroup.length && occupiedUntilRow[colIndex] > rowIndex) {
25524
+ colIndex += 1;
25525
+ }
25526
+ const td = tr.tdList[tdIndex];
25527
+ let width = 0;
25528
+ for (let currentCol = colIndex; currentCol < colIndex + td.colspan && currentCol < colgroup.length; currentCol++) {
25529
+ width += colgroup[currentCol].width;
25530
+ occupiedUntilRow[currentCol] = Math.max(
25531
+ occupiedUntilRow[currentCol],
25532
+ rowIndex + td.rowspan
25533
+ );
25534
+ }
25535
+ cellLayoutMap.set(td, { width });
25536
+ colIndex += td.colspan;
25537
+ }
25538
+ }
25539
+ return cellLayoutMap;
25540
+ }
25541
+ function getTableWidthFromColgroup(colgroup) {
25542
+ if (!colgroup?.length) {
25543
+ return void 0;
25544
+ }
25545
+ return colgroup.reduce((sum, col) => sum + col.width, 0);
25546
+ }
25547
+ function normalizeHexColor(color, fallback) {
25548
+ const normalized = normalizeHexLiteral(color) || normalizeRgbColor(color) || normalizeBrowserColor(color);
25549
+ if (normalized) {
25550
+ return normalized;
25551
+ }
25552
+ return fallback ? normalizeHexLiteral(fallback) || void 0 : void 0;
25553
+ }
25554
+ function normalizeHexLiteral(color) {
25555
+ const value = color.trim().replace(/^#/, "");
25556
+ if (/^[\da-f]{3}$/i.test(value)) {
25557
+ return value.split("").map((part) => `${part}${part}`).join("").toUpperCase();
25558
+ }
25559
+ if (/^[\da-f]{4}$/i.test(value)) {
25560
+ return value.slice(0, 3).split("").map((part) => `${part}${part}`).join("").toUpperCase();
25561
+ }
25562
+ if (/^[\da-f]{6}$/i.test(value)) {
25563
+ return value.toUpperCase();
25564
+ }
25565
+ if (/^[\da-f]{8}$/i.test(value)) {
25566
+ return value.slice(0, 6).toUpperCase();
25567
+ }
25568
+ return void 0;
25569
+ }
25570
+ function normalizeRgbColor(color) {
25571
+ const match = color.trim().match(/^rgba?\((.+)\)$/i);
25572
+ if (!match) {
25573
+ return void 0;
25574
+ }
25575
+ const parts = match[1].replace(/\s*\/\s*/g, ",").split(/\s*,\s*|\s+/).filter(Boolean);
25576
+ if (parts.length < 3) {
25577
+ return void 0;
25578
+ }
25579
+ const red = parseRgbChannel(parts[0]);
25580
+ const green = parseRgbChannel(parts[1]);
25581
+ const blue = parseRgbChannel(parts[2]);
25582
+ if (red === null || green === null || blue === null) {
25583
+ return void 0;
25584
+ }
25585
+ const alpha = parts[3] !== void 0 ? parseAlphaChannel(parts[3]) : 1;
25586
+ if (alpha === null || alpha <= 0) {
25587
+ return void 0;
25588
+ }
25589
+ const flattened = alpha >= 1 ? [red, green, blue] : [
25590
+ flattenChannel(red, alpha),
25591
+ flattenChannel(green, alpha),
25592
+ flattenChannel(blue, alpha)
25593
+ ];
25594
+ return flattened.map(toHexChannel).join("");
25595
+ }
25596
+ function normalizeBrowserColor(color) {
25597
+ if (typeof document === "undefined") {
25598
+ return void 0;
25599
+ }
25600
+ const canvas = document.createElement("canvas");
25601
+ const context = canvas.getContext("2d");
25602
+ if (!context) {
25603
+ return void 0;
25604
+ }
25605
+ context.fillStyle = "#000000";
25606
+ context.fillStyle = color;
25607
+ const normalized = context.fillStyle;
25608
+ if (typeof normalized !== "string") {
25609
+ return void 0;
25610
+ }
25611
+ return normalizeHexLiteral(normalized) || normalizeRgbColor(normalized);
25612
+ }
25613
+ function parseRgbChannel(value) {
25614
+ if (value.endsWith("%")) {
25615
+ const percent = Number(value.slice(0, -1));
25616
+ if (!Number.isFinite(percent)) {
25617
+ return null;
25618
+ }
25619
+ return clampColorChannel(Math.round(percent / 100 * 255));
25620
+ }
25621
+ const channel = Number(value);
25622
+ if (!Number.isFinite(channel)) {
25623
+ return null;
25624
+ }
25625
+ return clampColorChannel(Math.round(channel));
25626
+ }
25627
+ function parseAlphaChannel(value) {
25628
+ if (value.endsWith("%")) {
25629
+ const percent = Number(value.slice(0, -1));
25630
+ if (!Number.isFinite(percent)) {
25631
+ return null;
25632
+ }
25633
+ return Math.min(Math.max(percent / 100, 0), 1);
25634
+ }
25635
+ const alpha = Number(value);
25636
+ if (!Number.isFinite(alpha)) {
25637
+ return null;
25638
+ }
25639
+ return Math.min(Math.max(alpha, 0), 1);
25640
+ }
25641
+ function clampColorChannel(value) {
25642
+ return Math.min(Math.max(value, 0), 255);
25643
+ }
25644
+ function flattenChannel(value, alpha) {
25645
+ return clampColorChannel(Math.round(255 * (1 - alpha) + value * alpha));
25646
+ }
25647
+ function toHexChannel(value) {
25648
+ return value.toString(16).padStart(2, "0").toUpperCase();
25649
+ }
25650
+ function pxBorderToDocxSize(width) {
25651
+ const safeWidth = Number.isFinite(width) && width > 0 ? width : 1;
25652
+ return Math.max(2, Math.round(safeWidth * 6));
25653
+ }
25654
+ function getRegularImageType(mime) {
25655
+ if (mime.includes("png")) return "png";
25656
+ if (mime.includes("jpeg") || mime.includes("jpg")) return "jpg";
25657
+ if (mime.includes("gif")) return "gif";
25658
+ if (mime.includes("bmp")) return "bmp";
25659
+ return null;
25660
+ }
25661
+ function normalizeDocxFileName(fileName) {
25662
+ const trimmed = fileName?.trim();
25663
+ if (!trimmed) {
25664
+ return DEFAULT_DOCX_FILE_NAME;
25665
+ }
25666
+ return trimmed.toLowerCase().endsWith(".docx") ? trimmed : `${trimmed}.docx`;
25667
+ }
25668
+ function pxToTwips(px) {
25669
+ return Math.round(px * 15);
25670
+ }
25671
+
25672
+ // src/utils/pdf.ts
25673
+ var import_pdf_lib = require("pdf-lib");
25674
+ var DEFAULT_PDF_FILE_NAME = "document.pdf";
25675
+ var DEFAULT_IMAGE_WIDTH2 = 320;
25676
+ var DEFAULT_IMAGE_HEIGHT2 = 180;
25677
+ var DEFAULT_LINE_HEIGHT2 = 1.15;
25678
+ var PAGE_REGION_GAP = 12;
25679
+ var SEPARATOR_HEIGHT = 12;
25680
+ var LIST_GAP = 8;
25681
+ var FOOTER_MIN_BAR_HEIGHT = 29;
25682
+ var PDF_TEXT_FALLBACKS = {
25683
+ "\u2297": "x",
25684
+ "\u2611": "[x]",
25685
+ "\u2612": "[x]",
25686
+ "\u2610": "[]",
25687
+ "\u2713": "v",
25688
+ "\u2714": "v",
25689
+ "\u2717": "x",
25690
+ "\u2715": "x",
25691
+ "\u25E6": "o",
25692
+ "\u25AA": "*",
25693
+ "\u25A0": "*"
25694
+ };
25695
+ var pdfTextCache = /* @__PURE__ */ new WeakMap();
25696
+ var bulletCharMap = {
25697
+ ["disc" /* DISC */]: "\u2022",
25698
+ ["circle" /* CIRCLE */]: "\u25E6",
25699
+ ["square" /* SQUARE */]: "\u25A0",
25700
+ ["checkbox" /* CHECKBOX */]: "\u2611"
25701
+ };
25702
+ async function exportEditorDataToPdf(payload, options = {}) {
25703
+ const editorOptions = payload.options;
25704
+ const pdfDoc = await import_pdf_lib.PDFDocument.create();
25705
+ const context = await createPdfContext(pdfDoc, editorOptions);
25706
+ const headerBlocks = editorOptions.header.disabled ? [] : await parseElementList(payload.data.header || [], context, editorOptions);
25707
+ const footerBlocks = editorOptions.footer.disabled ? [] : await parseElementList(payload.data.footer || [], context, editorOptions);
25708
+ const mainBlocks = await parseElementList(
25709
+ payload.data.main,
25710
+ context,
25711
+ editorOptions
25712
+ );
25713
+ const headerHeight = measureBlocksHeight(
25714
+ headerBlocks,
25715
+ context.contentWidth,
25716
+ context
25717
+ );
25718
+ const footerHeight = measureBlocksHeight(
25719
+ footerBlocks,
25720
+ context.contentWidth,
25721
+ context
25722
+ );
25723
+ const footerBarHeight = getFooterBarHeight(footerHeight, context);
25724
+ const pageNumberHeight = getPageNumberHeight(editorOptions.pageNumber);
25725
+ const contentTop = Math.max(
25726
+ context.margins[0],
25727
+ context.headerTop + headerHeight + (headerBlocks.length ? context.headerGap : 0)
25728
+ );
25729
+ const contentBottom = Math.max(
25730
+ context.margins[2],
25731
+ context.footerBottom + footerBarHeight,
25732
+ getReservedPageNumberBottom(editorOptions.pageNumber, pageNumberHeight)
25733
+ );
25734
+ const pages = renderMainBlocks(
25735
+ mainBlocks,
25736
+ context,
25737
+ contentTop,
25738
+ contentBottom
25739
+ );
25740
+ renderPageDecorations(
25741
+ pages,
25742
+ context,
25743
+ headerBlocks,
25744
+ footerBlocks,
25745
+ headerHeight,
25746
+ footerHeight,
25747
+ footerBarHeight,
25748
+ editorOptions.pageNumber
25749
+ );
25750
+ const bytes = await pdfDoc.save();
25751
+ return {
25752
+ blob: new Blob([bytes], { type: "application/pdf" }),
25753
+ fileName: normalizePdfFileName(options.fileName)
25754
+ };
25755
+ }
25756
+ async function createPdfContext(pdfDoc, options) {
25757
+ const [sans, sansBold, sansItalic, sansBoldItalic] = await Promise.all([
25758
+ pdfDoc.embedFont(import_pdf_lib.StandardFonts.Helvetica),
25759
+ pdfDoc.embedFont(import_pdf_lib.StandardFonts.HelveticaBold),
25760
+ pdfDoc.embedFont(import_pdf_lib.StandardFonts.HelveticaOblique),
25761
+ pdfDoc.embedFont(import_pdf_lib.StandardFonts.HelveticaBoldOblique)
25762
+ ]);
25763
+ const [serif, serifBold, serifItalic, serifBoldItalic] = await Promise.all([
25764
+ pdfDoc.embedFont(import_pdf_lib.StandardFonts.TimesRoman),
25765
+ pdfDoc.embedFont(import_pdf_lib.StandardFonts.TimesRomanBold),
25766
+ pdfDoc.embedFont(import_pdf_lib.StandardFonts.TimesRomanItalic),
25767
+ pdfDoc.embedFont(import_pdf_lib.StandardFonts.TimesRomanBoldItalic)
25768
+ ]);
25769
+ const [mono, monoBold, monoItalic, monoBoldItalic] = await Promise.all([
25770
+ pdfDoc.embedFont(import_pdf_lib.StandardFonts.Courier),
25771
+ pdfDoc.embedFont(import_pdf_lib.StandardFonts.CourierBold),
25772
+ pdfDoc.embedFont(import_pdf_lib.StandardFonts.CourierOblique),
25773
+ pdfDoc.embedFont(import_pdf_lib.StandardFonts.CourierBoldOblique)
25774
+ ]);
25775
+ const pageWidth = options.paperDirection === "horizontal" /* HORIZONTAL */ ? pxToPt(options.height) : pxToPt(options.width);
25776
+ const pageHeight = options.paperDirection === "horizontal" /* HORIZONTAL */ ? pxToPt(options.width) : pxToPt(options.height);
25777
+ const margins = options.margins.map(pxToPt);
25778
+ return {
25779
+ pdfDoc,
25780
+ options,
25781
+ fonts: {
25782
+ sans: {
25783
+ regular: sans,
25784
+ bold: sansBold,
25785
+ italic: sansItalic,
25786
+ boldItalic: sansBoldItalic
25787
+ },
25788
+ serif: {
25789
+ regular: serif,
25790
+ bold: serifBold,
25791
+ italic: serifItalic,
25792
+ boldItalic: serifBoldItalic
25793
+ },
25794
+ mono: {
25795
+ regular: mono,
25796
+ bold: monoBold,
25797
+ italic: monoItalic,
25798
+ boldItalic: monoBoldItalic
25799
+ }
25800
+ },
25801
+ pageWidth,
25802
+ pageHeight,
25803
+ margins,
25804
+ contentWidth: pageWidth - margins[1] - margins[3],
25805
+ headerTop: pxToPt(options.header.top),
25806
+ footerBottom: pxToPt(options.footer.bottom),
25807
+ headerGap: PAGE_REGION_GAP,
25808
+ footerGap: PAGE_REGION_GAP,
25809
+ separatorGap: SEPARATOR_HEIGHT,
25810
+ imageCache: /* @__PURE__ */ new Map()
25811
+ };
25812
+ }
25813
+ async function parseElementList(elementList, context, options) {
25814
+ const blocks = [];
25815
+ let inlineBuffer = [];
25816
+ const flushInlineBuffer = async () => {
25817
+ if (!inlineBuffer.length) return;
25818
+ blocks.push(...await parseInlineElements(inlineBuffer, context, options));
25819
+ inlineBuffer = [];
25820
+ };
25821
+ for (let i = 0; i < elementList.length; i++) {
25822
+ const element = elementList[i];
25823
+ if (element.type === "area" /* AREA */ && element.valueList?.length) {
25824
+ await flushInlineBuffer();
25825
+ blocks.push(
25826
+ ...await parseElementList(element.valueList, context, options)
25827
+ );
25828
+ continue;
25829
+ }
25830
+ if (element.type === "title" /* TITLE */ && element.valueList?.length) {
25831
+ await flushInlineBuffer();
25832
+ blocks.push(
25833
+ ...await parseInlineElements(element.valueList, context, options, {
25834
+ alignment: element.rowFlex,
25835
+ rowMargin: element.rowMargin,
25836
+ listMarker: void 0,
25837
+ titleLevel: element.level || "first" /* FIRST */
25838
+ })
25839
+ );
25840
+ continue;
25841
+ }
25842
+ if (element.type === "list" /* LIST */ && element.valueList?.length) {
25843
+ await flushInlineBuffer();
25844
+ blocks.push(...await parseListBlock(element, context, options));
25845
+ continue;
25846
+ }
25847
+ if (element.type === "table" /* TABLE */ && element.trList?.length) {
25848
+ await flushInlineBuffer();
25849
+ blocks.push(await parseTableBlock(element, context, options));
25850
+ continue;
25851
+ }
25852
+ if (element.type === "pageBreak" /* PAGE_BREAK */) {
25853
+ await flushInlineBuffer();
25854
+ blocks.push({ type: "pageBreak" });
25855
+ continue;
25856
+ }
25857
+ if (element.type === "separator" /* SEPARATOR */) {
25858
+ await flushInlineBuffer();
25859
+ blocks.push({ type: "separator" });
25860
+ continue;
25861
+ }
25862
+ if (element.type === "image" /* IMAGE */ && element.imgDisplay && element.imgDisplay !== "inline") {
25863
+ await flushInlineBuffer();
25864
+ const imageBlock = await createImageBlock(element, context);
25865
+ if (imageBlock) {
25866
+ blocks.push(imageBlock);
25867
+ }
25868
+ continue;
25869
+ }
25870
+ if (element.type === "block" /* BLOCK */) {
25871
+ await flushInlineBuffer();
25872
+ const blockText = getBlockFallbackText2(element);
25873
+ if (blockText) {
25874
+ blocks.push(
25875
+ ...await parseInlineElements(
25876
+ [{ value: blockText }],
25877
+ context,
25878
+ options
25879
+ )
25880
+ );
25881
+ }
25882
+ continue;
25883
+ }
25884
+ inlineBuffer.push(element);
25885
+ }
25886
+ await flushInlineBuffer();
25887
+ return blocks;
25888
+ }
25889
+ async function parseInlineElements(elementList, context, options, overrides = {}) {
25890
+ const paragraphs = [];
25891
+ let current = null;
25892
+ const getParagraphContext = (element) => ({
25893
+ alignment: overrides.alignment !== void 0 ? overrides.alignment : element?.rowFlex,
25894
+ rowMargin: overrides.rowMargin !== void 0 ? overrides.rowMargin : element?.rowMargin,
25895
+ listMarker: overrides.listMarker
25896
+ });
25897
+ const ensureParagraph = (element) => {
25898
+ if (!current) {
25899
+ current = {
25900
+ runs: [],
25901
+ context: getParagraphContext(element)
25902
+ };
25903
+ }
25904
+ return current;
25905
+ };
25906
+ const flushParagraph = (contextValue) => {
25907
+ if (!current) {
25908
+ if (!contextValue) return;
25909
+ paragraphs.push({
25910
+ type: "paragraph",
25911
+ runs: [],
25912
+ context: contextValue
25913
+ });
25914
+ return;
25915
+ }
25916
+ paragraphs.push({
25917
+ type: "paragraph",
25918
+ runs: current.runs,
25919
+ context: current.context
25920
+ });
25921
+ current = null;
25922
+ };
25923
+ const appendText = (element, text, factory, preserveTrailingBreak = false) => {
25924
+ const normalized = normalizeText2(text);
25925
+ const parts = normalized.split("\n");
25926
+ let lastSeparatorFlushedContent = false;
25927
+ for (let i = 0; i < parts.length; i++) {
25928
+ const segment = parts[i];
25929
+ if (segment) {
25930
+ ensureParagraph(element).runs.push(factory(segment));
25931
+ }
25932
+ if (i < parts.length - 1) {
25933
+ if (!current) {
25934
+ paragraphs.push({
25935
+ type: "paragraph",
25936
+ runs: [],
25937
+ context: getParagraphContext(element)
25938
+ });
25939
+ lastSeparatorFlushedContent = false;
25940
+ } else {
25941
+ flushParagraph();
25942
+ lastSeparatorFlushedContent = true;
25943
+ }
25944
+ }
25945
+ }
25946
+ if (preserveTrailingBreak && normalized.endsWith("\n") && lastSeparatorFlushedContent) {
25947
+ paragraphs.push({
25948
+ type: "paragraph",
25949
+ runs: [],
25950
+ context: getParagraphContext(element)
25951
+ });
25952
+ }
25953
+ };
25954
+ for (let i = 0; i < elementList.length; i++) {
25955
+ const element = elementList[i];
25956
+ if (element.type === "hyperlink" /* HYPERLINK */ && element.valueList?.length) {
25957
+ const children = element.valueList || [];
25958
+ for (let childIndex = 0; childIndex < children.length; childIndex++) {
25959
+ const child = children[childIndex];
25960
+ const text = normalizeText2(getInlineElementText2(child));
25961
+ if (!text) continue;
25962
+ appendText(
25963
+ element,
25964
+ text,
25965
+ (segment) => {
25966
+ const run = createTextRun2(
25967
+ child,
25968
+ options,
25969
+ overrides.titleLevel,
25970
+ segment
25971
+ );
25972
+ run.color = run.color || options.defaultHyperlinkColor;
25973
+ run.underline = true;
25974
+ return run;
25975
+ },
25976
+ i === elementList.length - 1 && childIndex === children.length - 1
25977
+ );
25978
+ }
25979
+ continue;
25980
+ }
25981
+ if (element.type === "image" /* IMAGE */) {
25982
+ const imageRun = await createInlineImageRun(element, context);
25983
+ if (imageRun) {
25984
+ ensureParagraph(element).runs.push(imageRun);
25985
+ }
25986
+ continue;
25987
+ }
25988
+ if (element.type === "columnBreak" /* COLUMN_BREAK */) {
25989
+ flushParagraph(getParagraphContext(element));
25990
+ continue;
25991
+ }
25992
+ if (element.type === "pageBreak" /* PAGE_BREAK */) {
25993
+ flushParagraph();
25994
+ paragraphs.push({ type: "pageBreak" });
25995
+ continue;
25996
+ }
25997
+ if (element.type === "tab" /* TAB */) {
25998
+ ensureParagraph(element).runs.push({
25999
+ type: "tab",
26000
+ width: pxToPt(options.defaultTabWidth)
26001
+ });
26002
+ continue;
26003
+ }
26004
+ if (element.type === "label" /* LABEL */) {
26005
+ const badgeRun = createBadgeRun(element, options, overrides.titleLevel);
26006
+ ensureParagraph(element).runs.push(badgeRun);
26007
+ continue;
26008
+ }
26009
+ const textValue = getInlineElementText2(element);
26010
+ if (!textValue) {
26011
+ continue;
26012
+ }
26013
+ appendText(
26014
+ element,
26015
+ textValue,
26016
+ (segment) => createTextRun2(element, options, overrides.titleLevel, segment),
26017
+ i === elementList.length - 1
26018
+ );
26019
+ }
26020
+ if (current) {
26021
+ flushParagraph();
26022
+ }
26023
+ return paragraphs.length ? paragraphs : [
26024
+ {
26025
+ type: "paragraph",
26026
+ runs: [],
26027
+ context: getParagraphContext()
26028
+ }
26029
+ ];
26030
+ }
26031
+ async function parseListBlock(element, context, options) {
26032
+ const zipList = zipElementList(element.valueList || []);
26033
+ const listItemMap = splitListElement(zipList);
26034
+ const blocks = [];
26035
+ const orderedCounts = Array(9).fill(0);
26036
+ for (const listItemElements of listItemMap.values()) {
26037
+ const itemElement = getListItemNumberingElement2(listItemElements, element);
26038
+ const marker = getListMarker(itemElement, orderedCounts);
26039
+ blocks.push(
26040
+ ...await parseInlineElements(listItemElements, context, options, {
26041
+ alignment: itemElement.rowFlex,
26042
+ rowMargin: itemElement.rowMargin,
26043
+ listMarker: marker
26044
+ })
26045
+ );
26046
+ }
26047
+ return blocks;
26048
+ }
26049
+ async function parseTableBlock(element, context, options) {
26050
+ const placements = computeTableCellPlacement(
26051
+ element.trList || [],
26052
+ element.colgroup || []
26053
+ );
26054
+ const rows = [];
26055
+ for (let rowIndex = 0; rowIndex < (element.trList || []).length; rowIndex++) {
26056
+ const tr = element.trList[rowIndex];
26057
+ const cells = [];
26058
+ for (let cellIndex = 0; cellIndex < tr.tdList.length; cellIndex++) {
26059
+ const td = tr.tdList[cellIndex];
26060
+ const placement = placements.get(td);
26061
+ cells.push({
26062
+ colspan: td.colspan,
26063
+ rowspan: td.rowspan,
26064
+ blocks: await parseElementList(td.value, context, options),
26065
+ colIndex: placement?.colIndex || 0,
26066
+ width: placement?.width || td.width || 0,
26067
+ padding: td.padding || options.table.tdPadding,
26068
+ verticalAlign: td.verticalAlign,
26069
+ backgroundColor: td.backgroundColor,
26070
+ borderColor: td.borderColor,
26071
+ borderTypes: td.borderTypes
26072
+ });
26073
+ }
26074
+ rows.push({
26075
+ height: Math.max(tr.height || 0, options.table.defaultTrMinHeight),
26076
+ cells
26077
+ });
26078
+ }
26079
+ return {
26080
+ type: "table",
26081
+ rows,
26082
+ colWidths: (element.colgroup || []).map((col) => col.width),
26083
+ borderType: element.borderType,
26084
+ borderColor: element.borderColor || options.table.defaultBorderColor,
26085
+ borderWidth: element.borderWidth || 1,
26086
+ borderExternalWidth: element.borderExternalWidth
26087
+ };
26088
+ }
26089
+ async function createImageBlock(element, context) {
26090
+ const image = await loadPdfImage(element.value, context);
26091
+ if (!image) {
26092
+ return null;
26093
+ }
26094
+ return {
26095
+ type: "image",
26096
+ image,
26097
+ width: pxToPt(
26098
+ Math.max(1, Math.round(element.width || DEFAULT_IMAGE_WIDTH2))
26099
+ ),
26100
+ height: pxToPt(
26101
+ Math.max(1, Math.round(element.height || DEFAULT_IMAGE_HEIGHT2))
26102
+ ),
26103
+ alignment: element.rowFlex
26104
+ };
26105
+ }
26106
+ async function createInlineImageRun(element, context) {
26107
+ const image = await loadPdfImage(element.value, context);
26108
+ if (!image) {
26109
+ return null;
26110
+ }
26111
+ return {
26112
+ type: "image",
26113
+ image,
26114
+ width: pxToPt(
26115
+ Math.max(1, Math.round(element.width || DEFAULT_IMAGE_WIDTH2))
26116
+ ),
26117
+ height: pxToPt(
26118
+ Math.max(1, Math.round(element.height || DEFAULT_IMAGE_HEIGHT2))
26119
+ )
26120
+ };
26121
+ }
26122
+ function createTextRun2(element, options, titleLevel, text) {
26123
+ const titleSize = getTitleSize(titleLevel, options);
26124
+ const size = element.size || titleSize || options.defaultSize;
26125
+ const isTitle = !!titleLevel;
26126
+ return {
26127
+ type: "text",
26128
+ text,
26129
+ size,
26130
+ font: element.font || options.defaultFont,
26131
+ bold: isTitle ? true : !!element.bold,
26132
+ italic: !!element.italic,
26133
+ underline: !!element.underline,
26134
+ strikeout: !!element.strikeout,
26135
+ color: element.color || (isTitle ? "#000000" : void 0),
26136
+ highlight: element.highlight,
26137
+ superscript: element.type === "superscript" /* SUPERSCRIPT */,
26138
+ subscript: element.type === "subscript" /* SUBSCRIPT */
26139
+ };
26140
+ }
26141
+ function createBadgeRun(element, options, titleLevel) {
26142
+ const titleSize = getTitleSize(titleLevel, options);
26143
+ return {
26144
+ type: "badge",
26145
+ text: element.value,
26146
+ size: element.size || titleSize || options.defaultSize,
26147
+ font: element.font || options.defaultFont,
26148
+ bold: titleLevel ? true : !!element.bold,
26149
+ italic: !!element.italic,
26150
+ underline: !!element.underline,
26151
+ strikeout: !!element.strikeout,
26152
+ color: element.label?.color || element.color,
26153
+ backgroundColor: element.label?.backgroundColor,
26154
+ borderColor: element.label?.borderColor,
26155
+ padding: element.label?.padding || [2, 4, 2, 4]
26156
+ };
26157
+ }
26158
+ function renderMainBlocks(blocks, context, contentTop, contentBottom) {
26159
+ const pages = [];
26160
+ const contentEnd = context.pageHeight - contentBottom;
26161
+ const createPage = () => {
26162
+ const page = context.pdfDoc.addPage([
26163
+ context.pageWidth,
26164
+ context.pageHeight
26165
+ ]);
26166
+ const state = {
26167
+ page,
26168
+ cursorY: contentTop,
26169
+ isEmpty: true
26170
+ };
26171
+ pages.push(state);
26172
+ return state;
26173
+ };
26174
+ let currentPage = createPage();
26175
+ const ensureSpace = (height) => {
26176
+ if (currentPage.cursorY + height <= contentEnd || currentPage.isEmpty) {
26177
+ return;
26178
+ }
26179
+ currentPage = createPage();
26180
+ };
26181
+ for (let i = 0; i < blocks.length; i++) {
26182
+ const block = blocks[i];
26183
+ if (block.type === "pageBreak") {
26184
+ currentPage = createPage();
26185
+ continue;
26186
+ }
26187
+ if (block.type === "paragraph") {
26188
+ currentPage = renderParagraphAcrossPages(
26189
+ block,
26190
+ currentPage,
26191
+ pages,
26192
+ context,
26193
+ contentTop,
26194
+ contentEnd
26195
+ );
26196
+ continue;
26197
+ }
26198
+ if (block.type === "separator") {
26199
+ ensureSpace(context.separatorGap);
26200
+ renderSeparator(
26201
+ currentPage.page,
26202
+ context,
26203
+ currentPage.cursorY,
26204
+ context.margins[3],
26205
+ context.contentWidth
26206
+ );
26207
+ currentPage.cursorY += context.separatorGap;
26208
+ currentPage.isEmpty = false;
26209
+ continue;
26210
+ }
26211
+ if (block.type === "image") {
26212
+ ensureSpace(block.height);
26213
+ renderImageBlock(currentPage.page, block, context, currentPage.cursorY);
26214
+ currentPage.cursorY += block.height;
26215
+ currentPage.isEmpty = false;
26216
+ continue;
26217
+ }
26218
+ const tableLayout = layoutTable(block, context.contentWidth, context);
26219
+ currentPage = renderTableAcrossPages(
26220
+ block,
26221
+ tableLayout,
26222
+ currentPage,
26223
+ pages,
26224
+ context,
26225
+ contentTop,
26226
+ contentEnd
26227
+ );
26228
+ }
26229
+ return pages;
26230
+ }
26231
+ function renderParagraphAcrossPages(block, currentPage, pages, context, contentTop, contentEnd) {
26232
+ const layout = layoutParagraph(block, context.contentWidth, context);
26233
+ for (let lineIndex = 0; lineIndex < layout.lines.length; lineIndex++) {
26234
+ const line = layout.lines[lineIndex];
26235
+ if (currentPage.cursorY + line.height > contentEnd && !currentPage.isEmpty) {
26236
+ const page = context.pdfDoc.addPage([
26237
+ context.pageWidth,
26238
+ context.pageHeight
26239
+ ]);
26240
+ currentPage = {
26241
+ page,
26242
+ cursorY: contentTop,
26243
+ isEmpty: true
26244
+ };
26245
+ pages.push(currentPage);
26246
+ }
26247
+ renderParagraphLine(
26248
+ currentPage.page,
26249
+ block,
26250
+ line,
26251
+ lineIndex === 0,
26252
+ layout,
26253
+ context,
26254
+ currentPage.cursorY,
26255
+ context.margins[3],
26256
+ context.contentWidth
26257
+ );
26258
+ currentPage.cursorY += line.height;
26259
+ currentPage.isEmpty = false;
26260
+ }
26261
+ return currentPage;
26262
+ }
26263
+ function renderTableAcrossPages(block, tableLayout, currentPage, pages, context, contentTop, contentEnd) {
26264
+ const scaledColWidths = scaleColumnWidths(
26265
+ block.colWidths,
26266
+ context.contentWidth
26267
+ );
26268
+ let tableTop = currentPage.cursorY;
26269
+ for (let rowIndex = 0; rowIndex < block.rows.length; rowIndex++) {
26270
+ const row = block.rows[rowIndex];
26271
+ const rowHeight = tableLayout.rowHeights[rowIndex];
26272
+ const spanHeight = getSpanningRowHeight(
26273
+ block.rows,
26274
+ tableLayout.rowHeights,
26275
+ rowIndex
26276
+ );
26277
+ if (currentPage.cursorY + spanHeight > contentEnd && !currentPage.isEmpty) {
26278
+ const page = context.pdfDoc.addPage([
26279
+ context.pageWidth,
26280
+ context.pageHeight
26281
+ ]);
26282
+ currentPage = {
26283
+ page,
26284
+ cursorY: contentTop,
26285
+ isEmpty: true
26286
+ };
26287
+ pages.push(currentPage);
26288
+ tableTop = currentPage.cursorY;
26289
+ }
26290
+ const rowTop = currentPage.cursorY;
26291
+ for (let cellIndex = 0; cellIndex < row.cells.length; cellIndex++) {
26292
+ const cell = row.cells[cellIndex];
26293
+ const cellX = context.margins[3] + getColumnOffset(scaledColWidths, cell.colIndex);
26294
+ const cellWidth = getColumnSpanWidth(
26295
+ scaledColWidths,
26296
+ cell.colIndex,
26297
+ cell.colspan
26298
+ );
26299
+ const cellHeight = getRowSpanHeight(
26300
+ tableLayout.rowHeights,
26301
+ rowIndex,
26302
+ cell.rowspan
26303
+ );
26304
+ renderTableCell(
26305
+ currentPage.page,
26306
+ cell,
26307
+ context,
26308
+ block,
26309
+ cellX,
26310
+ rowTop,
26311
+ cellWidth,
26312
+ cellHeight
26313
+ );
26314
+ }
26315
+ currentPage.cursorY += rowHeight;
26316
+ currentPage.isEmpty = false;
26317
+ }
26318
+ return currentPage;
26319
+ }
26320
+ function renderPageDecorations(pages, context, headerBlocks, footerBlocks, headerHeight, footerHeight, footerBarHeight, pageNumber) {
26321
+ const totalPages = pages.length;
26322
+ for (let index = 0; index < pages.length; index++) {
26323
+ const pageState = pages[index];
26324
+ if (headerBlocks.length) {
26325
+ renderBlocksInRegion(
26326
+ pageState.page,
26327
+ headerBlocks,
26328
+ context,
26329
+ context.margins[3],
26330
+ context.headerTop,
26331
+ context.contentWidth
26332
+ );
26333
+ }
26334
+ if (footerBarHeight > 0) {
26335
+ if (context.options.footer.backgroundColor) {
26336
+ pageState.page.drawRectangle({
26337
+ x: 0,
26338
+ y: context.footerBottom,
26339
+ width: context.pageWidth,
26340
+ height: footerBarHeight,
26341
+ color: toPdfColor(context.options.footer.backgroundColor, "#FFFFFF")
26342
+ });
26343
+ }
26344
+ if (footerBlocks.length) {
26345
+ const footerTop = context.pageHeight - context.footerBottom - footerBarHeight;
26346
+ const footerContentTop = footerTop + Math.max(0, (footerBarHeight - footerHeight) / 2);
26347
+ renderBlocksInRegion(
26348
+ pageState.page,
26349
+ footerBlocks,
26350
+ context,
26351
+ context.margins[3],
26352
+ footerContentTop,
26353
+ context.contentWidth
26354
+ );
26355
+ }
26356
+ }
26357
+ renderPageNumber(pageState.page, context, pageNumber, index, totalPages);
26358
+ }
26359
+ }
26360
+ function renderBlocksInRegion(page, blocks, context, x, top, width) {
26361
+ let cursorY = top;
26362
+ for (let i = 0; i < blocks.length; i++) {
26363
+ const block = blocks[i];
26364
+ if (block.type === "pageBreak") {
26365
+ continue;
26366
+ }
26367
+ if (block.type === "paragraph") {
26368
+ const layout = layoutParagraph(block, width, context);
26369
+ for (let lineIndex = 0; lineIndex < layout.lines.length; lineIndex++) {
26370
+ const line = layout.lines[lineIndex];
26371
+ renderParagraphLine(
26372
+ page,
26373
+ block,
26374
+ line,
26375
+ lineIndex === 0,
26376
+ layout,
26377
+ context,
26378
+ cursorY,
26379
+ x,
26380
+ width
26381
+ );
26382
+ cursorY += line.height;
26383
+ }
26384
+ continue;
26385
+ }
26386
+ if (block.type === "separator") {
26387
+ renderSeparator(page, context, cursorY, x, width);
26388
+ cursorY += context.separatorGap;
26389
+ continue;
26390
+ }
26391
+ if (block.type === "image") {
26392
+ renderImageBlock(page, block, context, cursorY, x, width);
26393
+ cursorY += block.height;
26394
+ continue;
26395
+ }
26396
+ const tableLayout = layoutTable(block, width, context);
26397
+ const scaledColWidths = scaleColumnWidths(block.colWidths, width);
26398
+ for (let rowIndex = 0; rowIndex < block.rows.length; rowIndex++) {
26399
+ const row = block.rows[rowIndex];
26400
+ const rowTop = cursorY;
26401
+ for (let cellIndex = 0; cellIndex < row.cells.length; cellIndex++) {
26402
+ const cell = row.cells[cellIndex];
26403
+ const cellX = x + getColumnOffset(scaledColWidths, cell.colIndex);
26404
+ const cellWidth = getColumnSpanWidth(
26405
+ scaledColWidths,
26406
+ cell.colIndex,
26407
+ cell.colspan
26408
+ );
26409
+ const cellHeight = getRowSpanHeight(
26410
+ tableLayout.rowHeights,
26411
+ rowIndex,
26412
+ cell.rowspan
26413
+ );
26414
+ renderTableCell(
26415
+ page,
26416
+ cell,
26417
+ context,
26418
+ block,
26419
+ cellX,
26420
+ rowTop,
26421
+ cellWidth,
26422
+ cellHeight
26423
+ );
26424
+ }
26425
+ cursorY += tableLayout.rowHeights[rowIndex];
26426
+ }
26427
+ }
26428
+ }
26429
+ function renderParagraphLine(page, block, line, isFirstLine, layout, context, top, baseX, regionWidth) {
26430
+ const alignment = normalizeAlignment(block.context.alignment);
26431
+ const lineWidth = line.width;
26432
+ const availableWidth = Math.max(
26433
+ 1,
26434
+ regionWidth - layout.listIndent - layout.markerWidth
26435
+ );
26436
+ const justifyExtra = alignment === "justify" /* JUSTIFY */ && !isLastParagraphLine(layout, line) ? getJustifyExtra(line, availableWidth) : 0;
26437
+ let offsetX = 0;
26438
+ if (alignment === "center" /* CENTER */) {
26439
+ offsetX = (availableWidth - lineWidth) / 2;
26440
+ } else if (alignment === "right" /* RIGHT */) {
26441
+ offsetX = availableWidth - lineWidth;
26442
+ }
26443
+ const lineStart = baseX + layout.listIndent + layout.markerWidth + Math.max(0, offsetX);
26444
+ if (isFirstLine && block.context.listMarker) {
26445
+ const markerRun = getMarkerRun(block, context);
26446
+ const markerText = block.context.listMarker.text;
26447
+ drawTextRun(
26448
+ page,
26449
+ markerRun,
26450
+ markerText,
26451
+ baseX + layout.listIndent,
26452
+ top,
26453
+ line.height,
26454
+ context
26455
+ );
26456
+ }
26457
+ let cursorX = lineStart;
26458
+ for (let index = 0; index < line.fragments.length; index++) {
26459
+ const fragment = line.fragments[index];
26460
+ if (fragment.kind === "space" && justifyExtra > 0) {
26461
+ cursorX += justifyExtra;
26462
+ }
26463
+ drawLineFragment(page, fragment, cursorX, top, line.height, context);
26464
+ cursorX += fragment.width;
26465
+ }
26466
+ }
26467
+ function renderSeparator(page, context, top, x, width) {
26468
+ const lineY = toPdfY(context.pageHeight, top + SEPARATOR_HEIGHT / 2);
26469
+ page.drawLine({
26470
+ start: { x, y: lineY },
26471
+ end: { x: x + width, y: lineY },
26472
+ thickness: 1,
26473
+ color: (0, import_pdf_lib.rgb)(0.6, 0.6, 0.6)
26474
+ });
26475
+ }
26476
+ function renderImageBlock(page, block, context, top, baseX = context.margins[3], width = context.contentWidth) {
26477
+ const alignment = normalizeAlignment(block.alignment);
26478
+ let x = baseX;
26479
+ if (alignment === "center" /* CENTER */) {
26480
+ x += Math.max(0, (width - block.width) / 2);
26481
+ } else if (alignment === "right" /* RIGHT */) {
26482
+ x += Math.max(0, width - block.width);
26483
+ }
26484
+ page.drawImage(block.image, {
26485
+ x,
26486
+ y: toPdfY(context.pageHeight, top, block.height),
26487
+ width: block.width,
26488
+ height: block.height
26489
+ });
26490
+ }
26491
+ function renderTableCell(page, cell, context, table, x, top, width, height) {
26492
+ if (cell.backgroundColor) {
26493
+ page.drawRectangle({
26494
+ x,
26495
+ y: toPdfY(context.pageHeight, top, height),
26496
+ width,
26497
+ height,
26498
+ color: toPdfColor(cell.backgroundColor)
26499
+ });
26500
+ }
26501
+ drawTableCellBorders(page, cell, context, table, x, top, width, height);
26502
+ const padding = getPadding(cell.padding || defaultTableOption.tdPadding).map(
26503
+ pxToPt
26504
+ );
26505
+ const contentWidth = Math.max(1, width - padding[1] - padding[3]);
26506
+ const contentHeight = measureBlocksHeight(cell.blocks, contentWidth, context);
26507
+ let contentTop = top + padding[0];
26508
+ if (cell.verticalAlign === VerticalAlign.CENTER) {
26509
+ contentTop = top + (height - contentHeight) / 2;
26510
+ } else if (cell.verticalAlign === "bottom" /* BOTTOM */) {
26511
+ contentTop = top + height - contentHeight - padding[2];
26512
+ }
26513
+ renderBlocksInRegion(
26514
+ page,
26515
+ cell.blocks,
26516
+ context,
26517
+ x + padding[3],
26518
+ contentTop,
26519
+ contentWidth
26520
+ );
26521
+ }
26522
+ function renderPageNumber(page, context, pageNumber, pageIndex, totalPages) {
26523
+ if (pageNumber.disabled || pageIndex < pageNumber.fromPageNo || Number.isInteger(pageNumber.maxPageNo) && pageIndex >= pageNumber.maxPageNo) {
26524
+ return;
26525
+ }
26526
+ let text = pageNumber.format || FORMAT_PLACEHOLDER.PAGE_NO;
26527
+ const currentValue = pageIndex + pageNumber.startPageNo - pageNumber.fromPageNo;
26528
+ const totalValue = totalPages - pageNumber.fromPageNo;
26529
+ text = text.replace(
26530
+ new RegExp(FORMAT_PLACEHOLDER.PAGE_NO, "g"),
26531
+ `${currentValue}`
26532
+ );
26533
+ text = text.replace(
26534
+ new RegExp(FORMAT_PLACEHOLDER.PAGE_COUNT, "g"),
26535
+ `${Math.max(0, totalValue)}`
26536
+ );
26537
+ const font = getFont(
26538
+ pageNumber.font || context.options.defaultFont,
26539
+ false,
26540
+ false,
26541
+ context
26542
+ );
26543
+ const size = pageNumber.size || 12;
26544
+ const bottom = pxToPt(pageNumber.bottom || 0);
26545
+ const safeText = sanitizeTextForPdf(text, font);
26546
+ const width = font.widthOfTextAtSize(safeText, size);
26547
+ const descenderHeight = Math.max(
26548
+ 0,
26549
+ font.heightAtSize(size) - font.heightAtSize(size, { descender: false })
26550
+ );
26551
+ let x = context.margins[3];
26552
+ const alignment = normalizeAlignment(pageNumber.rowFlex);
26553
+ if (alignment === "center" /* CENTER */) {
26554
+ x = (context.pageWidth - width) / 2;
26555
+ } else if (alignment === "right" /* RIGHT */) {
26556
+ x = context.pageWidth - context.margins[1] - width;
26557
+ }
26558
+ page.drawText(safeText, {
26559
+ x,
26560
+ // Canvas draw uses the alphabetic baseline at `pageHeight - bottom`.
26561
+ // pdf-lib positions text from the text box bottom, so compensate by the
26562
+ // descender height to keep the baseline aligned.
26563
+ y: bottom - descenderHeight,
26564
+ size,
26565
+ font,
26566
+ color: toPdfColor(pageNumber.color, "#000000")
26567
+ });
26568
+ }
26569
+ function layoutParagraph(block, width, context) {
26570
+ const markerWidth = getMarkerWidth(block, context);
26571
+ const listIndent = block.context.listMarker ? pxToPt(block.context.listMarker.level * INDENT_PER_LEVEL) : 0;
26572
+ const availableWidth = Math.max(1, width - listIndent - markerWidth);
26573
+ const tokens = tokenizeParagraphRuns(block.runs, context);
26574
+ const lines = [];
26575
+ let line = {
26576
+ fragments: [],
26577
+ width: 0,
26578
+ height: getEmptyLineHeight(block, context)
26579
+ };
26580
+ const commitLine = () => {
26581
+ trimTrailingSpaces(line);
26582
+ lines.push(line);
26583
+ line = {
26584
+ fragments: [],
26585
+ width: 0,
26586
+ height: getEmptyLineHeight(block, context)
26587
+ };
26588
+ };
26589
+ for (let i = 0; i < tokens.length; i++) {
26590
+ let token = tokens[i];
26591
+ if (token.kind === "space" && !line.fragments.length) {
26592
+ continue;
26593
+ }
26594
+ if (token.width > availableWidth && token.kind === "text" && token.run.type === "text") {
26595
+ const segments = splitTextToken(token, availableWidth, context);
26596
+ for (let segmentIndex = 0; segmentIndex < segments.length; segmentIndex++) {
26597
+ tokens.splice(i + segmentIndex, 0, segments[segmentIndex]);
26598
+ }
26599
+ continue;
26600
+ }
26601
+ if (line.width + token.width > availableWidth && line.fragments.length) {
26602
+ commitLine();
26603
+ i--;
26604
+ continue;
26605
+ }
26606
+ line.fragments.push(token);
26607
+ line.width += token.width;
26608
+ line.height = Math.max(line.height, token.height);
26609
+ }
26610
+ if (line.fragments.length || !lines.length) {
26611
+ commitLine();
26612
+ }
26613
+ return {
26614
+ lines,
26615
+ height: lines.reduce((sum, current) => sum + current.height, 0),
26616
+ markerWidth,
26617
+ listIndent
26618
+ };
26619
+ }
26620
+ function tokenizeParagraphRuns(runs, context) {
26621
+ const fragments = [];
26622
+ for (let index = 0; index < runs.length; index++) {
26623
+ const run = runs[index];
26624
+ if (run.type === "tab") {
26625
+ fragments.push({
26626
+ kind: "tab",
26627
+ width: run.width,
26628
+ height: 0,
26629
+ run
26630
+ });
26631
+ continue;
26632
+ }
26633
+ if (run.type === "image") {
26634
+ fragments.push({
26635
+ kind: "image",
26636
+ width: run.width,
26637
+ height: run.height,
26638
+ run
26639
+ });
26640
+ continue;
26641
+ }
26642
+ if (run.type === "badge") {
26643
+ const badgeWidth = measureBadgeWidth(run, context);
26644
+ const badgeHeight = measureBadgeHeight(run);
26645
+ fragments.push({
26646
+ kind: "badge",
26647
+ width: badgeWidth,
26648
+ height: badgeHeight,
26649
+ run
26650
+ });
26651
+ continue;
26652
+ }
26653
+ const parts = run.text.split(/(\s+)/);
26654
+ for (let partIndex = 0; partIndex < parts.length; partIndex++) {
26655
+ const part = parts[partIndex];
26656
+ if (!part) continue;
26657
+ const isWhitespace = /^\s+$/.test(part);
26658
+ fragments.push({
26659
+ kind: isWhitespace ? "space" : "text",
26660
+ width: measureTextWidth(part, run, context),
26661
+ height: getRunHeight(run),
26662
+ run: { ...run, text: part }
26663
+ });
26664
+ }
26665
+ }
26666
+ return fragments;
26667
+ }
26668
+ function splitTextToken(token, availableWidth, context) {
26669
+ if (token.run.type !== "text") {
26670
+ return [token];
26671
+ }
26672
+ const chars = splitText(token.run.text);
26673
+ const result = [];
26674
+ let current = "";
26675
+ for (let i = 0; i < chars.length; i++) {
26676
+ const next = current + chars[i];
26677
+ const width = measureTextWidth(next, token.run, context);
26678
+ if (width > availableWidth && current) {
26679
+ result.push({
26680
+ kind: "text",
26681
+ width: measureTextWidth(current, token.run, context),
26682
+ height: getRunHeight(token.run),
26683
+ run: { ...token.run, text: current }
26684
+ });
26685
+ current = chars[i];
26686
+ } else {
26687
+ current = next;
26688
+ }
26689
+ }
26690
+ if (current) {
26691
+ result.push({
26692
+ kind: /^\s+$/.test(current) ? "space" : "text",
26693
+ width: measureTextWidth(current, token.run, context),
26694
+ height: getRunHeight(token.run),
26695
+ run: { ...token.run, text: current }
26696
+ });
26697
+ }
26698
+ return result.length ? result : [token];
26699
+ }
26700
+ function trimTrailingSpaces(line) {
26701
+ while (line.fragments.length && line.fragments[line.fragments.length - 1].kind === "space") {
26702
+ const fragment = line.fragments.pop();
26703
+ line.width -= fragment.width;
26704
+ }
26705
+ }
26706
+ function layoutTable(table, width, context) {
26707
+ const rowHeights = table.rows.map(
26708
+ (row) => Math.max(
26709
+ pxToPt(row.height),
26710
+ pxToPt(context.options.table.defaultTrMinHeight)
26711
+ )
26712
+ );
26713
+ const scaledColWidths = scaleColumnWidths(table.colWidths, width);
26714
+ for (let rowIndex = 0; rowIndex < table.rows.length; rowIndex++) {
26715
+ const row = table.rows[rowIndex];
26716
+ for (let cellIndex = 0; cellIndex < row.cells.length; cellIndex++) {
26717
+ const cell = row.cells[cellIndex];
26718
+ const cellWidth = getColumnSpanWidth(
26719
+ scaledColWidths,
26720
+ cell.colIndex,
26721
+ cell.colspan
26722
+ );
26723
+ const padding = getPadding(
26724
+ cell.padding || defaultTableOption.tdPadding
26725
+ ).map(pxToPt);
26726
+ const contentWidth = Math.max(1, cellWidth - padding[1] - padding[3]);
26727
+ const contentHeight = measureBlocksHeight(cell.blocks, contentWidth, context) + padding[0] + padding[2];
26728
+ const spanHeight = getRowSpanHeight(rowHeights, rowIndex, cell.rowspan);
26729
+ if (contentHeight > spanHeight) {
26730
+ rowHeights[rowIndex + cell.rowspan - 1] += contentHeight - spanHeight;
26731
+ }
26732
+ }
26733
+ }
26734
+ return {
26735
+ rowHeights,
26736
+ totalHeight: rowHeights.reduce((sum, height) => sum + height, 0)
26737
+ };
26738
+ }
26739
+ function measureBlocksHeight(blocks, width, context) {
26740
+ let height = 0;
26741
+ for (let i = 0; i < blocks.length; i++) {
26742
+ const block = blocks[i];
26743
+ if (block.type === "pageBreak") {
26744
+ continue;
26745
+ }
26746
+ if (block.type === "paragraph") {
26747
+ height += layoutParagraph(block, width, context).height;
26748
+ continue;
26749
+ }
26750
+ if (block.type === "separator") {
26751
+ height += context.separatorGap;
26752
+ continue;
26753
+ }
26754
+ if (block.type === "image") {
26755
+ height += block.height;
26756
+ continue;
26757
+ }
26758
+ height += layoutTable(block, width, context).totalHeight;
26759
+ }
26760
+ return height;
26761
+ }
26762
+ function drawLineFragment(page, fragment, x, top, lineHeight, context) {
26763
+ if (fragment.run.type === "tab") {
26764
+ return;
26765
+ }
26766
+ if (fragment.run.type === "image") {
26767
+ const imageTop = top + (lineHeight - fragment.run.height) / 2;
26768
+ page.drawImage(fragment.run.image, {
26769
+ x,
26770
+ y: toPdfY(context.pageHeight, imageTop, fragment.run.height),
26771
+ width: fragment.run.width,
26772
+ height: fragment.run.height
26773
+ });
26774
+ return;
26775
+ }
26776
+ if (fragment.run.type === "badge") {
26777
+ const badgeHeight = measureBadgeHeight(fragment.run);
26778
+ const badgeTop = top + (lineHeight - badgeHeight) / 2;
26779
+ const padding = getPadding(fragment.run.padding || [2, 4, 2, 4]).map(
26780
+ pxToPt
26781
+ );
26782
+ page.drawRectangle({
26783
+ x,
26784
+ y: toPdfY(context.pageHeight, badgeTop, badgeHeight),
26785
+ width: fragment.width,
26786
+ height: badgeHeight,
26787
+ color: toPdfColor(fragment.run.backgroundColor, "#FFFFFF"),
26788
+ borderColor: fragment.run.borderColor ? toPdfColor(fragment.run.borderColor) : void 0,
26789
+ borderWidth: fragment.run.borderColor ? 0.75 : void 0
26790
+ });
26791
+ drawTextRun(
26792
+ page,
26793
+ fragment.run,
26794
+ fragment.run.text,
26795
+ x + padding[3],
26796
+ badgeTop + padding[0],
26797
+ badgeHeight - padding[0] - padding[2],
26798
+ context
26799
+ );
26800
+ return;
26801
+ }
26802
+ if (fragment.run.type !== "text") {
26803
+ return;
26804
+ }
26805
+ drawTextRun(
26806
+ page,
26807
+ fragment.run,
26808
+ fragment.run.text,
26809
+ x,
26810
+ top,
26811
+ lineHeight,
26812
+ context
26813
+ );
26814
+ }
26815
+ function drawTextRun(page, run, text, x, top, lineHeight, context) {
26816
+ const resolved = resolveTextMetrics(run, context);
26817
+ const safeText = sanitizeTextForPdf(text, resolved.font);
26818
+ let textTop = top + (lineHeight - resolved.size) / 2;
26819
+ if (run.type === "text" && run.superscript) {
26820
+ textTop -= resolved.size * 0.25;
26821
+ }
26822
+ if (run.type === "text" && run.subscript) {
26823
+ textTop += resolved.size * 0.2;
26824
+ }
26825
+ const textY = toPdfY(context.pageHeight, textTop, resolved.size);
26826
+ if ("highlight" in run && run.highlight) {
26827
+ page.drawRectangle({
26828
+ x,
26829
+ y: textY,
26830
+ width: resolved.font.widthOfTextAtSize(safeText, resolved.size),
26831
+ height: resolved.size * 1.05,
26832
+ color: toPdfColor(run.highlight)
26833
+ });
26834
+ }
26835
+ page.drawText(safeText, {
26836
+ x,
26837
+ y: textY,
26838
+ size: resolved.size,
26839
+ font: resolved.font,
26840
+ color: toPdfColor(run.color, "#000000")
26841
+ });
26842
+ const textWidth = resolved.font.widthOfTextAtSize(safeText, resolved.size);
26843
+ if (run.underline) {
26844
+ const underlineY = textY - 1;
26845
+ page.drawLine({
26846
+ start: { x, y: underlineY },
26847
+ end: { x: x + textWidth, y: underlineY },
26848
+ thickness: 0.75,
26849
+ color: toPdfColor(run.color, "#000000")
26850
+ });
26851
+ }
26852
+ if (run.strikeout) {
26853
+ const strikeY = textY + resolved.size * 0.35;
26854
+ page.drawLine({
26855
+ start: { x, y: strikeY },
26856
+ end: { x: x + textWidth, y: strikeY },
26857
+ thickness: 0.75,
26858
+ color: toPdfColor(run.color, "#000000")
26859
+ });
26860
+ }
26861
+ }
26862
+ function drawTableCellBorders(page, cell, context, table, x, top, width, height) {
26863
+ const tableColor = table.borderColor || context.options.table.defaultBorderColor;
26864
+ const innerWidth = table.borderWidth || 1;
26865
+ const outerWidth = table.borderExternalWidth || innerWidth;
26866
+ const color = cell.borderColor || tableColor;
26867
+ const isEmpty = table.borderType === "empty" /* EMPTY */;
26868
+ const isExternal = table.borderType === "external" /* EXTERNAL */;
26869
+ const isInternal = table.borderType === "internal" /* INTERNAL */;
26870
+ const isDash = table.borderType === "dash" /* DASH */;
26871
+ const dashArray = isDash ? [3, 3] : void 0;
26872
+ const lineColor = toPdfColor(color, "#000000");
26873
+ const bottomY = toPdfY(context.pageHeight, top, height);
26874
+ const topY = toPdfY(context.pageHeight, top);
26875
+ const rightX = x + width;
26876
+ const drawEdge = (startX, startY, endX, endY, thickness) => {
26877
+ page.drawLine({
26878
+ start: { x: startX, y: startY },
26879
+ end: { x: endX, y: endY },
26880
+ thickness,
26881
+ color: lineColor,
26882
+ dashArray
26883
+ });
26884
+ };
26885
+ if (cell.borderTypes?.length) {
26886
+ if (cell.borderTypes.includes("top" /* TOP */)) {
26887
+ drawEdge(x, topY, rightX, topY, innerWidth);
26888
+ }
26889
+ if (cell.borderTypes.includes("right" /* RIGHT */)) {
26890
+ drawEdge(rightX, topY, rightX, bottomY, innerWidth);
26891
+ }
26892
+ if (cell.borderTypes.includes("bottom" /* BOTTOM */)) {
26893
+ drawEdge(x, bottomY, rightX, bottomY, innerWidth);
26894
+ }
26895
+ if (cell.borderTypes.includes("left" /* LEFT */)) {
26896
+ drawEdge(x, topY, x, bottomY, innerWidth);
26897
+ }
26898
+ }
26899
+ if (cell.borderColor && !cell.borderTypes?.length) {
26900
+ drawEdge(x, topY, rightX, topY, innerWidth);
26901
+ drawEdge(rightX, topY, rightX, bottomY, innerWidth);
26902
+ drawEdge(x, bottomY, rightX, bottomY, innerWidth);
26903
+ drawEdge(x, topY, x, bottomY, innerWidth);
26904
+ return;
26905
+ }
26906
+ if (isEmpty) {
26907
+ return;
26908
+ }
26909
+ if (!isInternal) {
26910
+ drawEdge(x, topY, rightX, topY, outerWidth);
26911
+ drawEdge(x, topY, x, bottomY, outerWidth);
26912
+ drawEdge(rightX, topY, rightX, bottomY, outerWidth);
26913
+ drawEdge(x, bottomY, rightX, bottomY, outerWidth);
26914
+ if (isExternal) {
26915
+ return;
26916
+ }
26917
+ }
26918
+ drawEdge(rightX, topY, rightX, bottomY, innerWidth);
26919
+ drawEdge(x, bottomY, rightX, bottomY, innerWidth);
26920
+ }
26921
+ function getMarkerWidth(block, context) {
26922
+ if (!block.context.listMarker) {
26923
+ return 0;
26924
+ }
26925
+ const markerRun = getMarkerRun(block, context);
26926
+ return measureTextWidth(block.context.listMarker.text, markerRun, context) + pxToPt(LIST_GAP);
26927
+ }
26928
+ function getMarkerRun(block, context) {
26929
+ const firstTextRun = block.runs.find((run) => run.type === "text" || run.type === "badge") || null;
26930
+ if (!firstTextRun) {
26931
+ return {
26932
+ type: "text",
26933
+ text: "",
26934
+ size: context.options.defaultSize,
26935
+ font: context.options.defaultFont
26936
+ };
26937
+ }
26938
+ if (firstTextRun.type === "badge") {
26939
+ return {
26940
+ type: "text",
26941
+ text: firstTextRun.text,
26942
+ size: firstTextRun.size,
26943
+ font: firstTextRun.font,
26944
+ bold: firstTextRun.bold,
26945
+ italic: firstTextRun.italic,
26946
+ color: firstTextRun.color
26947
+ };
26948
+ }
26949
+ return firstTextRun;
26950
+ }
26951
+ function getEmptyLineHeight(block, context) {
26952
+ const markerRun = getMarkerRun(block, context);
26953
+ return getRunHeight(
26954
+ markerRun,
26955
+ block.context.rowMargin || context.options.defaultRowMargin
26956
+ );
26957
+ }
26958
+ function getRunHeight(run, rowMargin = DEFAULT_LINE_HEIGHT2) {
26959
+ return run.size * rowMargin;
26960
+ }
26961
+ function resolveTextMetrics(run, context) {
26962
+ let size = run.size || context.options.defaultSize;
26963
+ if ("superscript" in run && run.superscript) {
26964
+ size *= 0.65;
26965
+ }
26966
+ if ("subscript" in run && run.subscript) {
26967
+ size *= 0.65;
26968
+ }
26969
+ return {
26970
+ size,
26971
+ font: getFont(
26972
+ run.font || context.options.defaultFont,
26973
+ !!run.bold,
26974
+ !!run.italic,
26975
+ context
26976
+ )
26977
+ };
26978
+ }
26979
+ function measureTextWidth(text, run, context) {
26980
+ const resolved = resolveTextMetrics(run, context);
26981
+ const safeText = sanitizeTextForPdf(text, resolved.font);
26982
+ return resolved.font.widthOfTextAtSize(safeText, resolved.size);
26983
+ }
26984
+ function measureBadgeWidth(run, context) {
26985
+ const padding = getPadding(run.padding || [2, 4, 2, 4]).map(pxToPt);
26986
+ return measureTextWidth(run.text, run, context) + padding[1] + padding[3];
26987
+ }
26988
+ function measureBadgeHeight(run) {
26989
+ const padding = getPadding(run.padding || [2, 4, 2, 4]).map(pxToPt);
26990
+ return run.size + padding[0] + padding[2];
26991
+ }
26992
+ function getJustifyExtra(line, availableWidth) {
26993
+ const spaceCount = line.fragments.filter(
26994
+ (fragment) => fragment.kind === "space"
26995
+ ).length;
26996
+ if (!spaceCount || line.width >= availableWidth) {
26997
+ return 0;
26998
+ }
26999
+ return (availableWidth - line.width) / spaceCount;
27000
+ }
27001
+ function isLastParagraphLine(layout, line) {
27002
+ return layout.lines[layout.lines.length - 1] === line;
27003
+ }
27004
+ function getSpanningRowHeight(rows, rowHeights, rowIndex) {
27005
+ const row = rows[rowIndex];
27006
+ let maxHeight = rowHeights[rowIndex];
27007
+ for (let i = 0; i < row.cells.length; i++) {
27008
+ const cell = row.cells[i];
27009
+ maxHeight = Math.max(
27010
+ maxHeight,
27011
+ getRowSpanHeight(rowHeights, rowIndex, cell.rowspan)
27012
+ );
27013
+ }
27014
+ return maxHeight;
27015
+ }
27016
+ function getRowSpanHeight(rowHeights, rowIndex, rowSpan) {
27017
+ let height = 0;
27018
+ for (let i = rowIndex; i < rowIndex + rowSpan; i++) {
27019
+ height += rowHeights[i] || 0;
27020
+ }
27021
+ return height;
27022
+ }
27023
+ function scaleColumnWidths(widths, maxWidth) {
27024
+ const ptWidths = widths.map(pxToPt);
27025
+ const total = ptWidths.reduce((sum, width) => sum + width, 0);
27026
+ if (!total || total <= maxWidth) {
27027
+ return ptWidths;
27028
+ }
27029
+ const ratio = maxWidth / total;
27030
+ return ptWidths.map((width) => width * ratio);
27031
+ }
27032
+ function getColumnOffset(widths, colIndex) {
27033
+ let offset = 0;
27034
+ for (let i = 0; i < colIndex; i++) {
27035
+ offset += widths[i] || 0;
27036
+ }
27037
+ return offset;
27038
+ }
27039
+ function getColumnSpanWidth(widths, colIndex, span) {
27040
+ let width = 0;
27041
+ for (let i = colIndex; i < colIndex + span; i++) {
27042
+ width += widths[i] || 0;
27043
+ }
27044
+ return width;
27045
+ }
27046
+ function computeTableCellPlacement(trList, colgroup) {
27047
+ const placementMap = /* @__PURE__ */ new WeakMap();
27048
+ if (!trList.length || !colgroup.length) {
27049
+ return placementMap;
27050
+ }
27051
+ const occupiedUntilRow = Array(colgroup.length).fill(0);
27052
+ for (let rowIndex = 0; rowIndex < trList.length; rowIndex++) {
27053
+ const tr = trList[rowIndex];
27054
+ let colIndex = 0;
27055
+ for (let tdIndex = 0; tdIndex < tr.tdList.length; tdIndex++) {
27056
+ while (colIndex < colgroup.length && occupiedUntilRow[colIndex] > rowIndex) {
27057
+ colIndex += 1;
27058
+ }
27059
+ const td = tr.tdList[tdIndex];
27060
+ let width = 0;
27061
+ for (let currentCol = colIndex; currentCol < colIndex + td.colspan; currentCol++) {
27062
+ width += colgroup[currentCol]?.width || 0;
27063
+ occupiedUntilRow[currentCol] = Math.max(
27064
+ occupiedUntilRow[currentCol],
27065
+ rowIndex + td.rowspan
27066
+ );
27067
+ }
27068
+ placementMap.set(td, { colIndex, width });
27069
+ colIndex += td.colspan;
27070
+ }
27071
+ }
27072
+ return placementMap;
27073
+ }
27074
+ async function loadPdfImage(src, context) {
27075
+ if (context.imageCache.has(src)) {
27076
+ return context.imageCache.get(src);
27077
+ }
27078
+ try {
27079
+ const payload = await loadPdfImagePayload(src);
27080
+ const image = payload.type === "jpg" ? await context.pdfDoc.embedJpg(payload.data) : await context.pdfDoc.embedPng(payload.data);
27081
+ context.imageCache.set(src, image);
27082
+ return image;
27083
+ } catch {
27084
+ return null;
27085
+ }
27086
+ }
27087
+ async function loadPdfImagePayload(src) {
27088
+ const source = src.trim();
27089
+ if (source.startsWith("data:")) {
27090
+ return getPdfImagePayloadFromDataUrl(source);
27091
+ }
27092
+ const response = await fetch(source);
27093
+ if (!response.ok) {
27094
+ throw new Error(`Image request failed: ${response.status}`);
27095
+ }
27096
+ const contentType = response.headers.get("content-type") || "";
27097
+ const data2 = await response.arrayBuffer();
27098
+ return normalizePdfImagePayload(data2, contentType);
27099
+ }
27100
+ async function getPdfImagePayloadFromDataUrl(src) {
27101
+ const [, meta = "", encoded = ""] = src.match(/^data:([^,]*),(.*)$/) || [];
27102
+ const mime = meta.split(";")[0] || "";
27103
+ const isBase64 = meta.includes(";base64");
27104
+ const text = isBase64 ? atob(encoded) : decodeURIComponent(encoded);
27105
+ const bytes = new Uint8Array(text.length);
27106
+ for (let i = 0; i < text.length; i++) {
27107
+ bytes[i] = text.charCodeAt(i);
27108
+ }
27109
+ return normalizePdfImagePayload(bytes.buffer, mime);
27110
+ }
27111
+ async function normalizePdfImagePayload(data2, mime) {
27112
+ const lower = mime.toLowerCase();
27113
+ if (lower.includes("jpeg") || lower.includes("jpg")) {
27114
+ return {
27115
+ type: "jpg",
27116
+ data: data2
27117
+ };
27118
+ }
27119
+ if (lower.includes("png")) {
27120
+ return {
27121
+ type: "png",
27122
+ data: data2
27123
+ };
27124
+ }
27125
+ return {
27126
+ type: "png",
27127
+ data: await rasterizeImageToPng2(data2, mime)
27128
+ };
27129
+ }
27130
+ async function rasterizeImageToPng2(data2, mime) {
27131
+ const blob = new Blob([data2], {
27132
+ type: mime || "image/png"
27133
+ });
27134
+ const url = URL.createObjectURL(blob);
27135
+ try {
27136
+ const image = await loadHtmlImage2(url);
27137
+ const canvas = document.createElement("canvas");
27138
+ canvas.width = image.naturalWidth || DEFAULT_IMAGE_WIDTH2;
27139
+ canvas.height = image.naturalHeight || DEFAULT_IMAGE_HEIGHT2;
27140
+ const context = canvas.getContext("2d");
27141
+ if (!context) {
27142
+ throw new Error("Canvas context is unavailable");
27143
+ }
27144
+ context.drawImage(image, 0, 0, canvas.width, canvas.height);
27145
+ const pngBlob = await new Promise((resolve, reject) => {
27146
+ canvas.toBlob((output) => {
27147
+ if (output) {
27148
+ resolve(output);
27149
+ } else {
27150
+ reject(new Error("Failed to create PNG blob"));
27151
+ }
27152
+ }, "image/png");
27153
+ });
27154
+ return await pngBlob.arrayBuffer();
27155
+ } finally {
27156
+ URL.revokeObjectURL(url);
27157
+ }
27158
+ }
27159
+ function loadHtmlImage2(src) {
27160
+ return new Promise((resolve, reject) => {
27161
+ const image = new Image();
27162
+ image.onload = () => resolve(image);
27163
+ image.onerror = () => reject(new Error("Failed to load image"));
27164
+ image.src = src;
27165
+ });
27166
+ }
27167
+ function getInlineElementText2(element) {
27168
+ switch (element.type) {
27169
+ case "control" /* CONTROL */:
27170
+ return getControlText2(element.control);
27171
+ case "date" /* DATE */:
27172
+ return element.valueList?.length ? getTextFromElementList(element.valueList) : element.value;
27173
+ case "checkbox" /* CHECKBOX */:
27174
+ return element.checkbox?.value ? "\u2611" : "\u2610";
27175
+ case "radio" /* RADIO */:
27176
+ return element.radio?.value ? "\u25C9" : "\u25CB";
27177
+ case "label" /* LABEL */:
27178
+ case "latex" /* LATEX */:
27179
+ case "subscript" /* SUBSCRIPT */:
27180
+ case "superscript" /* SUPERSCRIPT */:
27181
+ return element.value;
27182
+ default:
27183
+ return element.value;
27184
+ }
27185
+ }
27186
+ function getControlText2(control) {
27187
+ if (!control) return "";
27188
+ if (control.type === "text" /* TEXT */ || control.type === "date" /* DATE */ || control.type === "number" /* NUMBER */) {
27189
+ const value = control.value?.length ? getTextFromElementList(control.value) : "";
27190
+ const content = value || control.placeholder || "";
27191
+ return `${control.preText || ""}${content}${control.postText || ""}`;
27192
+ }
27193
+ if (control.type === "select" /* SELECT */) {
27194
+ const labels = getSelectedControlLabels2(control.code, control.valueSets);
27195
+ const content = labels.length ? labels.join(control.multiSelectDelimiter || ", ") : control.placeholder || "";
27196
+ return `${control.preText || ""}${content}${control.postText || ""}`;
27197
+ }
27198
+ if (control.type === "checkbox" /* CHECKBOX */ || control.type === "radio" /* RADIO */) {
27199
+ const isRadio = control.type === "radio" /* RADIO */;
27200
+ return (control.valueSets || []).map((valueSet) => {
27201
+ const checked = control.code?.split(",").includes(valueSet.code) || false;
27202
+ return `${checked ? isRadio ? "\u25C9" : "\u2611" : isRadio ? "\u25CB" : "\u2610"} ${valueSet.value}`;
27203
+ }).join(" ");
27204
+ }
27205
+ return "";
27206
+ }
27207
+ function getSelectedControlLabels2(code, valueSets) {
27208
+ if (!code || !valueSets?.length) return [];
27209
+ return code.split(",").map(
27210
+ (selectCode) => valueSets.find((valueSet) => valueSet.code === selectCode)?.value
27211
+ ).filter((value) => !!value);
27212
+ }
27213
+ function getBlockFallbackText2(element) {
27214
+ if (element.block?.iframeBlock?.src) {
27215
+ return element.block.iframeBlock.src;
27216
+ }
27217
+ if (element.block?.videoBlock?.src) {
27218
+ return element.block.videoBlock.src;
27219
+ }
27220
+ return "";
27221
+ }
27222
+ function getListItemNumberingElement2(listItemElements, fallback) {
27223
+ return listItemElements.find(
27224
+ (listItem) => listItem.listId || listItem.listLevel !== void 0 || !!listItem.listPreset || !!listItem.listStyle || !!listItem.listType
27225
+ ) || fallback;
27226
+ }
27227
+ function getListMarker(element, orderedCounts) {
27228
+ const level = Math.max(0, Math.min(element.listLevel || 0, 8));
27229
+ if (element.listType === "ul" /* UL */) {
27230
+ return {
27231
+ text: getUnorderedMarkerText(element, level),
27232
+ level
27233
+ };
27234
+ }
27235
+ while (orderedCounts.length <= level) {
27236
+ orderedCounts.push(0);
27237
+ }
27238
+ orderedCounts[level] += 1;
27239
+ orderedCounts.length = level + 1;
27240
+ const style = element.listPreset ? getOrderedPresetStyle(element.listPreset, level) : getOrderedStyle(element.listStyle);
27241
+ const outlinePrefix = style === "outline" ? orderedCounts.slice(0, level + 1).join(".") : void 0;
27242
+ return {
27243
+ text: formatOlNumber2(orderedCounts[level] - 1, style, outlinePrefix),
27244
+ level
27245
+ };
27246
+ }
27247
+ function getOrderedPresetStyle(preset, level = 0) {
27248
+ const cycle = preset ? olPresetCycles[preset] : void 0;
27249
+ if (!cycle?.length) {
27250
+ return "decimal";
27251
+ }
27252
+ return cycle[level % cycle.length];
27253
+ }
27254
+ function getOrderedStyle(style) {
27255
+ switch (style) {
27256
+ case "lowerAlpha" /* LOWER_ALPHA */:
27257
+ return "lowerAlpha";
27258
+ case "upperAlpha" /* UPPER_ALPHA */:
27259
+ return "upperAlpha";
27260
+ case "lowerRoman" /* LOWER_ROMAN */:
27261
+ return "lowerRoman";
27262
+ case "upperRoman" /* UPPER_ROMAN */:
27263
+ return "upperRoman";
27264
+ case "decimalParen" /* DECIMAL_PAREN */:
27265
+ return "decimalParen";
27266
+ default:
27267
+ return "decimal";
27268
+ }
27269
+ }
27270
+ function getUnorderedMarkerText(element, level) {
27271
+ if (element.listPreset) {
27272
+ const cycle = ulPresetCycles[element.listPreset];
27273
+ if (cycle?.length) {
27274
+ return cycle[level % cycle.length];
27275
+ }
27276
+ }
27277
+ return bulletCharMap[element.listStyle || "disc" /* DISC */] || bulletCharMap["disc" /* DISC */];
27278
+ }
27279
+ function toAlpha2(n, upper) {
27280
+ let result = "";
27281
+ let num = n + 1;
27282
+ while (num > 0) {
27283
+ num--;
27284
+ result = String.fromCharCode((upper ? 65 : 97) + num % 26) + result;
27285
+ num = Math.floor(num / 26);
27286
+ }
27287
+ return result;
27288
+ }
27289
+ function toRoman2(n, upper) {
27290
+ const num = n + 1;
27291
+ const vals = [1e3, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1];
27292
+ const syms = [
27293
+ "M",
27294
+ "CM",
27295
+ "D",
27296
+ "CD",
27297
+ "C",
27298
+ "XC",
27299
+ "L",
27300
+ "XL",
27301
+ "X",
27302
+ "IX",
27303
+ "V",
27304
+ "IV",
27305
+ "I"
27306
+ ];
27307
+ let result = "";
27308
+ let remaining = num;
27309
+ for (let i = 0; i < vals.length; i++) {
27310
+ while (remaining >= vals[i]) {
27311
+ result += syms[i];
27312
+ remaining -= vals[i];
27313
+ }
27314
+ }
27315
+ return upper ? result : result.toLowerCase();
27316
+ }
27317
+ function formatOlNumber2(index, style, outlinePrefix) {
27318
+ switch (style) {
27319
+ case "decimal":
27320
+ return `${index + 1}.`;
27321
+ case "decimalParen":
27322
+ return `${index + 1})`;
27323
+ case "decimalZero":
27324
+ return `${String(index + 1).padStart(2, "0")}.`;
27325
+ case "lowerAlpha":
27326
+ return `${toAlpha2(index, false)}.`;
27327
+ case "lowerAlphaParen":
27328
+ return `${toAlpha2(index, false)})`;
27329
+ case "upperAlpha":
27330
+ return `${toAlpha2(index, true)}.`;
27331
+ case "lowerRoman":
27332
+ return `${toRoman2(index, false)}.`;
27333
+ case "lowerRomanParen":
27334
+ return `${toRoman2(index, false)})`;
27335
+ case "upperRoman":
27336
+ return `${toRoman2(index, true)}.`;
27337
+ case "outline":
27338
+ return outlinePrefix ? `${outlinePrefix}.` : `${index + 1}.`;
27339
+ default:
27340
+ return `${index + 1}.`;
27341
+ }
27342
+ }
27343
+ function normalizeAlignment(rowFlex) {
27344
+ if (rowFlex === "alignment" /* ALIGNMENT */) {
27345
+ return "justify" /* JUSTIFY */;
27346
+ }
27347
+ return rowFlex || "left" /* LEFT */;
27348
+ }
27349
+ function getFont(family, bold, italic, context) {
27350
+ const fontSet = context.fonts[resolveFontFamily(family)];
27351
+ if (bold && italic) {
27352
+ return fontSet.boldItalic;
27353
+ }
27354
+ if (bold) {
27355
+ return fontSet.bold;
27356
+ }
27357
+ if (italic) {
27358
+ return fontSet.italic;
27359
+ }
27360
+ return fontSet.regular;
27361
+ }
27362
+ function resolveFontFamily(font) {
27363
+ const normalized = (font || "").trim().toLowerCase();
27364
+ if (normalized.includes("sans-serif") || normalized.includes("arial") || normalized.includes("helvetica") || normalized.includes("yahei") || normalized.includes("microsoft") || normalized.includes("inter") || normalized.includes("roboto")) {
27365
+ return "sans";
27366
+ }
27367
+ if (normalized.includes("times") || normalized === "serif" || normalized.endsWith(", serif")) {
27368
+ return "serif";
27369
+ }
27370
+ if (normalized.includes("courier") || normalized.includes("mono") || normalized.includes("code")) {
27371
+ return "mono";
27372
+ }
27373
+ return "sans";
27374
+ }
27375
+ function sanitizeTextForPdf(text, font) {
27376
+ let fontCache = pdfTextCache.get(font);
27377
+ if (!fontCache) {
27378
+ fontCache = /* @__PURE__ */ new Map();
27379
+ pdfTextCache.set(font, fontCache);
27380
+ }
27381
+ if (fontCache.has(text)) {
27382
+ return fontCache.get(text);
27383
+ }
27384
+ let safeText = text;
27385
+ try {
27386
+ font.encodeText(text);
27387
+ } catch {
27388
+ safeText = Array.from(text).map((char) => sanitizePdfChar(char, font)).join("");
27389
+ }
27390
+ fontCache.set(text, safeText);
27391
+ return safeText;
27392
+ }
27393
+ function sanitizePdfChar(char, font) {
27394
+ try {
27395
+ font.encodeText(char);
27396
+ return char;
27397
+ } catch {
27398
+ const directFallback = PDF_TEXT_FALLBACKS[char];
27399
+ if (directFallback) {
27400
+ return directFallback;
27401
+ }
27402
+ if (/^\s$/u.test(char)) {
27403
+ return " ";
27404
+ }
27405
+ const normalized = char.normalize("NFKD").replace(/[\u0300-\u036f]/g, "").replace(/[^\x20-\x7E]/g, "");
27406
+ if (normalized) {
27407
+ try {
27408
+ font.encodeText(normalized);
27409
+ return normalized;
27410
+ } catch {
27411
+ return "?";
27412
+ }
27413
+ }
27414
+ return "?";
27415
+ }
27416
+ }
27417
+ function getPadding(padding) {
27418
+ return [padding[0] ?? 0, padding[1] ?? 0, padding[2] ?? 0, padding[3] ?? 0];
27419
+ }
27420
+ function getTitleSize(titleLevel, options) {
27421
+ if (!titleLevel) {
27422
+ return void 0;
27423
+ }
27424
+ return options.title[titleSizeMapping[titleLevel]];
27425
+ }
27426
+ function getPageNumberHeight(pageNumber) {
27427
+ if (pageNumber.disabled) {
27428
+ return 0;
27429
+ }
27430
+ return pageNumber.size || 12;
27431
+ }
27432
+ function getFooterBarHeight(footerHeight, context) {
27433
+ if (context.options.footer.disabled) {
27434
+ return 0;
27435
+ }
27436
+ return Math.max(footerHeight, pxToPt(FOOTER_MIN_BAR_HEIGHT));
27437
+ }
27438
+ function getReservedPageNumberBottom(pageNumber, pageNumberHeight) {
27439
+ if (pageNumber.disabled) {
27440
+ return 0;
27441
+ }
27442
+ return pxToPt(pageNumber.bottom + 4) + pageNumberHeight;
27443
+ }
27444
+ function normalizeText2(text = "") {
27445
+ return text.replace(new RegExp(ZERO, "g"), "").replace(/\r\n/g, "\n");
27446
+ }
27447
+ function normalizePdfFileName(fileName) {
27448
+ const trimmed = fileName?.trim();
27449
+ if (!trimmed) {
27450
+ return DEFAULT_PDF_FILE_NAME;
27451
+ }
27452
+ return trimmed.toLowerCase().endsWith(".pdf") ? trimmed : `${trimmed}.pdf`;
27453
+ }
27454
+ function pxToPt(px) {
27455
+ return px * (72 / 96);
27456
+ }
27457
+ function toPdfY(pageHeight, top, height = 0) {
27458
+ return pageHeight - top - height;
27459
+ }
27460
+ function toPdfColor(color, fallback = "#000000") {
27461
+ const hex = normalizeHexColor2(color || fallback, "000000") || "000000";
27462
+ const red = parseInt(hex.slice(0, 2), 16) / 255;
27463
+ const green = parseInt(hex.slice(2, 4), 16) / 255;
27464
+ const blue = parseInt(hex.slice(4, 6), 16) / 255;
27465
+ return (0, import_pdf_lib.rgb)(red, green, blue);
27466
+ }
27467
+ function normalizeHexColor2(color, fallback) {
27468
+ const normalized = normalizeHexLiteral2(color) || normalizeRgbColor2(color) || normalizeBrowserColor2(color);
27469
+ if (normalized) {
27470
+ return normalized;
27471
+ }
27472
+ return fallback ? normalizeHexLiteral2(fallback) || void 0 : void 0;
27473
+ }
27474
+ function normalizeHexLiteral2(color) {
27475
+ const value = color.trim().replace(/^#/, "");
27476
+ if (/^[\da-f]{3}$/i.test(value)) {
27477
+ return value.split("").map((part) => `${part}${part}`).join("").toUpperCase();
27478
+ }
27479
+ if (/^[\da-f]{4}$/i.test(value)) {
27480
+ return value.slice(0, 3).split("").map((part) => `${part}${part}`).join("").toUpperCase();
27481
+ }
27482
+ if (/^[\da-f]{6}$/i.test(value)) {
27483
+ return value.toUpperCase();
27484
+ }
27485
+ if (/^[\da-f]{8}$/i.test(value)) {
27486
+ return value.slice(0, 6).toUpperCase();
27487
+ }
27488
+ return void 0;
27489
+ }
27490
+ function normalizeRgbColor2(color) {
27491
+ const match = color.trim().match(/^rgba?\((.+)\)$/i);
27492
+ if (!match) {
27493
+ return void 0;
27494
+ }
27495
+ const parts = match[1].replace(/\s*\/\s*/g, ",").split(/\s*,\s*|\s+/).filter(Boolean);
27496
+ if (parts.length < 3) {
27497
+ return void 0;
27498
+ }
27499
+ const red = parseRgbChannel2(parts[0]);
27500
+ const green = parseRgbChannel2(parts[1]);
27501
+ const blue = parseRgbChannel2(parts[2]);
27502
+ if (red === null || green === null || blue === null) {
27503
+ return void 0;
27504
+ }
27505
+ const alpha = parts[3] !== void 0 ? parseAlphaChannel2(parts[3]) : 1;
27506
+ if (alpha === null || alpha <= 0) {
27507
+ return void 0;
27508
+ }
27509
+ const flattened = alpha >= 1 ? [red, green, blue] : [
27510
+ flattenChannel2(red, alpha),
27511
+ flattenChannel2(green, alpha),
27512
+ flattenChannel2(blue, alpha)
27513
+ ];
27514
+ return flattened.map(toHexChannel2).join("");
27515
+ }
27516
+ function normalizeBrowserColor2(color) {
27517
+ if (typeof document === "undefined") {
27518
+ return void 0;
27519
+ }
27520
+ const canvas = document.createElement("canvas");
27521
+ const context = canvas.getContext("2d");
27522
+ if (!context) {
27523
+ return void 0;
27524
+ }
27525
+ context.fillStyle = "#000000";
27526
+ context.fillStyle = color;
27527
+ const normalized = context.fillStyle;
27528
+ if (typeof normalized !== "string") {
27529
+ return void 0;
27530
+ }
27531
+ return normalizeHexLiteral2(normalized) || normalizeRgbColor2(normalized);
27532
+ }
27533
+ function parseRgbChannel2(value) {
27534
+ if (value.endsWith("%")) {
27535
+ const percent = Number(value.slice(0, -1));
27536
+ if (!Number.isFinite(percent)) {
27537
+ return null;
27538
+ }
27539
+ return clampColorChannel2(Math.round(percent / 100 * 255));
27540
+ }
27541
+ const channel = Number(value);
27542
+ if (!Number.isFinite(channel)) {
27543
+ return null;
27544
+ }
27545
+ return clampColorChannel2(Math.round(channel));
27546
+ }
27547
+ function parseAlphaChannel2(value) {
27548
+ if (value.endsWith("%")) {
27549
+ const percent = Number(value.slice(0, -1));
27550
+ if (!Number.isFinite(percent)) {
27551
+ return null;
27552
+ }
27553
+ return Math.min(Math.max(percent / 100, 0), 1);
27554
+ }
27555
+ const alpha = Number(value);
27556
+ if (!Number.isFinite(alpha)) {
27557
+ return null;
27558
+ }
27559
+ return Math.min(Math.max(alpha, 0), 1);
27560
+ }
27561
+ function clampColorChannel2(value) {
27562
+ return Math.min(Math.max(value, 0), 255);
27563
+ }
27564
+ function flattenChannel2(value, alpha) {
27565
+ return clampColorChannel2(Math.round(255 * (1 - alpha) + value * alpha));
27566
+ }
27567
+ function toHexChannel2(value) {
27568
+ return value.toString(16).padStart(2, "0").toUpperCase();
27569
+ }
27570
+
27571
+ // src/utils/print.ts
27572
+ function convertPxToPaperSize(width, height) {
27573
+ if (width === 1125 && height === 1593) {
27574
+ return {
27575
+ size: "a3",
27576
+ width: "297mm",
27577
+ height: "420mm"
27578
+ };
27579
+ }
27580
+ if (width === 794 && height === 1123) {
27581
+ return {
27582
+ size: "a4",
27583
+ width: "210mm",
27584
+ height: "297mm"
27585
+ };
27586
+ }
27587
+ if (width === 565 && height === 796) {
27588
+ return {
27589
+ size: "a5",
27590
+ width: "148mm",
27591
+ height: "210mm"
27592
+ };
27593
+ }
27594
+ return {
27595
+ size: "",
27596
+ width: `${width}px`,
27597
+ height: `${height}px`
27598
+ };
27599
+ }
27600
+ function printImageBase64(base64List, options) {
27601
+ const { width, height, direction = "vertical" /* VERTICAL */ } = options;
27602
+ const iframe = document.createElement("iframe");
27603
+ iframe.style.visibility = "hidden";
27604
+ iframe.style.position = "absolute";
27605
+ iframe.style.left = "0";
27606
+ iframe.style.top = "0";
27607
+ iframe.style.width = "0";
27608
+ iframe.style.height = "0";
27609
+ iframe.style.border = "none";
27610
+ document.body.append(iframe);
27611
+ const contentWindow = iframe.contentWindow;
27612
+ const doc = contentWindow.document;
27613
+ doc.open();
27614
+ const container = document.createElement("div");
27615
+ const paperSize = convertPxToPaperSize(width, height);
27616
+ base64List.forEach((base64) => {
27617
+ const image = document.createElement("img");
27618
+ image.style.width = direction === "horizontal" /* HORIZONTAL */ ? paperSize.height : paperSize.width;
27619
+ image.style.height = direction === "horizontal" /* HORIZONTAL */ ? paperSize.width : paperSize.height;
27620
+ image.src = base64;
27621
+ container.append(image);
27622
+ });
27623
+ const style = document.createElement("style");
27624
+ const stylesheet = `
27625
+ * {
27626
+ margin: 0;
27627
+ padding: 0;
27628
+ }
27629
+ @page {
27630
+ margin: 0;
27631
+ size: ${paperSize.size} ${direction === "horizontal" /* HORIZONTAL */ ? `landscape` : `portrait`};
27632
+ }`;
27633
+ style.append(document.createTextNode(stylesheet));
27634
+ setTimeout(() => {
27635
+ doc.write(`${style.outerHTML}${container.innerHTML}`);
27636
+ contentWindow.print();
27637
+ doc.close();
27638
+ window.addEventListener(
27639
+ "mouseover",
27640
+ () => {
27641
+ iframe?.remove();
27642
+ },
27643
+ {
27644
+ once: true
27645
+ }
27646
+ );
27647
+ });
27648
+ }
27649
+
27650
+ // src/core/command/CommandAdapt.ts
27651
+ var CommandAdapt = class {
27652
+ constructor(draw) {
27653
+ this.draw = draw;
27654
+ this.range = draw.getRange();
27655
+ this.position = draw.getPosition();
27656
+ this.historyManager = draw.getHistoryManager();
27657
+ this.canvasEvent = draw.getCanvasEvent();
27658
+ this.options = draw.getOptions();
27659
+ this.control = draw.getControl();
27660
+ this.workerManager = draw.getWorkerManager();
27661
+ this.searchManager = draw.getSearch();
27662
+ this.i18n = draw.getI18n();
27663
+ this.zone = draw.getZone();
27664
+ this.tableOperate = draw.getTableOperate();
27665
+ }
27666
+ getStyleSelectionElementList(options = {}) {
27667
+ const selection = this.range.getSelectionElementList();
27668
+ if (!selection?.length) return null;
27669
+ const { textLikeOnly = false } = options;
27670
+ const result = [];
27671
+ const collect = (elementList) => {
27672
+ for (let i = 0; i < elementList.length; i++) {
27673
+ const element = elementList[i];
27674
+ if (element.type === "table" /* TABLE */ && element.trList?.length) {
27675
+ for (let t = 0; t < element.trList.length; t++) {
27676
+ const tr = element.trList[t];
27677
+ for (let d = 0; d < tr.tdList.length; d++) {
27678
+ collect(tr.tdList[d].value);
27679
+ }
27680
+ }
27681
+ continue;
27682
+ }
27683
+ result.push(element);
27684
+ }
27685
+ };
27686
+ collect(selection);
27687
+ if (!textLikeOnly) {
27688
+ return result;
27689
+ }
27690
+ return result.filter(
27691
+ (element) => isTextLikeElement(element) || element.type === "label" /* LABEL */
27692
+ );
27693
+ }
27694
+ mode(payload) {
27695
+ this.draw.setMode(payload);
27696
+ }
27697
+ async cut() {
27698
+ const isDisabled = this.draw.isReadonly() || this.draw.isDisabled();
27699
+ if (isDisabled) return;
27700
+ await this.canvasEvent.cut();
27701
+ }
27702
+ async copy(payload) {
27703
+ await this.canvasEvent.copy(payload);
27704
+ }
27705
+ paste(payload) {
27706
+ const isDisabled = this.draw.isReadonly() || this.draw.isDisabled();
27707
+ if (isDisabled) return;
27708
+ pasteByApi(this.canvasEvent, payload);
27709
+ }
27710
+ selectAll() {
27711
+ this.canvasEvent.selectAll();
27712
+ }
27713
+ backspace() {
27714
+ const isDisabled = this.draw.isReadonly() || this.draw.isDisabled();
27715
+ if (isDisabled) return;
27716
+ const elementList = this.draw.getElementList();
27717
+ const { startIndex, endIndex } = this.range.getRange();
27718
+ const isCollapsed = startIndex === endIndex;
27719
+ if (isCollapsed && elementList[startIndex].value === ZERO && startIndex === 0) {
27720
+ return;
27721
+ }
27722
+ if (!isCollapsed) {
27723
+ this.draw.spliceElementList(
27724
+ elementList,
27725
+ startIndex + 1,
27726
+ endIndex - startIndex
27727
+ );
27728
+ } else {
27729
+ this.draw.spliceElementList(elementList, startIndex, 1);
27730
+ }
27731
+ const curIndex = isCollapsed ? startIndex - 1 : startIndex;
27732
+ this.range.setRange(curIndex, curIndex);
27733
+ this.draw.render({ curIndex });
27734
+ }
27735
+ setRange(startIndex, endIndex, tableId, startTdIndex, endTdIndex, startTrIndex, endTrIndex) {
27736
+ if (startIndex < 0 || endIndex < 0 || endIndex < startIndex) return;
24586
27737
  this.range.setRange(
24587
27738
  startIndex,
24588
27739
  endIndex,
@@ -25629,6 +28780,16 @@ var CommandAdapt = class {
25629
28780
  this.draw.setPageScale(scale);
25630
28781
  }
25631
28782
  }
28783
+ async exportDocx(payload = {}) {
28784
+ const result = this.draw.getValue();
28785
+ const { blob, fileName } = await exportEditorDataToDocx(result, payload);
28786
+ downloadBlob(blob, fileName);
28787
+ }
28788
+ async exportPdf(payload = {}) {
28789
+ const result = this.draw.getValue();
28790
+ const { blob, fileName } = await exportEditorDataToPdf(result, payload);
28791
+ downloadBlob(blob, fileName);
28792
+ }
25632
28793
  replaceImageElement(payload) {
25633
28794
  const { startIndex } = this.range.getRange();
25634
28795
  const elementList = this.draw.getElementList();