@evotecit/officeimo 0.1.21 → 0.1.43

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.
Files changed (92) hide show
  1. package/README.md +39 -8
  2. package/bundles/officeimo-canopyx-adapter.js +56 -36
  3. package/bundles/officeimo-canopyx-adapter.min.js +1 -1
  4. package/bundles/officeimo-canopyx-adapter.min.mjs +1 -1
  5. package/bundles/officeimo-canopyx-adapter.mjs +42 -22
  6. package/bundles/officeimo-canopyx.js +420 -177
  7. package/bundles/officeimo-canopyx.min.js +1 -1
  8. package/bundles/officeimo-canopyx.min.mjs +1 -1
  9. package/bundles/officeimo-canopyx.mjs +346 -103
  10. package/bundles/officeimo-chartforgex-adapter.js +1924 -0
  11. package/bundles/officeimo-chartforgex-adapter.min.js +2 -0
  12. package/bundles/officeimo-chartforgex-adapter.min.mjs +2 -0
  13. package/bundles/officeimo-chartforgex-adapter.mjs +1910 -0
  14. package/bundles/officeimo-chartforgex.js +13594 -0
  15. package/bundles/officeimo-chartforgex.min.js +2 -0
  16. package/bundles/officeimo-chartforgex.min.mjs +2 -0
  17. package/bundles/officeimo-chartforgex.mjs +13487 -0
  18. package/bundles/officeimo-csv.js +12 -7
  19. package/bundles/officeimo-csv.min.js +1 -1
  20. package/bundles/officeimo-csv.min.mjs +1 -1
  21. package/bundles/officeimo-csv.mjs +8 -3
  22. package/bundles/officeimo-datatables-adapter.js +11 -11
  23. package/bundles/officeimo-datatables-adapter.min.js +1 -1
  24. package/bundles/officeimo-datatables-adapter.min.mjs +1 -1
  25. package/bundles/officeimo-datatables-adapter.mjs +7 -7
  26. package/bundles/officeimo-datatables.js +375 -152
  27. package/bundles/officeimo-datatables.min.js +1 -1
  28. package/bundles/officeimo-datatables.min.mjs +1 -1
  29. package/bundles/officeimo-datatables.mjs +311 -88
  30. package/bundles/officeimo-execution.js +14 -9
  31. package/bundles/officeimo-execution.min.js +1 -1
  32. package/bundles/officeimo-execution.min.mjs +1 -1
  33. package/bundles/officeimo-execution.mjs +8 -3
  34. package/bundles/officeimo-pdf.js +286 -120
  35. package/bundles/officeimo-pdf.min.js +1 -1
  36. package/bundles/officeimo-pdf.min.mjs +1 -1
  37. package/bundles/officeimo-pdf.mjs +244 -78
  38. package/bundles/officeimo-xlsx.js +93 -31
  39. package/bundles/officeimo-xlsx.min.js +1 -1
  40. package/bundles/officeimo-xlsx.min.mjs +1 -1
  41. package/bundles/officeimo-xlsx.mjs +75 -13
  42. package/bundles/officeimo.js +373 -150
  43. package/bundles/officeimo.min.js +1 -1
  44. package/bundles/officeimo.min.mjs +1 -1
  45. package/bundles/officeimo.mjs +312 -89
  46. package/dist/core/progress.js +7 -2
  47. package/dist/index.d.ts +1 -1
  48. package/dist/integrations/canopyx/index.js +9 -2
  49. package/dist/integrations/canopyx/source.js +26 -13
  50. package/dist/integrations/chartforgex/capture.d.ts +31 -0
  51. package/dist/integrations/chartforgex/capture.js +103 -0
  52. package/dist/integrations/chartforgex/index.d.ts +13 -0
  53. package/dist/integrations/chartforgex/index.js +88 -0
  54. package/dist/integrations/chartforgex/svg-drawing.d.ts +5 -0
  55. package/dist/integrations/chartforgex/svg-drawing.js +775 -0
  56. package/dist/integrations/chartforgex/svg-geometry.d.ts +23 -0
  57. package/dist/integrations/chartforgex/svg-geometry.js +304 -0
  58. package/dist/integrations/chartforgex/svg-image.d.ts +9 -0
  59. package/dist/integrations/chartforgex/svg-image.js +46 -0
  60. package/dist/integrations/chartforgex/svg-markup.d.ts +10 -0
  61. package/dist/integrations/chartforgex/svg-markup.js +124 -0
  62. package/dist/integrations/chartforgex/svg-paint.d.ts +16 -0
  63. package/dist/integrations/chartforgex/svg-paint.js +146 -0
  64. package/dist/integrations/chartforgex/types.d.ts +77 -0
  65. package/dist/integrations/chartforgex/types.js +1 -0
  66. package/dist/integrations/chartforgex/winansi.d.ts +4 -0
  67. package/dist/integrations/chartforgex/winansi.js +48 -0
  68. package/dist/integrations/chartforgex/workbook.d.ts +12 -0
  69. package/dist/integrations/chartforgex/workbook.js +137 -0
  70. package/dist/pdf/document-drawings.d.ts +1 -1
  71. package/dist/pdf/document-drawings.js +91 -17
  72. package/dist/pdf/document-images.d.ts +7 -1
  73. package/dist/pdf/document-images.js +59 -24
  74. package/dist/pdf/document-types.d.ts +3 -1
  75. package/dist/pdf/document.d.ts +2 -2
  76. package/dist/pdf/document.js +3 -1
  77. package/dist/pdf/drawing-types.d.ts +37 -10
  78. package/dist/pdf/font-resources.d.ts +1 -1
  79. package/dist/pdf/font-resources.js +6 -3
  80. package/dist/pdf/index.d.ts +1 -1
  81. package/dist/pdf/pages.js +15 -0
  82. package/dist/pdf/png.d.ts +11 -2
  83. package/dist/pdf/png.js +50 -23
  84. package/dist/pdf/session.js +3 -2
  85. package/dist/pdf/settings.d.ts +2 -2
  86. package/dist/pdf/settings.js +7 -3
  87. package/dist/xlsx/options.js +1 -1
  88. package/dist/xlsx/types.d.ts +8 -0
  89. package/dist/xlsx/workbook.js +6 -0
  90. package/dist/xlsx/worksheet.d.ts +13 -1
  91. package/dist/xlsx/worksheet.js +60 -9
  92. package/package.json +9 -2
@@ -1783,15 +1783,20 @@ return _exports;
1783
1783
  const _m23 = (() => {
1784
1784
  /** @internal Notify synchronously; observe an accidental promise before rejecting its unsupported use. */
1785
1785
  function notifyProgress(callback, progress) {
1786
+ notifySynchronously("onProgress", callback, progress);
1787
+ }
1788
+ /** @internal Run a host notification that must finish before the export continues. A returned promise is observed,
1789
+ * so its rejection is never unhandled, and the export fails instead of reporting success before the callback ends. */
1790
+ function notifySynchronously(name, callback, value) {
1786
1791
  if (!callback)
1787
1792
  return;
1788
- const result = callback(progress);
1793
+ const result = callback(value);
1789
1794
  if (result && typeof result.then === "function") {
1790
1795
  void Promise.resolve(result).catch(() => { });
1791
- throw new TypeError("onProgress must be synchronous.");
1796
+ throw new TypeError(name + " must be synchronous.");
1792
1797
  }
1793
1798
  }
1794
- const _exports = Object.freeze({ notifyProgress: notifyProgress });
1799
+ const _exports = Object.freeze({ notifyProgress: notifyProgress, notifySynchronously: notifySynchronously });
1795
1800
  return _exports;
1796
1801
  })();
1797
1802
 
@@ -3349,7 +3354,7 @@ const { ChunkedTextSink, BlobByteSink } = _m3;
3349
3354
 
3350
3355
  const { OfficeIMOError } = _m2;
3351
3356
 
3352
- const { notifyProgress } = _m23;
3357
+ const { notifyProgress, notifySynchronously } = _m23;
3353
3358
 
3354
3359
  const { copyColumns, createRowProjector } = _m11;
3355
3360
 
@@ -3421,8 +3426,14 @@ class Worksheet {
3421
3426
  pendingCharacters = 0;
3422
3427
  reservedLayout = false;
3423
3428
  internalLinks = [];
3429
+ // Evicted entries become holes and are compacted in one pass when the links are read, keeping eviction O(1).
3424
3430
  links = [];
3431
+ evictedLinks = 0;
3425
3432
  linkedCells = new Set();
3433
+ /** Indexes in `links` of data-cell links that `hyperlinkOverflow: "drop"` may give up, in row order. */
3434
+ droppable = [];
3435
+ droppableLinks = new WeakSet();
3436
+ droppedLinks = 0;
3426
3437
  pictures = [];
3427
3438
  nativeCharts = [];
3428
3439
  conditional;
@@ -3634,7 +3645,8 @@ class Worksheet {
3634
3645
  const cell = col.letter + row;
3635
3646
  if (link || this.linkedCells.has(cell))
3636
3647
  throw new TypeError("A text-preservation cell cannot also have an external hyperlink.");
3637
- checkHyperlinkCount(this.links.length + this.internalLinks.length + 1);
3648
+ this.makeLinkRoom();
3649
+ checkHyperlinkCount(this.linkCount + 1);
3638
3650
  this.book.checkLinks(1);
3639
3651
  // Replace a generated cell's original reservation with its preview and overflow records.
3640
3652
  if (reservedCharacters !== undefined) {
@@ -3648,7 +3660,7 @@ class Worksheet {
3648
3660
  value = preserved.preview;
3649
3661
  }
3650
3662
  if (link)
3651
- this.appendHyperlink({ cell: col.letter + row, ...link });
3663
+ this.appendHyperlink({ cell: col.letter + row, ...link }, !header && !footer && !title && this.book.settings.hyperlinkOverflow === "drop");
3652
3664
  if (type === "date")
3653
3665
  value = excelDate(value, this.book.settings.dateMode);
3654
3666
  if (!header && !footer && visible && (!formula || !isSubtotalFormula(formula)))
@@ -3957,20 +3969,61 @@ class Worksheet {
3957
3969
  throw this.error;
3958
3970
  this.appendHyperlink(link);
3959
3971
  }
3960
- appendHyperlink(link) {
3972
+ appendHyperlink(link, droppable = false) {
3973
+ // Validate before any overflow decision, so a dropped link can never hide an unsafe target.
3961
3974
  const copied = copyHyperlink(link, this.book.settings.invalidCharacterPolicy);
3962
3975
  const position = cellPosition(copied.cell);
3963
3976
  if (this.layout.regions.covered(position.column, position.row))
3964
3977
  throw new TypeError("Hyperlinks cannot address a covered merged cell.");
3965
3978
  if (this.linkedCells.has(copied.cell))
3966
3979
  throw new TypeError("Duplicate hyperlink cell: " + copied.cell);
3967
- checkHyperlinkCount(this.links.length + this.internalLinks.length + 1);
3980
+ if (droppable && this.linkCount >= maximumHyperlinks) {
3981
+ this.droppedLinks++;
3982
+ return;
3983
+ }
3984
+ if (!droppable)
3985
+ this.makeLinkRoom();
3986
+ checkHyperlinkCount(this.linkCount + 1);
3968
3987
  this.book.retainLink();
3988
+ if (droppable) {
3989
+ this.droppable.push(this.links.length);
3990
+ this.droppableLinks.add(copied);
3991
+ }
3969
3992
  this.links.push(copied);
3970
3993
  this.linkedCells.add(copied.cell);
3971
3994
  }
3995
+ /** Links the worksheet holds now, not counting evicted holes. */
3996
+ get linkCount() { return this.links.length - this.evictedLinks + this.internalLinks.length; }
3997
+ /** A full worksheet gives up its latest data-cell link for a link that cannot be dropped. Hyperlinks are serialized after
3998
+ * the rows, so the cell keeps its written value. The entry becomes a hole, so other indexes stay valid until compaction. */
3999
+ makeLinkRoom() {
4000
+ if (this.linkCount < maximumHyperlinks || !this.droppable.length)
4001
+ return;
4002
+ const index = this.droppable.pop(), removed = this.links[index];
4003
+ this.links[index] = undefined;
4004
+ this.evictedLinks++;
4005
+ this.linkedCells.delete(removed.cell);
4006
+ this.book.releaseLink();
4007
+ this.droppedLinks++;
4008
+ }
4009
+ /** One ordered pass removes evicted holes and rebuilds the droppable indexes. */
4010
+ compactLinks() {
4011
+ if (this.evictedLinks) {
4012
+ const kept = [], droppable = [];
4013
+ for (const link of this.links)
4014
+ if (link) {
4015
+ if (this.droppableLinks.has(link))
4016
+ droppable.push(kept.length);
4017
+ kept.push(link);
4018
+ }
4019
+ this.links = kept;
4020
+ this.droppable = droppable;
4021
+ this.evictedLinks = 0;
4022
+ }
4023
+ return this.links;
4024
+ }
3972
4025
  /** @internal */
3973
- get hyperlinks() { return this.links; }
4026
+ get hyperlinks() { return this.compactLinks(); }
3974
4027
  /** @internal */
3975
4028
  get images() { return this.pictures; }
3976
4029
  /** @internal An empty export has no data table; it still emits the declared headers. */
@@ -4021,7 +4074,7 @@ class Worksheet {
4021
4074
  for (const binding of this.chartSources)
4022
4075
  binding.finish();
4023
4076
  this.chartSources.length = 0;
4024
- for (const link of this.links) {
4077
+ for (const link of this.compactLinks()) {
4025
4078
  const position = cellPosition(link.cell);
4026
4079
  if (position.column > this.columns.length || position.row > this.totalRows)
4027
4080
  throw new RangeError("Hyperlinks must address cells within the exported rows and columns.");
@@ -4051,8 +4104,11 @@ class Worksheet {
4051
4104
  await this.buffer.write(xml);
4052
4105
  for (const xml of dataValidationsXml(this.validations, this.headerRows, this.count, detailRanges))
4053
4106
  await this.buffer.write(xml);
4054
- if (this.links.length || this.internalLinks.length)
4055
- await this.buffer.write(hyperlinksXml(this.links, this.book.settings.invalidCharacterPolicy, this.internalLinks));
4107
+ if (this.droppedLinks)
4108
+ notifySynchronously("onHyperlinkOverflow", this.book.settings.onHyperlinkOverflow, Object.freeze({ sheetName: this.name, dropped: this.droppedLinks }));
4109
+ const links = this.compactLinks();
4110
+ if (links.length || this.internalLinks.length)
4111
+ await this.buffer.write(hyperlinksXml(links, this.book.settings.invalidCharacterPolicy, this.internalLinks));
4056
4112
  await this.buffer.write(printXml(this.options.print, this.book.settings.invalidCharacterPolicy));
4057
4113
  if (this.pictures.length || this.nativeCharts.length)
4058
4114
  await this.buffer.write('<drawing r:id="drawing"/>');
@@ -4197,7 +4253,7 @@ const _m43 = (() => {
4197
4253
  const { captureFields } = _m10;
4198
4254
 
4199
4255
  /** @internal The workbook owner captures these settings before validation or adapter merging. */
4200
- const workbookOptionFields = ["signal", "onProgress", "limits", "sink", "dateMode", "compression", "invalidCharacterPolicy", "appProperties", "cellValueWriters", "oversizedText", "creator", "title", "subject", "description", "created", "modified"];
4256
+ const workbookOptionFields = ["signal", "onProgress", "limits", "sink", "dateMode", "compression", "invalidCharacterPolicy", "appProperties", "cellValueWriters", "oversizedText", "hyperlinkOverflow", "onHyperlinkOverflow", "creator", "title", "subject", "description", "created", "modified"];
4201
4257
  /** @internal Worksheet settings also used by the portable sheet owner. */
4202
4258
  const sheetOptionFields = ["columns", "includeHeader", "headerRows", "freezeHeader", "autoFilter", "boldHeader", "headerFill", "headerBorder", "headerWrap", "headerStyle", "alternatingRowStyle", "rowStyle", "cellStyle", "rowOutline", "maxOutlineLevel", "outlineSummaryBelow", "outlineSummaryRight", "columnOutlines", "rowHeight", "headerHeight", "defaultColumnWidth", "freezeColumns", "table", "autoSize", "footer", "print", "title", "mergedCells", "hyperlinks", "conditionalFormats", "dataValidation"];
4203
4259
  /** @internal Includes inherited format-specific ceilings before a wrapper combines stream settings. */
@@ -4649,6 +4705,10 @@ class Workbook {
4649
4705
  throw new RangeError("compression must be auto or store.");
4650
4706
  if (options.oversizedText !== undefined && !["reject", "preserve"].includes(options.oversizedText))
4651
4707
  throw new RangeError("oversizedText must be reject or preserve.");
4708
+ if (options.hyperlinkOverflow !== undefined && !["reject", "drop"].includes(options.hyperlinkOverflow))
4709
+ throw new RangeError("hyperlinkOverflow must be reject or drop.");
4710
+ if (options.onHyperlinkOverflow !== undefined && typeof options.onHyperlinkOverflow !== "function")
4711
+ throw new TypeError("onHyperlinkOverflow must be a function.");
4652
4712
  cleanXml("", policy);
4653
4713
  corePropertiesXml(options, policy);
4654
4714
  this.budget = new ExportBudget(options.limits);
@@ -4726,6 +4786,8 @@ class Workbook {
4726
4786
  }
4727
4787
  /** @internal Reserve a preflighted worksheet batch or one row hyperlink. */
4728
4788
  retainLink(count = 1) { this.checkLinks(count); this.links += count; }
4789
+ /** @internal A worksheet dropped a data-cell link it had retained. */
4790
+ releaseLink() { this.links--; }
4729
4791
  /** @internal */
4730
4792
  checkImage(bytes) {
4731
4793
  if (this.settings.limits?.maxImageBytes !== undefined && this.imageBytes + bytes > this.settings.limits.maxImageBytes)
@@ -5726,12 +5788,16 @@ const sizes = {
5726
5788
  };
5727
5789
  /** @internal Shared capture schema for thin format adapters and the grouped writer. */
5728
5790
  const pdfOptionFields = ["columns", "signal", "onProgress", "limits", "textShaper", "textDirection", "pageSize", "orientation", "margins", "fonts", "tagged", "fontSize",
5729
- "title", "messageTop", "messageBottom", "includeHeader", "headerRows", "footer", "headerPresentation", "footerPresentation", "alternateRowColor", "padding",
5791
+ "title", "metadataTitle", "messageTop", "messageBottom", "includeHeader", "headerRows", "footer", "headerPresentation", "footerPresentation", "alternateRowColor", "padding",
5730
5792
  "columnWidths", "wideTable", "pageHeader", "pageFooter", "pageNumbers", "pageNumberLabels", "booleanText", "formatValue", "formatRuns", "compression", "paragraphStyles"];
5731
5793
  /** @internal Complete PDF limit schema used when a host combines format and shared limits. */
5732
5794
  const pdfLimitFields = ["maxRows", "maxCells", "maxTextCharacters", "maxOutputBytes", "maxPages", "maxColumns", "maxTableBands", "maxTableWindowRows", "maxCellCharacters", "maxTextRuns", "maxGroupBlocks", "maxRowLines",
5733
5795
  "maxFontBytes", "maxPageBytes", "maxHyperlinks", "maxImageBytes", "maxImagePixels", "maxImageWorkingBytes", "maxVectorCommands", "maxDrawingElements", "maxStructureElements",
5734
5796
  "maxMarkedContentReferences", "maxSections", "maxBookmarks", "maxListItems", "maxParagraphStyles"];
5797
+ /** @internal Default ceilings shared by the drawing writer and its producers. */
5798
+ const pdfDrawingLimits = Object.freeze({ maxVectorCommands: 100000, maxDrawingElements: 100000 });
5799
+ /** @internal Maximum number of retained drawing levels including the leaf. */
5800
+ const pdfDrawingMaxDepth = 32;
5735
5801
  /** @internal Capture supported structural properties once, including class-based options with prototype accessors. */
5736
5802
  function capturePdfOptions(input) {
5737
5803
  if (!input || typeof input !== "object" || Array.isArray(input))
@@ -5842,7 +5908,7 @@ function settings(input, document = false) {
5842
5908
  footerPresentation: Object.freeze({ background: "eef2f6", bold: true, ...presentation(configuration.footerPresentation) }) };
5843
5909
  const budget = new ExportBudget(options.limits);
5844
5910
  const limits = { maxPages: 10000, maxColumns: 1024, maxTableBands: 64, maxTableWindowRows: 256, maxCellCharacters: 1000000, maxTextRuns: 10000, maxGroupBlocks: 256, maxRowLines: 100000, maxFontBytes: 16 * 1024 * 1024, maxPageBytes: 8 * 1024 * 1024, maxHyperlinks: 100000,
5845
- maxImageBytes: 32 * 1024 * 1024, maxImagePixels: 16 * 1024 * 1024, maxVectorCommands: 100000, maxDrawingElements: 100000,
5911
+ maxImageBytes: 32 * 1024 * 1024, maxImagePixels: 16 * 1024 * 1024, ...pdfDrawingLimits,
5846
5912
  maxStructureElements: 1000000, maxMarkedContentReferences: 2000000,
5847
5913
  maxListItems: 100000, maxParagraphStyles: 256, maxSections: 1000, maxBookmarks: 10000 };
5848
5914
  for (const key of Object.keys(limits)) {
@@ -5870,7 +5936,7 @@ function settings(input, document = false) {
5870
5936
  const fontSize = positive(options.fontSize ?? 9, "Font size", 144), padding = options.padding ?? 4;
5871
5937
  if (!Number.isFinite(padding) || padding < 0 || padding > 72)
5872
5938
  throw new RangeError("PDF padding must be from 0 through 72 points.");
5873
- for (const key of ["title", "messageTop", "messageBottom"])
5939
+ for (const key of ["title", "metadataTitle", "messageTop", "messageBottom"])
5874
5940
  if (options[key] !== undefined && typeof options[key] !== "string")
5875
5941
  throw new TypeError(key + " must be text.");
5876
5942
  for (const key of ["pageHeader", "pageFooter"])
@@ -5906,7 +5972,7 @@ function settings(input, document = false) {
5906
5972
  repeatedColumns: document ? Object.freeze([]) : repeatedColumns(options.wideTable, columns),
5907
5973
  limits: { ...limits, ...(maxImageWorkingBytes === undefined ? {} : { maxImageWorkingBytes }) }, budget };
5908
5974
  }
5909
- const _exports = Object.freeze({ positive: _m58.positive, color: _m58.color, presentation: _m58.presentation, pdfOptionFields: pdfOptionFields, pdfLimitFields: pdfLimitFields, capturePdfOptions: capturePdfOptions, capturePdfLimits: capturePdfLimits, captureWideTable: captureWideTable, settings: settings });
5975
+ const _exports = Object.freeze({ positive: _m58.positive, color: _m58.color, presentation: _m58.presentation, pdfOptionFields: pdfOptionFields, pdfLimitFields: pdfLimitFields, pdfDrawingLimits: pdfDrawingLimits, pdfDrawingMaxDepth: pdfDrawingMaxDepth, capturePdfOptions: capturePdfOptions, capturePdfLimits: capturePdfLimits, captureWideTable: captureWideTable, settings: settings });
5910
5976
  return _exports;
5911
5977
  })();
5912
5978
 
@@ -7424,7 +7490,7 @@ class PdfFontResources {
7424
7490
  this.fontBytes += bytes;
7425
7491
  this.registered.add(font);
7426
7492
  }
7427
- select(bold = false, italic = false, explicit) {
7493
+ select(bold = false, italic = false, explicit, standardForMissingFace = false) {
7428
7494
  if (explicit)
7429
7495
  this.registerFont(explicit);
7430
7496
  let selections = this.selections;
@@ -7434,10 +7500,13 @@ class PdfFontResources {
7434
7500
  if (!found)
7435
7501
  this.explicitSelections.set(explicit, selections);
7436
7502
  }
7437
- const key = (bold ? 2 : 0) | (italic ? 1 : 0), existing = selections.get(key);
7503
+ const fallback = standardForMissingFace && !explicit && this.fonts !== undefined &&
7504
+ this.fonts[bold ? italic ? "boldItalic" : "bold" : italic ? "italic" : "regular"] === undefined;
7505
+ const key = (bold ? 2 : 0) | (italic ? 1 : 0) | (fallback ? 4 : 0), existing = selections.get(key);
7438
7506
  if (existing)
7439
7507
  return existing;
7440
- const { font, syntheticBold, syntheticItalic } = explicit ? { font: explicit, syntheticBold: bold, syntheticItalic: italic } : selectFont(this.fonts, bold, italic);
7508
+ const { font, syntheticBold, syntheticItalic } = explicit ? { font: explicit, syntheticBold: bold, syntheticItalic: italic } :
7509
+ selectFont(fallback ? undefined : this.fonts, bold, italic);
7441
7510
  const shared = font ? this.programs.get(font) : undefined;
7442
7511
  const resource = new PdfFontResource(this.resources.length + 1, bold, italic, font, this.objects, syntheticBold, syntheticItalic, shared, this.signal);
7443
7512
  if (!shared) {
@@ -8731,6 +8800,7 @@ class PdfPages {
8731
8800
  rectangleLefts;
8732
8801
  rectangleColumns = [];
8733
8802
  externalObjects = new Map();
8803
+ opacityStates = new Map();
8734
8804
  bandFlow;
8735
8805
  bandCellBudget = false;
8736
8806
  tableElement;
@@ -9313,6 +9383,20 @@ class PdfPages {
9313
9383
  }
9314
9384
  async pageBreak() { await this.ensureStarted(); await this.finishPage(); await this.start(false); }
9315
9385
  registerXObject(name, id) { this.externalObjects.set(name, id); }
9386
+ /** One shared constant-opacity graphics state per serialized alpha value. */
9387
+ opacityState(alpha) {
9388
+ const value = pdfNumber(alpha);
9389
+ let name = this.opacityStates.get(value);
9390
+ if (!name) {
9391
+ name = "GA" + (this.opacityStates.size + 1);
9392
+ this.opacityStates.set(value, name);
9393
+ }
9394
+ return name;
9395
+ }
9396
+ graphicsStates() {
9397
+ const entries = [...this.opacityStates].map(([alpha, name]) => "/" + name + " << /ca " + alpha + " /CA " + alpha + " >>");
9398
+ return entries.length ? " /ExtGState << " + entries.join(" ") + " >>" : "";
9399
+ }
9316
9400
  /** Height after the existing fit-to-page graphic policy, used by heading keep constraints. */
9317
9401
  graphicHeight(width, height) {
9318
9402
  const { page, margins } = this.settings;
@@ -9899,13 +9983,14 @@ class PdfWriteSession {
9899
9983
  await pages.finish();
9900
9984
  for (const font of fonts.resources)
9901
9985
  await font.write(objects, options.compression !== false);
9902
- await objects.object(this.resources, "<< /Font " + fonts.dictionary() + pages.xobjects() + " >>");
9986
+ await objects.object(this.resources, "<< /Font " + fonts.dictionary() + pages.xobjects() + pages.graphicsStates() + " >>");
9903
9987
  await objects.object(this.parent, "<< /Type /Pages /Count " + pages.references.length + " /Kids [" + pages.references.map(id => id + " 0 R").join(" ") + "] >>");
9904
9988
  if (this.structure)
9905
9989
  await this.structure.finish();
9906
9990
  await this.outlines.finish();
9907
9991
  await objects.object(this.root, "<< /Type /Catalog /Pages " + this.parent + " 0 R" + (this.structure?.catalogDictionary ?? "") + this.outlines.catalogDictionary + " >>");
9908
- await objects.object(this.info, "<< /Producer (OfficeIMO.js)" + (options.title === undefined ? "" : " /Title <feff" + unicodeHex(options.title) + ">") + " >>");
9992
+ const title = options.metadataTitle ?? options.title;
9993
+ await objects.object(this.info, "<< /Producer (OfficeIMO.js)" + (title === undefined ? "" : " /Title <feff" + unicodeHex(title) + ">") + " >>");
9909
9994
  await objects.finish(this.root, this.info);
9910
9995
  }
9911
9996
  }
@@ -9990,15 +10075,10 @@ const { Crc32 } = _m16;
9990
10075
 
9991
10076
  const signature = [137, 80, 78, 71, 13, 10, 26, 10];
9992
10077
  const unsupportedChunks = new Set(["PLTE", "tRNS", "iCCP", "sRGB", "gAMA", "cHRM", "cICP", "mDCV", "cLLI", "sBIT", "eXIf", "acTL", "fcTL", "fdAT"]);
9993
- /** Decode the static unprofiled 8-bit RGB/RGBA profile without canvas or a second compression engine. */
9994
- async function pngPixels(inputSource, maxPixels, signal, maxWorkingBytes) {
10078
+ /** Decode an owned static unprofiled PNG without canvas or a second compression engine. */
10079
+ async function pngPixels(source, shape, signal) {
9995
10080
  checkAbort(signal);
9996
- const shape = pngShape(inputSource, maxPixels);
9997
10081
  const imagePixels = shape.width * shape.height;
9998
- const workingBytes = inputSource.length + imagePixels * shape.components + (shape.components === 4 ? shape.width * 8 : 0);
9999
- if (maxWorkingBytes !== undefined && workingBytes > maxWorkingBytes)
10000
- throw new OfficeIMOError("RESOURCE_LIMIT", "maxImageWorkingBytes exceeded by PNG source, image planes and scanlines.");
10001
- const source = new Uint8Array(inputSource);
10002
10082
  const header = await pngHeader(source, shape, signal);
10003
10083
  checkAbort(signal);
10004
10084
  let stream;
@@ -10012,9 +10092,6 @@ async function pngPixels(inputSource, maxPixels, signal, maxWorkingBytes) {
10012
10092
  }
10013
10093
  const { width, height, components } = header, rowBytes = width * components;
10014
10094
  const expected = (rowBytes + 1) * height;
10015
- // All dimensions and the exact filtered length are bounded before allocating decoded pixels.
10016
- if (!Number.isSafeInteger(expected) || expected > 0x7fffffff)
10017
- throw new OfficeIMOError("RESOURCE_LIMIT", "PNG filtered data exceeds the supported decoded byte length.");
10018
10095
  // RGBA is reconstructed one scanline at a time directly into PDF RGB/alpha planes.
10019
10096
  // It never retains an additional full interleaved RGBA image.
10020
10097
  const pixels = new Uint8Array(width * height * 3), alpha = components === 4 ? new Uint8Array(imagePixels) : undefined;
@@ -10162,20 +10239,55 @@ async function verifyPngZlibEnd(source, header, expected, signal) {
10162
10239
  reader.releaseLock();
10163
10240
  }
10164
10241
  }
10242
+ function pngChunk(source, view, offset) {
10243
+ if (offset + 12 > source.length)
10244
+ throw new TypeError("Truncated PNG chunk.");
10245
+ const length = view.getUint32(offset), end = offset + 12 + length;
10246
+ if (length > 0x7fffffff || end > source.length)
10247
+ throw new TypeError("Truncated or oversized PNG chunk.");
10248
+ const type = String.fromCharCode(...source.subarray(offset + 4, offset + 8));
10249
+ if (!/^[A-Za-z]{2}[A-Z][A-Za-z]$/.test(type))
10250
+ throw new TypeError("Invalid PNG chunk type.");
10251
+ return { length, end, type };
10252
+ }
10253
+ function checkAncillaryChunk(type) {
10254
+ if (unsupportedChunks.has(type))
10255
+ throw new NotSupportedError("PNG chunk " + type + "; normalize color, orientation, transparency or animation first");
10256
+ if (type.charCodeAt(0) < 97)
10257
+ throw new NotSupportedError("Required PNG chunk " + type);
10258
+ }
10259
+ /** Check the image profile for SVG placement without inflating pixels. Embedding still verifies CRCs and image data. */
10260
+ function pngEmbeddableSize(source) {
10261
+ const shape = pngShape(source, Infinity);
10262
+ const view = new DataView(source.buffer, source.byteOffset, source.byteLength);
10263
+ let hasData = false, dataClosed = false;
10264
+ for (let offset = 33; offset < source.length;) {
10265
+ const { length, end, type } = pngChunk(source, view, offset);
10266
+ if (type === "IEND") {
10267
+ if (length === 0 && hasData && end === source.length)
10268
+ return shape;
10269
+ break;
10270
+ }
10271
+ if (type === "IDAT") {
10272
+ if (dataClosed)
10273
+ throw new TypeError("PNG IDAT chunks must be consecutive.");
10274
+ hasData = true;
10275
+ }
10276
+ else {
10277
+ checkAncillaryChunk(type);
10278
+ dataClosed ||= hasData;
10279
+ }
10280
+ offset = end;
10281
+ }
10282
+ throw new TypeError("PNG requires a final empty IEND after IDAT.");
10283
+ }
10165
10284
  /** Verify the complete source and critical chunk order before any decompressed image allocation. */
10166
10285
  async function pngHeader(source, shape, signal) {
10167
10286
  const view = new DataView(source.buffer, source.byteOffset, source.byteLength);
10168
10287
  let firstData = 0, dataEnd = 0, lastDataByte = -1, dataClosed = false;
10169
10288
  for (let offset = 8; offset < source.length;) {
10170
10289
  checkAbort(signal);
10171
- if (offset + 12 > source.length)
10172
- throw new TypeError("Truncated PNG chunk.");
10173
- const length = view.getUint32(offset), end = offset + 12 + length;
10174
- if (length > 0x7fffffff || end > source.length)
10175
- throw new TypeError("Truncated or oversized PNG chunk.");
10176
- const type = String.fromCharCode(...source.subarray(offset + 4, offset + 8));
10177
- if (!/^[A-Za-z]{2}[A-Z][A-Za-z]$/.test(type))
10178
- throw new TypeError("Invalid PNG chunk type.");
10290
+ const { length, end, type } = pngChunk(source, view, offset);
10179
10291
  const crc = new Crc32();
10180
10292
  for (let p = offset + 4; p < end - 4; p += 65536) {
10181
10293
  crc.update(source.subarray(p, Math.min(end - 4, p + 65536)));
@@ -10207,17 +10319,14 @@ async function pngHeader(source, shape, signal) {
10207
10319
  throw new TypeError("PNG requires a final empty IEND after IDAT.");
10208
10320
  return { ...shape, firstData, dataEnd, lastDataByte };
10209
10321
  }
10210
- if (unsupportedChunks.has(type))
10211
- throw new NotSupportedError("PNG chunk " + type + "; normalize color, orientation, transparency or animation first");
10212
- if ((source[offset + 4] & 32) === 0)
10213
- throw new NotSupportedError("Required PNG chunk " + type);
10322
+ checkAncillaryChunk(type);
10214
10323
  }
10215
10324
  offset = end;
10216
10325
  }
10217
10326
  throw new TypeError("PNG requires a complete final IEND chunk.");
10218
10327
  }
10219
10328
  /** Check source metadata synchronously, before capturing source bytes or allocating any image plane. */
10220
- function pngShape(source, maxPixels) {
10329
+ function pngShape(source, maxPixels, maxWorkingBytes) {
10221
10330
  if (source.length < 33 || signature.some((value, index) => source[index] !== value))
10222
10331
  throw new TypeError("Invalid PNG signature or truncated IHDR.");
10223
10332
  const view = new DataView(source.buffer, source.byteOffset, source.byteLength);
@@ -10237,6 +10346,9 @@ function pngShape(source, maxPixels) {
10237
10346
  const components = source[25] === 6 ? 4 : 3;
10238
10347
  if (!Number.isSafeInteger((width * components + 1) * height) || (width * components + 1) * height > 0x7fffffff)
10239
10348
  throw new OfficeIMOError("RESOURCE_LIMIT", "PNG filtered data exceeds the supported decoded byte length.");
10349
+ const workingBytes = source.length + width * height * components + (components === 4 ? width * 8 : 0);
10350
+ if (maxWorkingBytes !== undefined && workingBytes > maxWorkingBytes)
10351
+ throw new OfficeIMOError("RESOURCE_LIMIT", "maxImageWorkingBytes exceeded by PNG source, image planes and scanlines.");
10240
10352
  return { width, height, components };
10241
10353
  }
10242
10354
  function paeth(left, up, upperLeft) {
@@ -10244,7 +10356,7 @@ function paeth(left, up, upperLeft) {
10244
10356
  const a = Math.abs(prediction - left), b = Math.abs(prediction - up), c = Math.abs(prediction - upperLeft);
10245
10357
  return a <= b && a <= c ? left : b <= c ? up : upperLeft;
10246
10358
  }
10247
- const _exports = Object.freeze({ pngPixels: pngPixels });
10359
+ const _exports = Object.freeze({ pngPixels: pngPixels, pngEmbeddableSize: pngEmbeddableSize, pngShape: pngShape });
10248
10360
  return _exports;
10249
10361
  })();
10250
10362
 
@@ -10253,54 +10365,83 @@ const { NotSupportedError, OfficeIMOError } = _m2;
10253
10365
 
10254
10366
  const { checkAbort, pause, taskYieldDue } = _m4;
10255
10367
 
10256
- const { pngPixels } = _m86;
10368
+ const { pngPixels, pngShape } = _m86;
10257
10369
 
10258
10370
  /** Shared document image resources; source objects are captured on first consumption. */
10259
10371
  class PdfDocumentImages {
10260
10372
  objects;
10261
10373
  settings;
10262
10374
  images = new Map();
10375
+ snapshots = new WeakMap();
10263
10376
  bytes = 0;
10377
+ pendingBytes = 0;
10264
10378
  constructor(objects, settings) {
10265
10379
  this.objects = objects;
10266
10380
  this.settings = settings;
10267
10381
  }
10268
- async prepare(image) {
10269
- const existing = this.images.get(image);
10270
- if (existing)
10271
- return existing;
10382
+ /** Own a drawing image before preparing earlier elements can yield to the caller. */
10383
+ snapshot(image) {
10384
+ if (this.images.has(image) || this.snapshots.has(image))
10385
+ return;
10386
+ const captured = this.capture(image);
10387
+ this.snapshots.set(image, captured);
10388
+ this.pendingBytes += captured.data.length;
10389
+ }
10390
+ capture(image) {
10272
10391
  const { limits, options } = this.settings;
10392
+ checkAbort(options.signal);
10273
10393
  if (!image || typeof image !== "object")
10274
10394
  throw new TypeError("PDF images require a byte array.");
10275
- const data = image.data, format = image.format;
10395
+ const format = image.format;
10396
+ // Dimension getters may change a resizable backing buffer. Read them before measuring the byte view.
10397
+ const raw = format === "rgb" || format === "rgba" ? image : undefined;
10398
+ const widthValue = raw?.width, heightValue = raw?.height;
10399
+ const data = image.data;
10276
10400
  if (!(data instanceof Uint8Array))
10277
10401
  throw new TypeError("PDF images require a byte array.");
10278
10402
  const byteLength = data.length;
10279
- if (this.bytes + byteLength > limits.maxImageBytes)
10403
+ if (this.bytes + this.pendingBytes + byteLength > limits.maxImageBytes)
10280
10404
  throw new OfficeIMOError("RESOURCE_LIMIT", "maxImageBytes exceeded.");
10281
- let width, height, components, decoded, decodedAlpha;
10282
10405
  const maximumWorkingBytes = limits.maxImageWorkingBytes;
10283
- if (format === "png")
10284
- ({ width, height, components, data: decoded, alpha: decodedAlpha } = await pngPixels(data, limits.maxImagePixels, options.signal, maximumWorkingBytes));
10285
- else if (format === "jpeg")
10286
- ({ width, height, components } = jpegSize(data));
10406
+ if (format === "png") {
10407
+ const shape = pngShape(data, limits.maxImagePixels, maximumWorkingBytes);
10408
+ return { format, shape, data: new Uint8Array(data) };
10409
+ }
10410
+ let shape;
10411
+ if (format === "jpeg")
10412
+ shape = jpegSize(data);
10287
10413
  else if (format === "rgb" || format === "rgba") {
10288
- ({ width, height } = image);
10289
- components = format === "rgba" ? 4 : 3;
10414
+ shape = { width: widthValue, height: heightValue, components: format === "rgba" ? 4 : 3 };
10290
10415
  }
10291
10416
  else
10292
10417
  throw new NotSupportedError("PDF images support unprofiled PNG/JPEG or decoded RGB/RGBA pixels.");
10418
+ const { width, height, components } = shape;
10293
10419
  if (!Number.isSafeInteger(width) || !Number.isSafeInteger(height) || width < 1 || height < 1 ||
10294
10420
  !Number.isSafeInteger(width * height) || width * height > limits.maxImagePixels)
10295
10421
  throw new OfficeIMOError("RESOURCE_LIMIT", "Image dimensions must be positive integers within maxImagePixels.");
10296
- if ((format === "rgb" || format === "rgba") && byteLength !== width * height * components)
10422
+ if (format !== "jpeg" && byteLength !== width * height * components)
10297
10423
  throw new RangeError("Raw image bytes must match width × height × channels exactly.");
10298
- if (format !== "png" && maximumWorkingBytes !== undefined && byteLength + (components === 4 ? width * height : 0) > maximumWorkingBytes)
10424
+ if (maximumWorkingBytes !== undefined && byteLength + (components === 4 ? width * height : 0) > maximumWorkingBytes)
10299
10425
  throw new OfficeIMOError("RESOURCE_LIMIT", "maxImageWorkingBytes exceeded by image snapshot and alpha plane.");
10426
+ return { format, shape, data: new Uint8Array(data) };
10427
+ }
10428
+ async prepare(image) {
10429
+ const existing = this.images.get(image);
10430
+ if (existing)
10431
+ return existing;
10432
+ const { options } = this.settings, snapshot = this.snapshots.get(image);
10433
+ const source = snapshot ?? this.capture(image);
10434
+ if (snapshot) {
10435
+ this.snapshots.delete(image);
10436
+ this.pendingBytes -= source.data.length;
10437
+ }
10438
+ this.bytes += source.data.length;
10439
+ const { format } = source;
10440
+ const decoded = format === "png" ? await pngPixels(source.data, source.shape, options.signal) : undefined;
10441
+ const { width, height, components } = decoded ?? source.shape;
10300
10442
  checkAbort(options.signal);
10301
10443
  const id = this.objects.reserve(), name = "Image" + (this.images.size + 1);
10302
- this.bytes += byteLength;
10303
- const captured = decoded ?? new Uint8Array(data);
10444
+ const captured = decoded?.data ?? source.data, decodedAlpha = decoded?.alpha;
10304
10445
  let pixels = captured, alpha = decodedAlpha, mask;
10305
10446
  if (components === 4) {
10306
10447
  // Compact the owned RGBA snapshot in place. Forward writes never overwrite unread channels.
@@ -10322,20 +10463,22 @@ class PdfDocumentImages {
10322
10463
  mask = this.objects.reserve();
10323
10464
  await this.objects.stream(mask, alpha, "/Type /XObject /Subtype /Image /Width " + width + " /Height " + height + " /ColorSpace /DeviceGray /BitsPerComponent 8", options.compression !== false, true);
10324
10465
  }
10466
+ const jpegFilter = format === "jpeg" ? " /Filter /DCTDecode" +
10467
+ (source.shape.colorTransform === 0 ? " /DecodeParms << /ColorTransform 0 >>" : "") : "";
10325
10468
  const dictionary = "/Type /XObject /Subtype /Image /Width " + width + " /Height " + height + " /ColorSpace /" +
10326
10469
  (components === 1 ? "DeviceGray" : "DeviceRGB") + " /BitsPerComponent 8" + (mask ? " /SMask " + mask + " 0 R" : "") +
10327
- (format === "jpeg" ? " /Filter /DCTDecode" : "");
10470
+ jpegFilter;
10328
10471
  await this.objects.stream(id, pixels, dictionary, format === "jpeg" ? false : options.compression !== false, true);
10329
10472
  const resource = { name, id, width, height };
10330
10473
  this.images.set(image, resource);
10331
10474
  return resource;
10332
10475
  }
10333
10476
  }
10334
- /** Inspect bounded JPEG headers; JPEG entropy decoding remains the independent reader's job. */
10477
+ /** @internal Inspect bounded JPEG headers; JPEG entropy decoding remains the independent reader's job. */
10335
10478
  function jpegSize(bytes) {
10336
10479
  if (bytes.length < 4 || bytes[0] !== 255 || bytes[1] !== 216 || bytes[bytes.length - 2] !== 255 || bytes[bytes.length - 1] !== 217)
10337
10480
  throw new TypeError("JPEG images need complete SOI/EOI markers.");
10338
- let result;
10481
+ let result, rgb = false, adobe = false;
10339
10482
  for (let p = 2; p < bytes.length;) {
10340
10483
  if (bytes[p++] !== 255)
10341
10484
  throw new TypeError("Invalid JPEG marker.");
@@ -10345,7 +10488,8 @@ function jpegSize(bytes) {
10345
10488
  if (marker === 218) {
10346
10489
  if (!result)
10347
10490
  throw new TypeError("JPEG scan precedes its frame header.");
10348
- return result;
10491
+ // PDF decoders otherwise assume a color transform for three-component JPEGs.
10492
+ return rgb && !adobe ? { ...result, colorTransform: 0 } : result;
10349
10493
  }
10350
10494
  if (marker === 217)
10351
10495
  break;
@@ -10354,6 +10498,8 @@ function jpegSize(bytes) {
10354
10498
  const length = bytes[p] * 256 + bytes[p + 1], end = p + length;
10355
10499
  if (length < 2 || end > bytes.length)
10356
10500
  throw new TypeError("Truncated JPEG segment.");
10501
+ if (marker === 238 && length >= 14 && String.fromCharCode(...bytes.subarray(p + 2, p + 7)) === "Adobe")
10502
+ adobe = true;
10357
10503
  if (marker === 226 && length >= 14 && String.fromCharCode(...bytes.subarray(p + 2, p + 14)) === "ICC_PROFILE\0")
10358
10504
  throw new NotSupportedError("Normalize ICC-profiled JPEG colors before PDF embedding.");
10359
10505
  if (marker === 225 && length >= 8 && String.fromCharCode(...bytes.subarray(p + 2, p + 8)) === "Exif\0\0")
@@ -10366,7 +10512,8 @@ function jpegSize(bytes) {
10366
10512
  throw new NotSupportedError("PDF JPEG images require grayscale or RGB components; CMYK is unsupported.");
10367
10513
  if (components === 3) {
10368
10514
  const ids = [bytes[p + 8], bytes[p + 11], bytes[p + 14]].join(",");
10369
- if (ids !== "1,2,3" && ids !== "82,71,66")
10515
+ rgb = ids === "82,71,66";
10516
+ if (ids !== "1,2,3" && !rgb)
10370
10517
  throw new NotSupportedError("Unsupported JPEG component color layout.");
10371
10518
  }
10372
10519
  if (result)
@@ -10377,7 +10524,7 @@ function jpegSize(bytes) {
10377
10524
  }
10378
10525
  throw new TypeError("JPEG image has no complete frame and scan.");
10379
10526
  }
10380
- const _exports = Object.freeze({ PdfDocumentImages: PdfDocumentImages });
10527
+ const _exports = Object.freeze({ PdfDocumentImages: PdfDocumentImages, jpegSize: jpegSize });
10381
10528
  return _exports;
10382
10529
  })();
10383
10530
 
@@ -10472,7 +10619,7 @@ const { NotSupportedError, OfficeIMOError } = _m2;
10472
10619
 
10473
10620
  const { checkAbort, pause, taskYieldDue } = _m4;
10474
10621
 
10475
- const { color, positive } = _m56;
10622
+ const { color, pdfDrawingMaxDepth, positive } = _m56;
10476
10623
 
10477
10624
  const { pdfNumber: n } = _m60;
10478
10625
 
@@ -10494,22 +10641,50 @@ function clipRectangle(value) {
10494
10641
  const clip = record(value, ["x", "y", "width", "height"], "drawing clip");
10495
10642
  return { x: coordinate(clip.x), y: coordinate(clip.y), width: positive(clip.width, "Drawing clip width", 1000000), height: positive(clip.height, "Drawing clip height", 1000000) };
10496
10643
  }
10644
+ /** A PDF dash array: 1 through 16 nonnegative lengths, not all zero, and a finite phase. */
10645
+ function dashPattern(value, offset) {
10646
+ if (value === undefined) {
10647
+ if (offset !== undefined)
10648
+ throw new TypeError("Drawing dashOffset requires dash.");
10649
+ return "";
10650
+ }
10651
+ if (!Array.isArray(value) || !value.length || value.length > 16)
10652
+ throw new TypeError("Drawing dash must list 1 through 16 nonnegative lengths with at least one positive length.");
10653
+ const lengths = Array.from(value, item => {
10654
+ if (typeof item !== "number" || !Number.isFinite(item) || item < 0 || item > 14400)
10655
+ throw new TypeError("Drawing dash lengths must be from 0 through 14,400 points.");
10656
+ return n(item);
10657
+ });
10658
+ if (lengths.every(length => length === "0"))
10659
+ throw new TypeError("Drawing dash needs a positive length after PDF rounding.");
10660
+ let phase = coordinate(offset ?? 0);
10661
+ if (phase < 0) {
10662
+ // Work in serialized thousandths of a point. Odd arrays repeat twice before the paint state repeats.
10663
+ const period = lengths.reduce((sum, length) => sum + Math.round(Number(length) * 1000), 0) * (lengths.length % 2 ? 2 : 1);
10664
+ phase = ((Math.round(phase * 1000) % period + period) % period) / 1000;
10665
+ }
10666
+ return "[" + lengths.join(" ") + "] " + n(phase) + " d\n";
10667
+ }
10497
10668
  async function cooperate(settings) {
10498
10669
  if (taskYieldDue())
10499
10670
  await pause();
10500
10671
  checkAbort(settings.options.signal);
10501
10672
  }
10502
10673
  /** Take ownership of one bounded schema before any cooperative or font work can run caller code. */
10503
- function captureDrawing(drawing, settings, used) {
10674
+ function captureDrawing(drawing, settings, used, images) {
10504
10675
  checkAbort(settings.options.signal);
10505
- const root = record(drawing, ["version", "width", "height", "elements"], "drawing");
10506
- if (root.version !== 1)
10507
- throw new NotSupportedError("Only portable drawing version 1 is supported.");
10676
+ const root = record(drawing, ["version", "width", "height", "elements", "standardFonts"], "drawing");
10677
+ const standardFonts = root.standardFonts;
10678
+ if (standardFonts !== undefined && typeof standardFonts !== "boolean")
10679
+ throw new TypeError("Drawing standardFonts must be boolean.");
10680
+ const version = root.version;
10681
+ if (version !== 1 && version !== 2)
10682
+ throw new NotSupportedError("Only portable drawing versions 1 and 2 are supported.");
10508
10683
  const width = positive(root.width, "Drawing width"), height = positive(root.height, "Drawing height");
10509
10684
  let commands = used.commands, elements = used.elements;
10510
10685
  const ancestors = new Set();
10511
10686
  function path(value) {
10512
- record(value, ["kind", "commands", "fill", "stroke", "strokeWidth", "fillRule", "lineCap", "lineJoin"], "drawing path");
10687
+ record(value, ["kind", "commands", "fill", "stroke", "strokeWidth", "fillRule", "lineCap", "lineJoin", "miterLimit", "dash", "dashOffset"], "drawing path");
10513
10688
  const source = value.commands;
10514
10689
  if (!Array.isArray(source))
10515
10690
  throw new TypeError("Drawing path commands must be an array.");
@@ -10531,6 +10706,10 @@ function captureDrawing(drawing, settings, used) {
10531
10706
  throw new TypeError("Invalid drawing lineCap.");
10532
10707
  if (lineJoin !== undefined && !["miter", "round", "bevel"].includes(lineJoin))
10533
10708
  throw new TypeError("Invalid drawing lineJoin.");
10709
+ const miterLimit = positive(value.miterLimit ?? 10, "Drawing miter limit", 1000000);
10710
+ if (miterLimit < 1)
10711
+ throw new RangeError("Drawing miter limit must be at least 1.");
10712
+ const dash = dashPattern(value.dash, value.dashOffset);
10534
10713
  for (let i = 0; i < snapshot.length; i++) {
10535
10714
  const c = snapshot[i];
10536
10715
  if (!c || typeof c !== "object")
@@ -10563,11 +10742,12 @@ function captureDrawing(drawing, settings, used) {
10563
10742
  if (!started)
10564
10743
  throw new TypeError("A drawing path needs at least one command.");
10565
10744
  return { kind: "path", commands: copied, style: (fill === undefined ? "" : fill + " rg\n") + (stroke === undefined ? "" : stroke + " RG\n" + n(strokeWidth) + " w\n") +
10566
- String(["butt", "round", "square"].indexOf(lineCap ?? "butt")) + " J\n" + String(["miter", "round", "bevel"].indexOf(lineJoin ?? "miter")) + " j\n10 M\n",
10745
+ String(["butt", "round", "square"].indexOf(lineCap ?? "butt")) + " J\n" + String(["miter", "round", "bevel"].indexOf(lineJoin ?? "miter")) +
10746
+ " j\n" + n(miterLimit) + " M\n" + dash,
10567
10747
  paint: (fill !== undefined && stroke !== undefined ? "B" : fill !== undefined ? "f" : "S") + (fill !== undefined && fillRule === "evenodd" ? "*" : "") + "\n" };
10568
10748
  }
10569
10749
  function text(value) {
10570
- record(value, ["kind", "text", "x", "y", "font", "fontSize", "color"], "drawing text");
10750
+ record(value, ["kind", "text", "x", "y", "font", "fontSize", "color", "anchor", "rotation"], "drawing text");
10571
10751
  const snapshot = value.text, slot = value.font;
10572
10752
  if (typeof snapshot !== "string")
10573
10753
  throw new TypeError("Drawing text must be a string.");
@@ -10578,14 +10758,33 @@ function captureDrawing(drawing, settings, used) {
10578
10758
  if (!["regular", "bold", "italic", "boldItalic"].includes(slot))
10579
10759
  throw new TypeError("Invalid drawing font slot.");
10580
10760
  const x = coordinate(value.x), y = coordinate(value.y), size = positive(value.fontSize, "Drawing font size"), foreground = color(value.color);
10761
+ const anchor = value.anchor, rotation = value.rotation ?? 0;
10762
+ if (anchor !== undefined && !["start", "middle", "end"].includes(anchor))
10763
+ throw new TypeError("Invalid drawing text anchor.");
10764
+ if (typeof rotation !== "number" || !Number.isFinite(rotation) || Math.abs(rotation) > 360)
10765
+ throw new RangeError("Drawing text rotation must be finite degrees within -360 through 360.");
10581
10766
  settings.budget.cell(snapshot);
10582
- return { kind: "text", text: snapshot, x, y, size, color: foreground, font: slot };
10767
+ // Quarter turns stay exact so upright and vertical axis labels keep integral matrices.
10768
+ const turn = rotation % 90 === 0 ? (((rotation / 90) % 4) + 4) % 4 : -1, radians = rotation * Math.PI / 180;
10769
+ const cos = turn < 0 ? Math.cos(radians) : [1, 0, -1, 0][turn], sin = turn < 0 ? Math.sin(radians) : [0, 1, 0, -1][turn];
10770
+ return { kind: "text", text: snapshot, x, y, size, color: foreground, font: slot, anchor: anchor === "middle" ? .5 : anchor === "end" ? 1 : 0, cos, sin };
10771
+ }
10772
+ function image(value) {
10773
+ record(value, ["kind", "image", "x", "y", "width", "height", "opacity"], "drawing image");
10774
+ const x = coordinate(value.x), y = coordinate(value.y), suppliedOpacity = value.opacity;
10775
+ const opacity = suppliedOpacity === undefined ? 1 : suppliedOpacity;
10776
+ const width = positive(value.width, "Drawing image width", 1000000), height = positive(value.height, "Drawing image height", 1000000);
10777
+ if (typeof opacity !== "number" || !(opacity >= 0 && opacity <= 1))
10778
+ throw new RangeError("Drawing image opacity must be from 0 through 1.");
10779
+ const source = value.image;
10780
+ images.snapshot(source);
10781
+ return { kind: "image", image: source, x, y, width, height, opacity };
10583
10782
  }
10584
10783
  function children(input, depth) {
10585
10784
  if (!Array.isArray(input))
10586
10785
  throw new TypeError("Drawing elements must be an array.");
10587
- if (depth > 32 && input.length)
10588
- throw new RangeError("Drawing groups support at most 32 element levels.");
10786
+ if (depth > pdfDrawingMaxDepth && input.length)
10787
+ throw new RangeError("Drawing groups support at most " + pdfDrawingMaxDepth + " element levels.");
10589
10788
  if (elements + input.length > settings.limits.maxDrawingElements)
10590
10789
  throw new OfficeIMOError("RESOURCE_LIMIT", "maxDrawingElements exceeded.");
10591
10790
  checkAbort(settings.options.signal);
@@ -10603,6 +10802,8 @@ function captureDrawing(drawing, settings, used) {
10603
10802
  output.push(path(value));
10604
10803
  else if (kind === "text")
10605
10804
  output.push(text(value));
10805
+ else if (kind === "image" && version === 2)
10806
+ output.push(image(value));
10606
10807
  else if (kind === "group") {
10607
10808
  record(value, ["kind", "clip", "elements"], "drawing group");
10608
10809
  const clipValue = value.clip, clip = clipValue === undefined ? undefined : clipRectangle(clipValue);
@@ -10619,29 +10820,35 @@ function captureDrawing(drawing, settings, used) {
10619
10820
  }
10620
10821
  const plan = children(root.elements, 1);
10621
10822
  checkAbort(settings.options.signal);
10622
- return { width, height, plan, commands: commands - used.commands, elements: elements - used.elements };
10823
+ return { width, height, plan, commands: commands - used.commands, elements: elements - used.elements, standardFonts: standardFonts === true };
10623
10824
  }
10624
10825
  /** Preflight and paint owned records. The existing font owner retains glyph maps and subsets. */
10625
- async function prepareDrawing(drawing, settings, fonts, used) {
10826
+ async function prepareDrawing(drawing, settings, fonts, used, resources) {
10626
10827
  // A drawing's bounded capture is synchronous; yielding here would leave later caller records borrowed.
10627
- const captured = captureDrawing(drawing, settings, used), drawingFonts = new Map();
10828
+ const { images } = resources, captured = captureDrawing(drawing, settings, used, images), drawingFonts = new Map();
10628
10829
  function fontFor(slot) {
10629
10830
  const existing = drawingFonts.get(slot);
10630
10831
  if (existing)
10631
10832
  return existing;
10632
- const font = fonts.select(slot === "bold" || slot === "boldItalic", slot === "italic" || slot === "boldItalic");
10633
- if (!font.program || font.syntheticBold || font.syntheticItalic)
10833
+ const font = fonts.select(slot === "bold" || slot === "boldItalic", slot === "italic" || slot === "boldItalic", undefined, captured.standardFonts);
10834
+ if (font.syntheticBold || font.syntheticItalic || !font.program && !captured.standardFonts)
10634
10835
  throw new NotSupportedError("Drawing text without an exact embedded font face at fonts." + slot);
10635
10836
  drawingFonts.set(slot, font);
10636
10837
  return font;
10637
10838
  }
10638
10839
  // The work budget belongs to the drawing, including short runs in separate sibling groups.
10639
10840
  let preflightCharacters = 0, preflightElements = 0;
10841
+ const imageNames = new Map();
10640
10842
  async function preflight(nodes) {
10641
10843
  for (let i = 0; i < nodes.length; i++) {
10642
10844
  const node = nodes[i];
10643
10845
  if (node.kind === "group")
10644
10846
  await preflight(node.children);
10847
+ else if (node.kind === "image" && !imageNames.has(node.image)) {
10848
+ const resource = await images.prepare(node.image);
10849
+ resources.registerImage(resource.name, resource.id);
10850
+ imageNames.set(node.image, resource.name);
10851
+ }
10645
10852
  else if (node.kind === "text") {
10646
10853
  const font = fontFor(node.font);
10647
10854
  for (const character of node.text) {
@@ -10684,9 +10891,23 @@ async function prepareDrawing(drawing, settings, fonts, used) {
10684
10891
  }
10685
10892
  add(node.paint);
10686
10893
  }
10894
+ else if (node.kind === "image") {
10895
+ // Image space is a unit square with a bottom-left origin; the drawing's y axis points down.
10896
+ if (node.opacity < 1)
10897
+ add("/" + resources.opacity(node.opacity) + " gs\n");
10898
+ add([node.width, 0, 0, -node.height, node.x, node.y + node.height].map(n).join(" ") + " cm /" + imageNames.get(node.image) + " Do\n");
10899
+ }
10687
10900
  else {
10688
10901
  const font = fontFor(node.font);
10689
- add(node.color + " rg\nBT /" + font.name + " " + n(node.size) + " Tf 0 Tr 1 0 0 -1 " + n(node.x) + " " + n(node.y) + " Tm <");
10902
+ let shift = 0;
10903
+ if (node.anchor) {
10904
+ for (const character of node.text)
10905
+ shift += font.width(character.codePointAt(0));
10906
+ shift *= node.size / 1000 * node.anchor;
10907
+ }
10908
+ // Text space is upright in the drawing's downward y axis; rotation turns the baseline clockwise about its anchor.
10909
+ add(node.color + " rg\nBT /" + font.name + " " + n(node.size) + " Tf 0 Tr " +
10910
+ [node.cos, node.sin, node.sin, -node.cos, node.x - shift * node.cos, node.y - shift * node.sin].map(n).join(" ") + " Tm <");
10690
10911
  let chunk = "";
10691
10912
  for (const character of node.text) {
10692
10913
  chunk += character;
@@ -11409,7 +11630,9 @@ async function writePdfDocumentTo(blocks, destination, configuration = {}) {
11409
11630
  const inputDrawing = block.drawing, capturedCaption = snapshotCaption(block.caption), alternative = graphicAlternative(block, pages.settings), alignment = graphicAlignment(block.alignment);
11410
11631
  if (capturedCaption && alternative === undefined)
11411
11632
  throw new TypeError("A captioned PDF graphic requires alternativeText and cannot be decorative.");
11412
- const drawing = await prepareDrawing(inputDrawing, pages.settings, fonts, { commands, elements: drawingElements }), caption = await prepareCaption(capturedCaption);
11633
+ const drawing = await prepareDrawing(inputDrawing, pages.settings, fonts, { commands, elements: drawingElements }, {
11634
+ images, registerImage: (name, id) => pages.registerXObject(name, id), opacity: alpha => pages.opacityState(alpha)
11635
+ }), caption = await prepareCaption(capturedCaption);
11413
11636
  commands += drawing.commands;
11414
11637
  drawingElements += drawing.elements;
11415
11638
  await flushParagraphs((caption?.height ?? 0) + pages.graphicHeight(drawing.width, drawing.height));
@@ -11551,6 +11774,6 @@ const _m0 = (() => {
11551
11774
  const _exports = Object.freeze({ core: _m1, zip: _m14, xml: _m17, opc: _m18, xlsx: _m21, csv: _m50, pdf: _m54, Workbook: _m21.Workbook, Worksheet: _m21.Worksheet, Cell: _m21.Cell, FormulaCell: _m21.FormulaCell, StyleRegistry: _m21.StyleRegistry, NumberFormats: _m21.NumberFormats, writeXlsx: _m21.writeXlsx, writeXlsxTo: _m21.writeXlsxTo, writeCsv: _m50.writeCsv, writeCsvTo: _m50.writeCsvTo, createGroupedReport: _m8.createGroupedReport, writeGroupedXlsx: _m48.writeGroupedXlsx, writeGroupedXlsxTo: _m48.writeGroupedXlsxTo, addGroupedXlsx: _m48.addGroupedXlsx, writeGroupedPdf: _m83.writeGroupedPdf, writeGroupedPdfTo: _m83.writeGroupedPdfTo, pdfGroupedTable: _m83.pdfGroupedTable, writePdf: _m54.writePdf, writePdfTo: _m54.writePdfTo, writePdfDocument: _m54.writePdfDocument, writePdfDocumentTo: _m54.writePdfDocumentTo, pdfTable: _m54.pdfTable, PdfFont: _m54.PdfFont, preflightPdfText: _m54.preflightPdfText, OfficeIMOError: _m1.OfficeIMOError, NotSupportedError: _m1.NotSupportedError, detectFeatures: _m1.detectFeatures, saveBlob: _m1.saveBlob, ExportCell: _m1.ExportCell });
11552
11775
  return _exports;
11553
11776
  })();
11554
- const __officeimoModules = Object.freeze({ "81b3d47c02b7d8443b79e02b3cfb52032d6b73d9a3fb592b777ebe028ad0ef00": _m1, "6cfd3e806439f6301003a2d1699a74fdfa574d935550ab62b97b528728eaee1f": _m23, "b48bcab805d4c75294dd8d8e8dc57f96d9db3f5af31a8f0ddc6562f010f566e4": _m50, "e5310c591178a3de9292f150e2e6f1477b94b895ef0c90840c72adef00f75974": _m21, "027aafa08408056b10d7d717d63d1f7c0ee20ecfc68213aa66feacc75ec525fe": _m54, "62ff1bcbf8ca07e8ab92cd1f6afbd54049346193e18160ab0afec48e03950bba": _m47, "732224f6995c2478cf33a6ed01f3e3d3dcccb159a731d6db9280104bd5040fc5": _m5, "d56b24243cff6f3552a2f7b45521af4491494375ec76117e9ac1ebb047ce02da": _m30, "87c24efeaa0f1579c19afeeb4918caeb4f8f65a88d24a246e2cfd712b37dbac3": _m4, "42faf379960e5674a6fdfa8c8fca0bb68bbd74587231248d2524d7004def3671": _m9, "50b3c10b690ceff693c8c5f809195ba6845b20e60f408e791a750d2ecbd5c669": _m10, "0391fe35ea7d02b25804ab4d0e7543136d6bb615f368f268c74aa135f23aa6bc": _m11, "f0627ba89e5c8fcb376ebe3ce72dcc8d68c34952981f8703e36b8bb1a9894208": _m53, "4a089607f7cbe50e13d4382d1cc4e5f6ce32c5773bbec2df84178710f54d9a38": _m56, "8f13b484030aa6b921e616d803614fd061f718241692003633375fab4c36045e": _m43, "d9c1509dff0538488752433e47cd0927ece5f93c559ad0e32dc56602dfd44596": _m63, "e88a83ca79cd099fc2de29689554c913c7d04b17018098f81c43044064fcdfb8": _m27, "046b305cdccf817d847addb75a778131622de23f2840830bbe1c0c26053a68c0": _m8, "c9fde2c438e186da56f740105fcd41c265fdfdd855a4f1b811d556a02387479b": _m12, "227236fd7adc9472e188831b8f16fdc69338c4d779f2b69a8abbd8dbfa95b585": _m17, "5337d1e3bd5ae0c1d10a476fcd31540d20337ccf7aa93c7e9e26c2b1a7dab92b": _m3, "59911f0fe023545e9e97521b268551078bdc4c5f303e446a13b7d52f905e8070": _m67 });
11777
+ const __officeimoModules = Object.freeze({ "81b3d47c02b7d8443b79e02b3cfb52032d6b73d9a3fb592b777ebe028ad0ef00": _m1, "4eea31c4336d3c43bc743739843a3ef31803d8f0ed553f5645ee9de2554eb244": _m23, "406ac6c93ee68eae70c6f52a1e6f4c56b84f43cae12576040c766dcc5598a580": _m50, "edf1bf5cb6d749de0e6823397df6610a6c1cc88768898c1b4d7083ee96ef6759": _m21, "344fd55ffe1a37b32a8eb6a2bdaa14dff90e0fee0f37282457f9e4c3b7bce1ca": _m54, "d6884428c3e4d15a691ecf2523372a03b32de22a890edfbfc9961f2dc92711c2": _m47, "732224f6995c2478cf33a6ed01f3e3d3dcccb159a731d6db9280104bd5040fc5": _m5, "d56b24243cff6f3552a2f7b45521af4491494375ec76117e9ac1ebb047ce02da": _m30, "87c24efeaa0f1579c19afeeb4918caeb4f8f65a88d24a246e2cfd712b37dbac3": _m4, "42faf379960e5674a6fdfa8c8fca0bb68bbd74587231248d2524d7004def3671": _m9, "50b3c10b690ceff693c8c5f809195ba6845b20e60f408e791a750d2ecbd5c669": _m10, "0391fe35ea7d02b25804ab4d0e7543136d6bb615f368f268c74aa135f23aa6bc": _m11, "f0627ba89e5c8fcb376ebe3ce72dcc8d68c34952981f8703e36b8bb1a9894208": _m53, "6c92204b587bb12cfa85c60eb1fd921804dfa51304538c7be3353e2927551b02": _m56, "fd70ccda89f27c6b874c8840ac944b3ec723dbdef3dfe7600f7bdb81f4660c96": _m43, "d9c1509dff0538488752433e47cd0927ece5f93c559ad0e32dc56602dfd44596": _m63, "e88a83ca79cd099fc2de29689554c913c7d04b17018098f81c43044064fcdfb8": _m27, "046b305cdccf817d847addb75a778131622de23f2840830bbe1c0c26053a68c0": _m8, "c9fde2c438e186da56f740105fcd41c265fdfdd855a4f1b811d556a02387479b": _m12, "227236fd7adc9472e188831b8f16fdc69338c4d779f2b69a8abbd8dbfa95b585": _m17, "5337d1e3bd5ae0c1d10a476fcd31540d20337ccf7aa93c7e9e26c2b1a7dab92b": _m3, "59911f0fe023545e9e97521b268551078bdc4c5f303e446a13b7d52f905e8070": _m67, "d5c945064d81fdd257960f48c421125e106e5f270427d170bb05587dd96a44ea": _m2, "e716b8b1da464094622f5f671518493c78e63ff22a029d61544d2d193b63ce8f": _m60, "32ca4982f963f400829c2e364b7d3479f36d91740dafb32d600f29b5cac487ec": _m85, "6b0244b5ec6d550c705b4e4cbb47997331f1ecd99e2bf8a06f7c646eebbffbf8": _m86, "8d96d0024443ac9aeaea70e9324b53aacef098c2385d4e6a89a76d184e28556a": _m24 });
11555
11778
  const { core, zip, xml, opc, xlsx, csv, pdf, Workbook, Worksheet, Cell, FormulaCell, StyleRegistry, NumberFormats, writeXlsx, writeXlsxTo, writeCsv, writeCsvTo, createGroupedReport, writeGroupedXlsx, writeGroupedXlsxTo, addGroupedXlsx, writeGroupedPdf, writeGroupedPdfTo, pdfGroupedTable, writePdf, writePdfTo, writePdfDocument, writePdfDocumentTo, pdfTable, PdfFont, preflightPdfText, OfficeIMOError, NotSupportedError, detectFeatures, saveBlob, ExportCell } = _m0;
11556
11779
  export { core, zip, xml, opc, xlsx, csv, pdf, Workbook, Worksheet, Cell, FormulaCell, StyleRegistry, NumberFormats, writeXlsx, writeXlsxTo, writeCsv, writeCsvTo, createGroupedReport, writeGroupedXlsx, writeGroupedXlsxTo, addGroupedXlsx, writeGroupedPdf, writeGroupedPdfTo, pdfGroupedTable, writePdf, writePdfTo, writePdfDocument, writePdfDocumentTo, pdfTable, PdfFont, preflightPdfText, OfficeIMOError, NotSupportedError, detectFeatures, saveBlob, ExportCell, __officeimoModules };