@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
@@ -301,15 +301,20 @@ return _exports;
301
301
  const _m5 = (() => {
302
302
  /** @internal Notify synchronously; observe an accidental promise before rejecting its unsupported use. */
303
303
  function notifyProgress(callback, progress) {
304
+ notifySynchronously("onProgress", callback, progress);
305
+ }
306
+ /** @internal Run a host notification that must finish before the export continues. A returned promise is observed,
307
+ * so its rejection is never unhandled, and the export fails instead of reporting success before the callback ends. */
308
+ function notifySynchronously(name, callback, value) {
304
309
  if (!callback)
305
310
  return;
306
- const result = callback(progress);
311
+ const result = callback(value);
307
312
  if (result && typeof result.then === "function") {
308
313
  void Promise.resolve(result).catch(() => { });
309
- throw new TypeError("onProgress must be synchronous.");
314
+ throw new TypeError(name + " must be synchronous.");
310
315
  }
311
316
  }
312
- const _exports = Object.freeze({ notifyProgress: notifyProgress });
317
+ const _exports = Object.freeze({ notifyProgress: notifyProgress, notifySynchronously: notifySynchronously });
313
318
  return _exports;
314
319
  })();
315
320
 
@@ -825,12 +830,16 @@ const sizes = {
825
830
  };
826
831
  /** @internal Shared capture schema for thin format adapters and the grouped writer. */
827
832
  const pdfOptionFields = ["columns", "signal", "onProgress", "limits", "textShaper", "textDirection", "pageSize", "orientation", "margins", "fonts", "tagged", "fontSize",
828
- "title", "messageTop", "messageBottom", "includeHeader", "headerRows", "footer", "headerPresentation", "footerPresentation", "alternateRowColor", "padding",
833
+ "title", "metadataTitle", "messageTop", "messageBottom", "includeHeader", "headerRows", "footer", "headerPresentation", "footerPresentation", "alternateRowColor", "padding",
829
834
  "columnWidths", "wideTable", "pageHeader", "pageFooter", "pageNumbers", "pageNumberLabels", "booleanText", "formatValue", "formatRuns", "compression", "paragraphStyles"];
830
835
  /** @internal Complete PDF limit schema used when a host combines format and shared limits. */
831
836
  const pdfLimitFields = ["maxRows", "maxCells", "maxTextCharacters", "maxOutputBytes", "maxPages", "maxColumns", "maxTableBands", "maxTableWindowRows", "maxCellCharacters", "maxTextRuns", "maxGroupBlocks", "maxRowLines",
832
837
  "maxFontBytes", "maxPageBytes", "maxHyperlinks", "maxImageBytes", "maxImagePixels", "maxImageWorkingBytes", "maxVectorCommands", "maxDrawingElements", "maxStructureElements",
833
838
  "maxMarkedContentReferences", "maxSections", "maxBookmarks", "maxListItems", "maxParagraphStyles"];
839
+ /** @internal Default ceilings shared by the drawing writer and its producers. */
840
+ const pdfDrawingLimits = Object.freeze({ maxVectorCommands: 100000, maxDrawingElements: 100000 });
841
+ /** @internal Maximum number of retained drawing levels including the leaf. */
842
+ const pdfDrawingMaxDepth = 32;
834
843
  /** @internal Capture supported structural properties once, including class-based options with prototype accessors. */
835
844
  function capturePdfOptions(input) {
836
845
  if (!input || typeof input !== "object" || Array.isArray(input))
@@ -941,7 +950,7 @@ function settings(input, document = false) {
941
950
  footerPresentation: Object.freeze({ background: "eef2f6", bold: true, ...presentation(configuration.footerPresentation) }) };
942
951
  const budget = new ExportBudget(options.limits);
943
952
  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,
944
- maxImageBytes: 32 * 1024 * 1024, maxImagePixels: 16 * 1024 * 1024, maxVectorCommands: 100000, maxDrawingElements: 100000,
953
+ maxImageBytes: 32 * 1024 * 1024, maxImagePixels: 16 * 1024 * 1024, ...pdfDrawingLimits,
945
954
  maxStructureElements: 1000000, maxMarkedContentReferences: 2000000,
946
955
  maxListItems: 100000, maxParagraphStyles: 256, maxSections: 1000, maxBookmarks: 10000 };
947
956
  for (const key of Object.keys(limits)) {
@@ -969,7 +978,7 @@ function settings(input, document = false) {
969
978
  const fontSize = positive(options.fontSize ?? 9, "Font size", 144), padding = options.padding ?? 4;
970
979
  if (!Number.isFinite(padding) || padding < 0 || padding > 72)
971
980
  throw new RangeError("PDF padding must be from 0 through 72 points.");
972
- for (const key of ["title", "messageTop", "messageBottom"])
981
+ for (const key of ["title", "metadataTitle", "messageTop", "messageBottom"])
973
982
  if (options[key] !== undefined && typeof options[key] !== "string")
974
983
  throw new TypeError(key + " must be text.");
975
984
  for (const key of ["pageHeader", "pageFooter"])
@@ -1005,7 +1014,7 @@ function settings(input, document = false) {
1005
1014
  repeatedColumns: document ? Object.freeze([]) : repeatedColumns(options.wideTable, columns),
1006
1015
  limits: { ...limits, ...(maxImageWorkingBytes === undefined ? {} : { maxImageWorkingBytes }) }, budget };
1007
1016
  }
1008
- const _exports = Object.freeze({ positive: _m16.positive, color: _m16.color, presentation: _m16.presentation, pdfOptionFields: pdfOptionFields, pdfLimitFields: pdfLimitFields, capturePdfOptions: capturePdfOptions, capturePdfLimits: capturePdfLimits, captureWideTable: captureWideTable, settings: settings });
1017
+ const _exports = Object.freeze({ positive: _m16.positive, color: _m16.color, presentation: _m16.presentation, pdfOptionFields: pdfOptionFields, pdfLimitFields: pdfLimitFields, pdfDrawingLimits: pdfDrawingLimits, pdfDrawingMaxDepth: pdfDrawingMaxDepth, capturePdfOptions: capturePdfOptions, capturePdfLimits: capturePdfLimits, captureWideTable: captureWideTable, settings: settings });
1009
1018
  return _exports;
1010
1019
  })();
1011
1020
 
@@ -2523,7 +2532,7 @@ class PdfFontResources {
2523
2532
  this.fontBytes += bytes;
2524
2533
  this.registered.add(font);
2525
2534
  }
2526
- select(bold = false, italic = false, explicit) {
2535
+ select(bold = false, italic = false, explicit, standardForMissingFace = false) {
2527
2536
  if (explicit)
2528
2537
  this.registerFont(explicit);
2529
2538
  let selections = this.selections;
@@ -2533,10 +2542,13 @@ class PdfFontResources {
2533
2542
  if (!found)
2534
2543
  this.explicitSelections.set(explicit, selections);
2535
2544
  }
2536
- const key = (bold ? 2 : 0) | (italic ? 1 : 0), existing = selections.get(key);
2545
+ const fallback = standardForMissingFace && !explicit && this.fonts !== undefined &&
2546
+ this.fonts[bold ? italic ? "boldItalic" : "bold" : italic ? "italic" : "regular"] === undefined;
2547
+ const key = (bold ? 2 : 0) | (italic ? 1 : 0) | (fallback ? 4 : 0), existing = selections.get(key);
2537
2548
  if (existing)
2538
2549
  return existing;
2539
- const { font, syntheticBold, syntheticItalic } = explicit ? { font: explicit, syntheticBold: bold, syntheticItalic: italic } : selectFont(this.fonts, bold, italic);
2550
+ const { font, syntheticBold, syntheticItalic } = explicit ? { font: explicit, syntheticBold: bold, syntheticItalic: italic } :
2551
+ selectFont(fallback ? undefined : this.fonts, bold, italic);
2540
2552
  const shared = font ? this.programs.get(font) : undefined;
2541
2553
  const resource = new PdfFontResource(this.resources.length + 1, bold, italic, font, this.objects, syntheticBold, syntheticItalic, shared, this.signal);
2542
2554
  if (!shared) {
@@ -3877,6 +3889,7 @@ class PdfPages {
3877
3889
  rectangleLefts;
3878
3890
  rectangleColumns = [];
3879
3891
  externalObjects = new Map();
3892
+ opacityStates = new Map();
3880
3893
  bandFlow;
3881
3894
  bandCellBudget = false;
3882
3895
  tableElement;
@@ -4459,6 +4472,20 @@ class PdfPages {
4459
4472
  }
4460
4473
  async pageBreak() { await this.ensureStarted(); await this.finishPage(); await this.start(false); }
4461
4474
  registerXObject(name, id) { this.externalObjects.set(name, id); }
4475
+ /** One shared constant-opacity graphics state per serialized alpha value. */
4476
+ opacityState(alpha) {
4477
+ const value = pdfNumber(alpha);
4478
+ let name = this.opacityStates.get(value);
4479
+ if (!name) {
4480
+ name = "GA" + (this.opacityStates.size + 1);
4481
+ this.opacityStates.set(value, name);
4482
+ }
4483
+ return name;
4484
+ }
4485
+ graphicsStates() {
4486
+ const entries = [...this.opacityStates].map(([alpha, name]) => "/" + name + " << /ca " + alpha + " /CA " + alpha + " >>");
4487
+ return entries.length ? " /ExtGState << " + entries.join(" ") + " >>" : "";
4488
+ }
4462
4489
  /** Height after the existing fit-to-page graphic policy, used by heading keep constraints. */
4463
4490
  graphicHeight(width, height) {
4464
4491
  const { page, margins } = this.settings;
@@ -5045,13 +5072,14 @@ class PdfWriteSession {
5045
5072
  await pages.finish();
5046
5073
  for (const font of fonts.resources)
5047
5074
  await font.write(objects, options.compression !== false);
5048
- await objects.object(this.resources, "<< /Font " + fonts.dictionary() + pages.xobjects() + " >>");
5075
+ await objects.object(this.resources, "<< /Font " + fonts.dictionary() + pages.xobjects() + pages.graphicsStates() + " >>");
5049
5076
  await objects.object(this.parent, "<< /Type /Pages /Count " + pages.references.length + " /Kids [" + pages.references.map(id => id + " 0 R").join(" ") + "] >>");
5050
5077
  if (this.structure)
5051
5078
  await this.structure.finish();
5052
5079
  await this.outlines.finish();
5053
5080
  await objects.object(this.root, "<< /Type /Catalog /Pages " + this.parent + " 0 R" + (this.structure?.catalogDictionary ?? "") + this.outlines.catalogDictionary + " >>");
5054
- await objects.object(this.info, "<< /Producer (OfficeIMO.js)" + (options.title === undefined ? "" : " /Title <feff" + unicodeHex(options.title) + ">") + " >>");
5081
+ const title = options.metadataTitle ?? options.title;
5082
+ await objects.object(this.info, "<< /Producer (OfficeIMO.js)" + (title === undefined ? "" : " /Title <feff" + unicodeHex(title) + ">") + " >>");
5055
5083
  await objects.finish(this.root, this.info);
5056
5084
  }
5057
5085
  }
@@ -5423,15 +5451,10 @@ const { Crc32 } = _m48;
5423
5451
 
5424
5452
  const signature = [137, 80, 78, 71, 13, 10, 26, 10];
5425
5453
  const unsupportedChunks = new Set(["PLTE", "tRNS", "iCCP", "sRGB", "gAMA", "cHRM", "cICP", "mDCV", "cLLI", "sBIT", "eXIf", "acTL", "fcTL", "fdAT"]);
5426
- /** Decode the static unprofiled 8-bit RGB/RGBA profile without canvas or a second compression engine. */
5427
- async function pngPixels(inputSource, maxPixels, signal, maxWorkingBytes) {
5454
+ /** Decode an owned static unprofiled PNG without canvas or a second compression engine. */
5455
+ async function pngPixels(source, shape, signal) {
5428
5456
  checkAbort(signal);
5429
- const shape = pngShape(inputSource, maxPixels);
5430
5457
  const imagePixels = shape.width * shape.height;
5431
- const workingBytes = inputSource.length + imagePixels * shape.components + (shape.components === 4 ? shape.width * 8 : 0);
5432
- if (maxWorkingBytes !== undefined && workingBytes > maxWorkingBytes)
5433
- throw new OfficeIMOError("RESOURCE_LIMIT", "maxImageWorkingBytes exceeded by PNG source, image planes and scanlines.");
5434
- const source = new Uint8Array(inputSource);
5435
5458
  const header = await pngHeader(source, shape, signal);
5436
5459
  checkAbort(signal);
5437
5460
  let stream;
@@ -5445,9 +5468,6 @@ async function pngPixels(inputSource, maxPixels, signal, maxWorkingBytes) {
5445
5468
  }
5446
5469
  const { width, height, components } = header, rowBytes = width * components;
5447
5470
  const expected = (rowBytes + 1) * height;
5448
- // All dimensions and the exact filtered length are bounded before allocating decoded pixels.
5449
- if (!Number.isSafeInteger(expected) || expected > 0x7fffffff)
5450
- throw new OfficeIMOError("RESOURCE_LIMIT", "PNG filtered data exceeds the supported decoded byte length.");
5451
5471
  // RGBA is reconstructed one scanline at a time directly into PDF RGB/alpha planes.
5452
5472
  // It never retains an additional full interleaved RGBA image.
5453
5473
  const pixels = new Uint8Array(width * height * 3), alpha = components === 4 ? new Uint8Array(imagePixels) : undefined;
@@ -5595,20 +5615,55 @@ async function verifyPngZlibEnd(source, header, expected, signal) {
5595
5615
  reader.releaseLock();
5596
5616
  }
5597
5617
  }
5618
+ function pngChunk(source, view, offset) {
5619
+ if (offset + 12 > source.length)
5620
+ throw new TypeError("Truncated PNG chunk.");
5621
+ const length = view.getUint32(offset), end = offset + 12 + length;
5622
+ if (length > 0x7fffffff || end > source.length)
5623
+ throw new TypeError("Truncated or oversized PNG chunk.");
5624
+ const type = String.fromCharCode(...source.subarray(offset + 4, offset + 8));
5625
+ if (!/^[A-Za-z]{2}[A-Z][A-Za-z]$/.test(type))
5626
+ throw new TypeError("Invalid PNG chunk type.");
5627
+ return { length, end, type };
5628
+ }
5629
+ function checkAncillaryChunk(type) {
5630
+ if (unsupportedChunks.has(type))
5631
+ throw new NotSupportedError("PNG chunk " + type + "; normalize color, orientation, transparency or animation first");
5632
+ if (type.charCodeAt(0) < 97)
5633
+ throw new NotSupportedError("Required PNG chunk " + type);
5634
+ }
5635
+ /** Check the image profile for SVG placement without inflating pixels. Embedding still verifies CRCs and image data. */
5636
+ function pngEmbeddableSize(source) {
5637
+ const shape = pngShape(source, Infinity);
5638
+ const view = new DataView(source.buffer, source.byteOffset, source.byteLength);
5639
+ let hasData = false, dataClosed = false;
5640
+ for (let offset = 33; offset < source.length;) {
5641
+ const { length, end, type } = pngChunk(source, view, offset);
5642
+ if (type === "IEND") {
5643
+ if (length === 0 && hasData && end === source.length)
5644
+ return shape;
5645
+ break;
5646
+ }
5647
+ if (type === "IDAT") {
5648
+ if (dataClosed)
5649
+ throw new TypeError("PNG IDAT chunks must be consecutive.");
5650
+ hasData = true;
5651
+ }
5652
+ else {
5653
+ checkAncillaryChunk(type);
5654
+ dataClosed ||= hasData;
5655
+ }
5656
+ offset = end;
5657
+ }
5658
+ throw new TypeError("PNG requires a final empty IEND after IDAT.");
5659
+ }
5598
5660
  /** Verify the complete source and critical chunk order before any decompressed image allocation. */
5599
5661
  async function pngHeader(source, shape, signal) {
5600
5662
  const view = new DataView(source.buffer, source.byteOffset, source.byteLength);
5601
5663
  let firstData = 0, dataEnd = 0, lastDataByte = -1, dataClosed = false;
5602
5664
  for (let offset = 8; offset < source.length;) {
5603
5665
  checkAbort(signal);
5604
- if (offset + 12 > source.length)
5605
- throw new TypeError("Truncated PNG chunk.");
5606
- const length = view.getUint32(offset), end = offset + 12 + length;
5607
- if (length > 0x7fffffff || end > source.length)
5608
- throw new TypeError("Truncated or oversized PNG chunk.");
5609
- const type = String.fromCharCode(...source.subarray(offset + 4, offset + 8));
5610
- if (!/^[A-Za-z]{2}[A-Z][A-Za-z]$/.test(type))
5611
- throw new TypeError("Invalid PNG chunk type.");
5666
+ const { length, end, type } = pngChunk(source, view, offset);
5612
5667
  const crc = new Crc32();
5613
5668
  for (let p = offset + 4; p < end - 4; p += 65536) {
5614
5669
  crc.update(source.subarray(p, Math.min(end - 4, p + 65536)));
@@ -5640,17 +5695,14 @@ async function pngHeader(source, shape, signal) {
5640
5695
  throw new TypeError("PNG requires a final empty IEND after IDAT.");
5641
5696
  return { ...shape, firstData, dataEnd, lastDataByte };
5642
5697
  }
5643
- if (unsupportedChunks.has(type))
5644
- throw new NotSupportedError("PNG chunk " + type + "; normalize color, orientation, transparency or animation first");
5645
- if ((source[offset + 4] & 32) === 0)
5646
- throw new NotSupportedError("Required PNG chunk " + type);
5698
+ checkAncillaryChunk(type);
5647
5699
  }
5648
5700
  offset = end;
5649
5701
  }
5650
5702
  throw new TypeError("PNG requires a complete final IEND chunk.");
5651
5703
  }
5652
5704
  /** Check source metadata synchronously, before capturing source bytes or allocating any image plane. */
5653
- function pngShape(source, maxPixels) {
5705
+ function pngShape(source, maxPixels, maxWorkingBytes) {
5654
5706
  if (source.length < 33 || signature.some((value, index) => source[index] !== value))
5655
5707
  throw new TypeError("Invalid PNG signature or truncated IHDR.");
5656
5708
  const view = new DataView(source.buffer, source.byteOffset, source.byteLength);
@@ -5670,6 +5722,9 @@ function pngShape(source, maxPixels) {
5670
5722
  const components = source[25] === 6 ? 4 : 3;
5671
5723
  if (!Number.isSafeInteger((width * components + 1) * height) || (width * components + 1) * height > 0x7fffffff)
5672
5724
  throw new OfficeIMOError("RESOURCE_LIMIT", "PNG filtered data exceeds the supported decoded byte length.");
5725
+ const workingBytes = source.length + width * height * components + (components === 4 ? width * 8 : 0);
5726
+ if (maxWorkingBytes !== undefined && workingBytes > maxWorkingBytes)
5727
+ throw new OfficeIMOError("RESOURCE_LIMIT", "maxImageWorkingBytes exceeded by PNG source, image planes and scanlines.");
5673
5728
  return { width, height, components };
5674
5729
  }
5675
5730
  function paeth(left, up, upperLeft) {
@@ -5677,7 +5732,7 @@ function paeth(left, up, upperLeft) {
5677
5732
  const a = Math.abs(prediction - left), b = Math.abs(prediction - up), c = Math.abs(prediction - upperLeft);
5678
5733
  return a <= b && a <= c ? left : b <= c ? up : upperLeft;
5679
5734
  }
5680
- const _exports = Object.freeze({ pngPixels: pngPixels });
5735
+ const _exports = Object.freeze({ pngPixels: pngPixels, pngEmbeddableSize: pngEmbeddableSize, pngShape: pngShape });
5681
5736
  return _exports;
5682
5737
  })();
5683
5738
 
@@ -5686,54 +5741,83 @@ const { NotSupportedError, OfficeIMOError } = _m4;
5686
5741
 
5687
5742
  const { checkAbort, pause, taskYieldDue } = _m3;
5688
5743
 
5689
- const { pngPixels } = _m47;
5744
+ const { pngPixels, pngShape } = _m47;
5690
5745
 
5691
5746
  /** Shared document image resources; source objects are captured on first consumption. */
5692
5747
  class PdfDocumentImages {
5693
5748
  objects;
5694
5749
  settings;
5695
5750
  images = new Map();
5751
+ snapshots = new WeakMap();
5696
5752
  bytes = 0;
5753
+ pendingBytes = 0;
5697
5754
  constructor(objects, settings) {
5698
5755
  this.objects = objects;
5699
5756
  this.settings = settings;
5700
5757
  }
5701
- async prepare(image) {
5702
- const existing = this.images.get(image);
5703
- if (existing)
5704
- return existing;
5758
+ /** Own a drawing image before preparing earlier elements can yield to the caller. */
5759
+ snapshot(image) {
5760
+ if (this.images.has(image) || this.snapshots.has(image))
5761
+ return;
5762
+ const captured = this.capture(image);
5763
+ this.snapshots.set(image, captured);
5764
+ this.pendingBytes += captured.data.length;
5765
+ }
5766
+ capture(image) {
5705
5767
  const { limits, options } = this.settings;
5768
+ checkAbort(options.signal);
5706
5769
  if (!image || typeof image !== "object")
5707
5770
  throw new TypeError("PDF images require a byte array.");
5708
- const data = image.data, format = image.format;
5771
+ const format = image.format;
5772
+ // Dimension getters may change a resizable backing buffer. Read them before measuring the byte view.
5773
+ const raw = format === "rgb" || format === "rgba" ? image : undefined;
5774
+ const widthValue = raw?.width, heightValue = raw?.height;
5775
+ const data = image.data;
5709
5776
  if (!(data instanceof Uint8Array))
5710
5777
  throw new TypeError("PDF images require a byte array.");
5711
5778
  const byteLength = data.length;
5712
- if (this.bytes + byteLength > limits.maxImageBytes)
5779
+ if (this.bytes + this.pendingBytes + byteLength > limits.maxImageBytes)
5713
5780
  throw new OfficeIMOError("RESOURCE_LIMIT", "maxImageBytes exceeded.");
5714
- let width, height, components, decoded, decodedAlpha;
5715
5781
  const maximumWorkingBytes = limits.maxImageWorkingBytes;
5716
- if (format === "png")
5717
- ({ width, height, components, data: decoded, alpha: decodedAlpha } = await pngPixels(data, limits.maxImagePixels, options.signal, maximumWorkingBytes));
5718
- else if (format === "jpeg")
5719
- ({ width, height, components } = jpegSize(data));
5782
+ if (format === "png") {
5783
+ const shape = pngShape(data, limits.maxImagePixels, maximumWorkingBytes);
5784
+ return { format, shape, data: new Uint8Array(data) };
5785
+ }
5786
+ let shape;
5787
+ if (format === "jpeg")
5788
+ shape = jpegSize(data);
5720
5789
  else if (format === "rgb" || format === "rgba") {
5721
- ({ width, height } = image);
5722
- components = format === "rgba" ? 4 : 3;
5790
+ shape = { width: widthValue, height: heightValue, components: format === "rgba" ? 4 : 3 };
5723
5791
  }
5724
5792
  else
5725
5793
  throw new NotSupportedError("PDF images support unprofiled PNG/JPEG or decoded RGB/RGBA pixels.");
5794
+ const { width, height, components } = shape;
5726
5795
  if (!Number.isSafeInteger(width) || !Number.isSafeInteger(height) || width < 1 || height < 1 ||
5727
5796
  !Number.isSafeInteger(width * height) || width * height > limits.maxImagePixels)
5728
5797
  throw new OfficeIMOError("RESOURCE_LIMIT", "Image dimensions must be positive integers within maxImagePixels.");
5729
- if ((format === "rgb" || format === "rgba") && byteLength !== width * height * components)
5798
+ if (format !== "jpeg" && byteLength !== width * height * components)
5730
5799
  throw new RangeError("Raw image bytes must match width × height × channels exactly.");
5731
- if (format !== "png" && maximumWorkingBytes !== undefined && byteLength + (components === 4 ? width * height : 0) > maximumWorkingBytes)
5800
+ if (maximumWorkingBytes !== undefined && byteLength + (components === 4 ? width * height : 0) > maximumWorkingBytes)
5732
5801
  throw new OfficeIMOError("RESOURCE_LIMIT", "maxImageWorkingBytes exceeded by image snapshot and alpha plane.");
5802
+ return { format, shape, data: new Uint8Array(data) };
5803
+ }
5804
+ async prepare(image) {
5805
+ const existing = this.images.get(image);
5806
+ if (existing)
5807
+ return existing;
5808
+ const { options } = this.settings, snapshot = this.snapshots.get(image);
5809
+ const source = snapshot ?? this.capture(image);
5810
+ if (snapshot) {
5811
+ this.snapshots.delete(image);
5812
+ this.pendingBytes -= source.data.length;
5813
+ }
5814
+ this.bytes += source.data.length;
5815
+ const { format } = source;
5816
+ const decoded = format === "png" ? await pngPixels(source.data, source.shape, options.signal) : undefined;
5817
+ const { width, height, components } = decoded ?? source.shape;
5733
5818
  checkAbort(options.signal);
5734
5819
  const id = this.objects.reserve(), name = "Image" + (this.images.size + 1);
5735
- this.bytes += byteLength;
5736
- const captured = decoded ?? new Uint8Array(data);
5820
+ const captured = decoded?.data ?? source.data, decodedAlpha = decoded?.alpha;
5737
5821
  let pixels = captured, alpha = decodedAlpha, mask;
5738
5822
  if (components === 4) {
5739
5823
  // Compact the owned RGBA snapshot in place. Forward writes never overwrite unread channels.
@@ -5755,20 +5839,22 @@ class PdfDocumentImages {
5755
5839
  mask = this.objects.reserve();
5756
5840
  await this.objects.stream(mask, alpha, "/Type /XObject /Subtype /Image /Width " + width + " /Height " + height + " /ColorSpace /DeviceGray /BitsPerComponent 8", options.compression !== false, true);
5757
5841
  }
5842
+ const jpegFilter = format === "jpeg" ? " /Filter /DCTDecode" +
5843
+ (source.shape.colorTransform === 0 ? " /DecodeParms << /ColorTransform 0 >>" : "") : "";
5758
5844
  const dictionary = "/Type /XObject /Subtype /Image /Width " + width + " /Height " + height + " /ColorSpace /" +
5759
5845
  (components === 1 ? "DeviceGray" : "DeviceRGB") + " /BitsPerComponent 8" + (mask ? " /SMask " + mask + " 0 R" : "") +
5760
- (format === "jpeg" ? " /Filter /DCTDecode" : "");
5846
+ jpegFilter;
5761
5847
  await this.objects.stream(id, pixels, dictionary, format === "jpeg" ? false : options.compression !== false, true);
5762
5848
  const resource = { name, id, width, height };
5763
5849
  this.images.set(image, resource);
5764
5850
  return resource;
5765
5851
  }
5766
5852
  }
5767
- /** Inspect bounded JPEG headers; JPEG entropy decoding remains the independent reader's job. */
5853
+ /** @internal Inspect bounded JPEG headers; JPEG entropy decoding remains the independent reader's job. */
5768
5854
  function jpegSize(bytes) {
5769
5855
  if (bytes.length < 4 || bytes[0] !== 255 || bytes[1] !== 216 || bytes[bytes.length - 2] !== 255 || bytes[bytes.length - 1] !== 217)
5770
5856
  throw new TypeError("JPEG images need complete SOI/EOI markers.");
5771
- let result;
5857
+ let result, rgb = false, adobe = false;
5772
5858
  for (let p = 2; p < bytes.length;) {
5773
5859
  if (bytes[p++] !== 255)
5774
5860
  throw new TypeError("Invalid JPEG marker.");
@@ -5778,7 +5864,8 @@ function jpegSize(bytes) {
5778
5864
  if (marker === 218) {
5779
5865
  if (!result)
5780
5866
  throw new TypeError("JPEG scan precedes its frame header.");
5781
- return result;
5867
+ // PDF decoders otherwise assume a color transform for three-component JPEGs.
5868
+ return rgb && !adobe ? { ...result, colorTransform: 0 } : result;
5782
5869
  }
5783
5870
  if (marker === 217)
5784
5871
  break;
@@ -5787,6 +5874,8 @@ function jpegSize(bytes) {
5787
5874
  const length = bytes[p] * 256 + bytes[p + 1], end = p + length;
5788
5875
  if (length < 2 || end > bytes.length)
5789
5876
  throw new TypeError("Truncated JPEG segment.");
5877
+ if (marker === 238 && length >= 14 && String.fromCharCode(...bytes.subarray(p + 2, p + 7)) === "Adobe")
5878
+ adobe = true;
5790
5879
  if (marker === 226 && length >= 14 && String.fromCharCode(...bytes.subarray(p + 2, p + 14)) === "ICC_PROFILE\0")
5791
5880
  throw new NotSupportedError("Normalize ICC-profiled JPEG colors before PDF embedding.");
5792
5881
  if (marker === 225 && length >= 8 && String.fromCharCode(...bytes.subarray(p + 2, p + 8)) === "Exif\0\0")
@@ -5799,7 +5888,8 @@ function jpegSize(bytes) {
5799
5888
  throw new NotSupportedError("PDF JPEG images require grayscale or RGB components; CMYK is unsupported.");
5800
5889
  if (components === 3) {
5801
5890
  const ids = [bytes[p + 8], bytes[p + 11], bytes[p + 14]].join(",");
5802
- if (ids !== "1,2,3" && ids !== "82,71,66")
5891
+ rgb = ids === "82,71,66";
5892
+ if (ids !== "1,2,3" && !rgb)
5803
5893
  throw new NotSupportedError("Unsupported JPEG component color layout.");
5804
5894
  }
5805
5895
  if (result)
@@ -5810,7 +5900,7 @@ function jpegSize(bytes) {
5810
5900
  }
5811
5901
  throw new TypeError("JPEG image has no complete frame and scan.");
5812
5902
  }
5813
- const _exports = Object.freeze({ PdfDocumentImages: PdfDocumentImages });
5903
+ const _exports = Object.freeze({ PdfDocumentImages: PdfDocumentImages, jpegSize: jpegSize });
5814
5904
  return _exports;
5815
5905
  })();
5816
5906
 
@@ -5905,7 +5995,7 @@ const { NotSupportedError, OfficeIMOError } = _m4;
5905
5995
 
5906
5996
  const { checkAbort, pause, taskYieldDue } = _m3;
5907
5997
 
5908
- const { color, positive } = _m11;
5998
+ const { color, pdfDrawingMaxDepth, positive } = _m11;
5909
5999
 
5910
6000
  const { pdfNumber: n } = _m19;
5911
6001
 
@@ -5927,22 +6017,50 @@ function clipRectangle(value) {
5927
6017
  const clip = record(value, ["x", "y", "width", "height"], "drawing clip");
5928
6018
  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) };
5929
6019
  }
6020
+ /** A PDF dash array: 1 through 16 nonnegative lengths, not all zero, and a finite phase. */
6021
+ function dashPattern(value, offset) {
6022
+ if (value === undefined) {
6023
+ if (offset !== undefined)
6024
+ throw new TypeError("Drawing dashOffset requires dash.");
6025
+ return "";
6026
+ }
6027
+ if (!Array.isArray(value) || !value.length || value.length > 16)
6028
+ throw new TypeError("Drawing dash must list 1 through 16 nonnegative lengths with at least one positive length.");
6029
+ const lengths = Array.from(value, item => {
6030
+ if (typeof item !== "number" || !Number.isFinite(item) || item < 0 || item > 14400)
6031
+ throw new TypeError("Drawing dash lengths must be from 0 through 14,400 points.");
6032
+ return n(item);
6033
+ });
6034
+ if (lengths.every(length => length === "0"))
6035
+ throw new TypeError("Drawing dash needs a positive length after PDF rounding.");
6036
+ let phase = coordinate(offset ?? 0);
6037
+ if (phase < 0) {
6038
+ // Work in serialized thousandths of a point. Odd arrays repeat twice before the paint state repeats.
6039
+ const period = lengths.reduce((sum, length) => sum + Math.round(Number(length) * 1000), 0) * (lengths.length % 2 ? 2 : 1);
6040
+ phase = ((Math.round(phase * 1000) % period + period) % period) / 1000;
6041
+ }
6042
+ return "[" + lengths.join(" ") + "] " + n(phase) + " d\n";
6043
+ }
5930
6044
  async function cooperate(settings) {
5931
6045
  if (taskYieldDue())
5932
6046
  await pause();
5933
6047
  checkAbort(settings.options.signal);
5934
6048
  }
5935
6049
  /** Take ownership of one bounded schema before any cooperative or font work can run caller code. */
5936
- function captureDrawing(drawing, settings, used) {
6050
+ function captureDrawing(drawing, settings, used, images) {
5937
6051
  checkAbort(settings.options.signal);
5938
- const root = record(drawing, ["version", "width", "height", "elements"], "drawing");
5939
- if (root.version !== 1)
5940
- throw new NotSupportedError("Only portable drawing version 1 is supported.");
6052
+ const root = record(drawing, ["version", "width", "height", "elements", "standardFonts"], "drawing");
6053
+ const standardFonts = root.standardFonts;
6054
+ if (standardFonts !== undefined && typeof standardFonts !== "boolean")
6055
+ throw new TypeError("Drawing standardFonts must be boolean.");
6056
+ const version = root.version;
6057
+ if (version !== 1 && version !== 2)
6058
+ throw new NotSupportedError("Only portable drawing versions 1 and 2 are supported.");
5941
6059
  const width = positive(root.width, "Drawing width"), height = positive(root.height, "Drawing height");
5942
6060
  let commands = used.commands, elements = used.elements;
5943
6061
  const ancestors = new Set();
5944
6062
  function path(value) {
5945
- record(value, ["kind", "commands", "fill", "stroke", "strokeWidth", "fillRule", "lineCap", "lineJoin"], "drawing path");
6063
+ record(value, ["kind", "commands", "fill", "stroke", "strokeWidth", "fillRule", "lineCap", "lineJoin", "miterLimit", "dash", "dashOffset"], "drawing path");
5946
6064
  const source = value.commands;
5947
6065
  if (!Array.isArray(source))
5948
6066
  throw new TypeError("Drawing path commands must be an array.");
@@ -5964,6 +6082,10 @@ function captureDrawing(drawing, settings, used) {
5964
6082
  throw new TypeError("Invalid drawing lineCap.");
5965
6083
  if (lineJoin !== undefined && !["miter", "round", "bevel"].includes(lineJoin))
5966
6084
  throw new TypeError("Invalid drawing lineJoin.");
6085
+ const miterLimit = positive(value.miterLimit ?? 10, "Drawing miter limit", 1000000);
6086
+ if (miterLimit < 1)
6087
+ throw new RangeError("Drawing miter limit must be at least 1.");
6088
+ const dash = dashPattern(value.dash, value.dashOffset);
5967
6089
  for (let i = 0; i < snapshot.length; i++) {
5968
6090
  const c = snapshot[i];
5969
6091
  if (!c || typeof c !== "object")
@@ -5996,11 +6118,12 @@ function captureDrawing(drawing, settings, used) {
5996
6118
  if (!started)
5997
6119
  throw new TypeError("A drawing path needs at least one command.");
5998
6120
  return { kind: "path", commands: copied, style: (fill === undefined ? "" : fill + " rg\n") + (stroke === undefined ? "" : stroke + " RG\n" + n(strokeWidth) + " w\n") +
5999
- String(["butt", "round", "square"].indexOf(lineCap ?? "butt")) + " J\n" + String(["miter", "round", "bevel"].indexOf(lineJoin ?? "miter")) + " j\n10 M\n",
6121
+ String(["butt", "round", "square"].indexOf(lineCap ?? "butt")) + " J\n" + String(["miter", "round", "bevel"].indexOf(lineJoin ?? "miter")) +
6122
+ " j\n" + n(miterLimit) + " M\n" + dash,
6000
6123
  paint: (fill !== undefined && stroke !== undefined ? "B" : fill !== undefined ? "f" : "S") + (fill !== undefined && fillRule === "evenodd" ? "*" : "") + "\n" };
6001
6124
  }
6002
6125
  function text(value) {
6003
- record(value, ["kind", "text", "x", "y", "font", "fontSize", "color"], "drawing text");
6126
+ record(value, ["kind", "text", "x", "y", "font", "fontSize", "color", "anchor", "rotation"], "drawing text");
6004
6127
  const snapshot = value.text, slot = value.font;
6005
6128
  if (typeof snapshot !== "string")
6006
6129
  throw new TypeError("Drawing text must be a string.");
@@ -6011,14 +6134,33 @@ function captureDrawing(drawing, settings, used) {
6011
6134
  if (!["regular", "bold", "italic", "boldItalic"].includes(slot))
6012
6135
  throw new TypeError("Invalid drawing font slot.");
6013
6136
  const x = coordinate(value.x), y = coordinate(value.y), size = positive(value.fontSize, "Drawing font size"), foreground = color(value.color);
6137
+ const anchor = value.anchor, rotation = value.rotation ?? 0;
6138
+ if (anchor !== undefined && !["start", "middle", "end"].includes(anchor))
6139
+ throw new TypeError("Invalid drawing text anchor.");
6140
+ if (typeof rotation !== "number" || !Number.isFinite(rotation) || Math.abs(rotation) > 360)
6141
+ throw new RangeError("Drawing text rotation must be finite degrees within -360 through 360.");
6014
6142
  settings.budget.cell(snapshot);
6015
- return { kind: "text", text: snapshot, x, y, size, color: foreground, font: slot };
6143
+ // Quarter turns stay exact so upright and vertical axis labels keep integral matrices.
6144
+ const turn = rotation % 90 === 0 ? (((rotation / 90) % 4) + 4) % 4 : -1, radians = rotation * Math.PI / 180;
6145
+ const cos = turn < 0 ? Math.cos(radians) : [1, 0, -1, 0][turn], sin = turn < 0 ? Math.sin(radians) : [0, 1, 0, -1][turn];
6146
+ return { kind: "text", text: snapshot, x, y, size, color: foreground, font: slot, anchor: anchor === "middle" ? .5 : anchor === "end" ? 1 : 0, cos, sin };
6147
+ }
6148
+ function image(value) {
6149
+ record(value, ["kind", "image", "x", "y", "width", "height", "opacity"], "drawing image");
6150
+ const x = coordinate(value.x), y = coordinate(value.y), suppliedOpacity = value.opacity;
6151
+ const opacity = suppliedOpacity === undefined ? 1 : suppliedOpacity;
6152
+ const width = positive(value.width, "Drawing image width", 1000000), height = positive(value.height, "Drawing image height", 1000000);
6153
+ if (typeof opacity !== "number" || !(opacity >= 0 && opacity <= 1))
6154
+ throw new RangeError("Drawing image opacity must be from 0 through 1.");
6155
+ const source = value.image;
6156
+ images.snapshot(source);
6157
+ return { kind: "image", image: source, x, y, width, height, opacity };
6016
6158
  }
6017
6159
  function children(input, depth) {
6018
6160
  if (!Array.isArray(input))
6019
6161
  throw new TypeError("Drawing elements must be an array.");
6020
- if (depth > 32 && input.length)
6021
- throw new RangeError("Drawing groups support at most 32 element levels.");
6162
+ if (depth > pdfDrawingMaxDepth && input.length)
6163
+ throw new RangeError("Drawing groups support at most " + pdfDrawingMaxDepth + " element levels.");
6022
6164
  if (elements + input.length > settings.limits.maxDrawingElements)
6023
6165
  throw new OfficeIMOError("RESOURCE_LIMIT", "maxDrawingElements exceeded.");
6024
6166
  checkAbort(settings.options.signal);
@@ -6036,6 +6178,8 @@ function captureDrawing(drawing, settings, used) {
6036
6178
  output.push(path(value));
6037
6179
  else if (kind === "text")
6038
6180
  output.push(text(value));
6181
+ else if (kind === "image" && version === 2)
6182
+ output.push(image(value));
6039
6183
  else if (kind === "group") {
6040
6184
  record(value, ["kind", "clip", "elements"], "drawing group");
6041
6185
  const clipValue = value.clip, clip = clipValue === undefined ? undefined : clipRectangle(clipValue);
@@ -6052,29 +6196,35 @@ function captureDrawing(drawing, settings, used) {
6052
6196
  }
6053
6197
  const plan = children(root.elements, 1);
6054
6198
  checkAbort(settings.options.signal);
6055
- return { width, height, plan, commands: commands - used.commands, elements: elements - used.elements };
6199
+ return { width, height, plan, commands: commands - used.commands, elements: elements - used.elements, standardFonts: standardFonts === true };
6056
6200
  }
6057
6201
  /** Preflight and paint owned records. The existing font owner retains glyph maps and subsets. */
6058
- async function prepareDrawing(drawing, settings, fonts, used) {
6202
+ async function prepareDrawing(drawing, settings, fonts, used, resources) {
6059
6203
  // A drawing's bounded capture is synchronous; yielding here would leave later caller records borrowed.
6060
- const captured = captureDrawing(drawing, settings, used), drawingFonts = new Map();
6204
+ const { images } = resources, captured = captureDrawing(drawing, settings, used, images), drawingFonts = new Map();
6061
6205
  function fontFor(slot) {
6062
6206
  const existing = drawingFonts.get(slot);
6063
6207
  if (existing)
6064
6208
  return existing;
6065
- const font = fonts.select(slot === "bold" || slot === "boldItalic", slot === "italic" || slot === "boldItalic");
6066
- if (!font.program || font.syntheticBold || font.syntheticItalic)
6209
+ const font = fonts.select(slot === "bold" || slot === "boldItalic", slot === "italic" || slot === "boldItalic", undefined, captured.standardFonts);
6210
+ if (font.syntheticBold || font.syntheticItalic || !font.program && !captured.standardFonts)
6067
6211
  throw new NotSupportedError("Drawing text without an exact embedded font face at fonts." + slot);
6068
6212
  drawingFonts.set(slot, font);
6069
6213
  return font;
6070
6214
  }
6071
6215
  // The work budget belongs to the drawing, including short runs in separate sibling groups.
6072
6216
  let preflightCharacters = 0, preflightElements = 0;
6217
+ const imageNames = new Map();
6073
6218
  async function preflight(nodes) {
6074
6219
  for (let i = 0; i < nodes.length; i++) {
6075
6220
  const node = nodes[i];
6076
6221
  if (node.kind === "group")
6077
6222
  await preflight(node.children);
6223
+ else if (node.kind === "image" && !imageNames.has(node.image)) {
6224
+ const resource = await images.prepare(node.image);
6225
+ resources.registerImage(resource.name, resource.id);
6226
+ imageNames.set(node.image, resource.name);
6227
+ }
6078
6228
  else if (node.kind === "text") {
6079
6229
  const font = fontFor(node.font);
6080
6230
  for (const character of node.text) {
@@ -6117,9 +6267,23 @@ async function prepareDrawing(drawing, settings, fonts, used) {
6117
6267
  }
6118
6268
  add(node.paint);
6119
6269
  }
6270
+ else if (node.kind === "image") {
6271
+ // Image space is a unit square with a bottom-left origin; the drawing's y axis points down.
6272
+ if (node.opacity < 1)
6273
+ add("/" + resources.opacity(node.opacity) + " gs\n");
6274
+ add([node.width, 0, 0, -node.height, node.x, node.y + node.height].map(n).join(" ") + " cm /" + imageNames.get(node.image) + " Do\n");
6275
+ }
6120
6276
  else {
6121
6277
  const font = fontFor(node.font);
6122
- add(node.color + " rg\nBT /" + font.name + " " + n(node.size) + " Tf 0 Tr 1 0 0 -1 " + n(node.x) + " " + n(node.y) + " Tm <");
6278
+ let shift = 0;
6279
+ if (node.anchor) {
6280
+ for (const character of node.text)
6281
+ shift += font.width(character.codePointAt(0));
6282
+ shift *= node.size / 1000 * node.anchor;
6283
+ }
6284
+ // Text space is upright in the drawing's downward y axis; rotation turns the baseline clockwise about its anchor.
6285
+ add(node.color + " rg\nBT /" + font.name + " " + n(node.size) + " Tf 0 Tr " +
6286
+ [node.cos, node.sin, node.sin, -node.cos, node.x - shift * node.cos, node.y - shift * node.sin].map(n).join(" ") + " Tm <");
6123
6287
  let chunk = "";
6124
6288
  for (const character of node.text) {
6125
6289
  chunk += character;
@@ -6842,7 +7006,9 @@ async function writePdfDocumentTo(blocks, destination, configuration = {}) {
6842
7006
  const inputDrawing = block.drawing, capturedCaption = snapshotCaption(block.caption), alternative = graphicAlternative(block, pages.settings), alignment = graphicAlignment(block.alignment);
6843
7007
  if (capturedCaption && alternative === undefined)
6844
7008
  throw new TypeError("A captioned PDF graphic requires alternativeText and cannot be decorative.");
6845
- const drawing = await prepareDrawing(inputDrawing, pages.settings, fonts, { commands, elements: drawingElements }), caption = await prepareCaption(capturedCaption);
7009
+ const drawing = await prepareDrawing(inputDrawing, pages.settings, fonts, { commands, elements: drawingElements }, {
7010
+ images, registerImage: (name, id) => pages.registerXObject(name, id), opacity: alpha => pages.opacityState(alpha)
7011
+ }), caption = await prepareCaption(capturedCaption);
6846
7012
  commands += drawing.commands;
6847
7013
  drawingElements += drawing.elements;
6848
7014
  await flushParagraphs((caption?.height ?? 0) + pages.graphicHeight(drawing.width, drawing.height));