@wirabyte/w-pdfmaker 0.0.0-stage → 1.0.2

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 (142) hide show
  1. package/CHANGELOG.md +53 -0
  2. package/LICENSE +22 -0
  3. package/NOTICE.md +39 -0
  4. package/README.md +106 -2
  5. package/build/fonts/Roboto/Roboto-Italic.ttf +0 -0
  6. package/build/fonts/Roboto/Roboto-Medium.ttf +0 -0
  7. package/build/fonts/Roboto/Roboto-MediumItalic.ttf +0 -0
  8. package/build/fonts/Roboto/Roboto-Regular.ttf +0 -0
  9. package/build/fonts/Roboto.js +27 -0
  10. package/build/pdfmake.js +103161 -0
  11. package/build/pdfmake.js.map +1 -0
  12. package/build/pdfmake.min.js +3 -0
  13. package/build/pdfmake.min.js.map +1 -0
  14. package/build/standard-fonts/Courier.js +9 -0
  15. package/build/standard-fonts/Helvetica.js +9 -0
  16. package/build/standard-fonts/Symbol.js +9 -0
  17. package/build/standard-fonts/Times.js +9 -0
  18. package/build/standard-fonts/ZapfDingbats.js +9 -0
  19. package/build/vfs_fonts.js +6 -0
  20. package/build-vfs.js +44 -0
  21. package/fonts/Roboto/Roboto-Italic.ttf +0 -0
  22. package/fonts/Roboto/Roboto-Medium.ttf +0 -0
  23. package/fonts/Roboto/Roboto-MediumItalic.ttf +0 -0
  24. package/fonts/Roboto/Roboto-Regular.ttf +0 -0
  25. package/fonts/Roboto.js +8 -0
  26. package/fonts/THSarabunIT9/LICENSE.txt +7 -0
  27. package/fonts/THSarabunIT9/THSarabunIT9-Bold.ttf +0 -0
  28. package/fonts/THSarabunIT9/THSarabunIT9-BoldItalic.ttf +0 -0
  29. package/fonts/THSarabunIT9/THSarabunIT9-Italic.ttf +0 -0
  30. package/fonts/THSarabunIT9/THSarabunIT9.ttf +0 -0
  31. package/fonts/THSarabunNew/COPYING.GPLv2 +339 -0
  32. package/fonts/THSarabunNew/LICENSE.txt +13 -0
  33. package/fonts/THSarabunNew/THSarabunNew-Bold.ttf +0 -0
  34. package/fonts/THSarabunNew/THSarabunNew-BoldItalic.ttf +0 -0
  35. package/fonts/THSarabunNew/THSarabunNew-Italic.ttf +0 -0
  36. package/fonts/THSarabunNew/THSarabunNew.ttf +0 -0
  37. package/index.d.ts +167 -0
  38. package/interfaces.d.ts +2779 -0
  39. package/js/DocMeasure.js +695 -0
  40. package/js/DocPreprocessor.js +263 -0
  41. package/js/DocumentContext.js +563 -0
  42. package/js/ElementWriter.js +488 -0
  43. package/js/LayoutBuilder.js +1525 -0
  44. package/js/Line.js +105 -0
  45. package/js/OutputDocument.js +73 -0
  46. package/js/OutputDocumentServer.js +34 -0
  47. package/js/PDFDocument.js +322 -0
  48. package/js/PageElementWriter.js +302 -0
  49. package/js/PageSize.js +74 -0
  50. package/js/Printer.js +275 -0
  51. package/js/Renderer.js +439 -0
  52. package/js/SVGMeasure.js +94 -0
  53. package/js/StyleContextStack.js +191 -0
  54. package/js/TableProcessor.js +658 -0
  55. package/js/TextBreaker.js +164 -0
  56. package/js/TextDecorator.js +164 -0
  57. package/js/TextInlines.js +212 -0
  58. package/js/URLResolver.js +122 -0
  59. package/js/base.js +125 -0
  60. package/js/browser-extensions/OutputDocumentBrowser.js +82 -0
  61. package/js/browser-extensions/fonts/Roboto.js +38 -0
  62. package/js/browser-extensions/fonts/thai.js +28 -0
  63. package/js/browser-extensions/index.js +88 -0
  64. package/js/browser-extensions/pageUrls.js +79 -0
  65. package/js/browser-extensions/pdfMake.js +3 -0
  66. package/js/browser-extensions/standard-fonts/Courier.js +20 -0
  67. package/js/browser-extensions/standard-fonts/Helvetica.js +20 -0
  68. package/js/browser-extensions/standard-fonts/Symbol.js +17 -0
  69. package/js/browser-extensions/standard-fonts/Times.js +20 -0
  70. package/js/browser-extensions/standard-fonts/ZapfDingbats.js +17 -0
  71. package/js/browser-extensions/virtual-fs-cjs.js +3 -0
  72. package/js/columnCalculator.js +159 -0
  73. package/js/helpers/node.js +122 -0
  74. package/js/helpers/tools.js +46 -0
  75. package/js/helpers/variableType.js +59 -0
  76. package/js/imageFallback.js +23 -0
  77. package/js/index.js +45 -0
  78. package/js/mergeStamp.js +194 -0
  79. package/js/pageNumbering.js +48 -0
  80. package/js/qrEnc.js +721 -0
  81. package/js/standardPageSizes.js +56 -0
  82. package/js/tableLayouts.js +98 -0
  83. package/js/thai.js +201 -0
  84. package/js/virtual-fs.js +82 -0
  85. package/package.json +93 -4
  86. package/skills/w-pdfmaker/SKILL.md +171 -0
  87. package/skills/w-pdfmaker/references/browser.md +36 -0
  88. package/skills/w-pdfmaker/references/document-definition.md +241 -0
  89. package/skills/w-pdfmaker/references/images.md +90 -0
  90. package/skills/w-pdfmaker/references/merge-stamp.md +94 -0
  91. package/skills/w-pdfmaker/references/thai.md +67 -0
  92. package/src/DocMeasure.js +780 -0
  93. package/src/DocPreprocessor.js +293 -0
  94. package/src/DocumentContext.js +605 -0
  95. package/src/ElementWriter.js +550 -0
  96. package/src/LayoutBuilder.js +1689 -0
  97. package/src/Line.js +114 -0
  98. package/src/OutputDocument.js +75 -0
  99. package/src/OutputDocumentServer.js +38 -0
  100. package/src/PDFDocument.js +352 -0
  101. package/src/PageElementWriter.js +343 -0
  102. package/src/PageSize.js +53 -0
  103. package/src/Printer.js +289 -0
  104. package/src/Renderer.js +468 -0
  105. package/src/SVGMeasure.js +109 -0
  106. package/src/StyleContextStack.js +208 -0
  107. package/src/TableProcessor.js +719 -0
  108. package/src/TextBreaker.js +166 -0
  109. package/src/TextDecorator.js +191 -0
  110. package/src/TextInlines.js +229 -0
  111. package/src/URLResolver.js +122 -0
  112. package/src/base.js +143 -0
  113. package/src/browser-extensions/OutputDocumentBrowser.js +80 -0
  114. package/src/browser-extensions/fonts/Roboto.js +27 -0
  115. package/src/browser-extensions/fonts/thai.js +23 -0
  116. package/src/browser-extensions/index.js +91 -0
  117. package/src/browser-extensions/pageUrls.js +67 -0
  118. package/src/browser-extensions/pdfMake.js +1 -0
  119. package/src/browser-extensions/standard-fonts/Courier.js +25 -0
  120. package/src/browser-extensions/standard-fonts/Helvetica.js +25 -0
  121. package/src/browser-extensions/standard-fonts/Symbol.js +17 -0
  122. package/src/browser-extensions/standard-fonts/Times.js +25 -0
  123. package/src/browser-extensions/standard-fonts/ZapfDingbats.js +17 -0
  124. package/src/browser-extensions/virtual-fs-cjs.js +1 -0
  125. package/src/columnCalculator.js +160 -0
  126. package/src/helpers/node.js +134 -0
  127. package/src/helpers/tools.js +44 -0
  128. package/src/helpers/variableType.js +50 -0
  129. package/src/imageFallback.js +18 -0
  130. package/src/index.js +45 -0
  131. package/src/mergeStamp.js +132 -0
  132. package/src/pageNumbering.js +45 -0
  133. package/src/qrEnc.js +796 -0
  134. package/src/standardPageSizes.js +52 -0
  135. package/src/tableLayouts.js +100 -0
  136. package/src/thai.js +170 -0
  137. package/src/virtual-fs.js +92 -0
  138. package/standard-fonts/Courier.js +8 -0
  139. package/standard-fonts/Helvetica.js +8 -0
  140. package/standard-fonts/Symbol.js +5 -0
  141. package/standard-fonts/Times.js +8 -0
  142. package/standard-fonts/ZapfDingbats.js +5 -0
@@ -0,0 +1,1525 @@
1
+ "use strict";
2
+
3
+ exports.__esModule = true;
4
+ exports.default = void 0;
5
+ var _DocPreprocessor = _interopRequireDefault(require("./DocPreprocessor"));
6
+ var _DocMeasure = _interopRequireDefault(require("./DocMeasure"));
7
+ var _DocumentContext = _interopRequireDefault(require("./DocumentContext"));
8
+ var _PageElementWriter = _interopRequireDefault(require("./PageElementWriter"));
9
+ var _columnCalculator = _interopRequireDefault(require("./columnCalculator"));
10
+ var _TableProcessor = _interopRequireDefault(require("./TableProcessor"));
11
+ var _Line = _interopRequireDefault(require("./Line"));
12
+ var _variableType = require("./helpers/variableType");
13
+ var _node = require("./helpers/node");
14
+ var _tools = require("./helpers/tools");
15
+ var _TextInlines = _interopRequireDefault(require("./TextInlines"));
16
+ var _StyleContextStack = _interopRequireDefault(require("./StyleContextStack"));
17
+ var _pageNumbering = require("./pageNumbering");
18
+ function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
19
+ function addAll(target, otherArray) {
20
+ otherArray.forEach(item => {
21
+ target.push(item);
22
+ });
23
+ }
24
+
25
+ /**
26
+ * Layout engine which turns document-definition-object into a set of pages, lines, inlines
27
+ * and vectors ready to be rendered into a PDF
28
+ */
29
+ class LayoutBuilder {
30
+ /**
31
+ * @param {object} pageSize - an object defining page width and height
32
+ * @param {object} pageMargins - an object defining top, left, right and bottom margins
33
+ * @param {object} svgMeasure
34
+ * @param {string} unbreakableOverflow
35
+ */
36
+ constructor(pageSize, pageMargins, svgMeasure, unbreakableOverflow = 'allowBreak') {
37
+ this.pageSize = pageSize;
38
+ this.pageMargins = pageMargins;
39
+ this.svgMeasure = svgMeasure;
40
+ this.unbreakableOverflow = unbreakableOverflow;
41
+ this.tableLayouts = {};
42
+ this.nestedLevel = 0;
43
+ this.verticalAlignmentItemStack = [];
44
+ this.backgroundLevel = 0;
45
+ this.contentNodes = [];
46
+ this.breakableBlocks = new Set();
47
+ }
48
+ registerTableLayouts(tableLayouts) {
49
+ this.tableLayouts = (0, _tools.pack)(this.tableLayouts, tableLayouts);
50
+ }
51
+
52
+ /**
53
+ * Executes layout engine on document-definition-object and creates an array of pages
54
+ * containing positioned Blocks, Lines and inlines
55
+ *
56
+ * @param {object} docStructure document-definition-object
57
+ * @param {object} pdfDocument pdfkit document
58
+ * @param {object} styleDictionary dictionary with style definitions
59
+ * @param {object} defaultStyle default style definition
60
+ * @param {object} background
61
+ * @param {object} header
62
+ * @param {object} footer
63
+ * @param {object} watermark
64
+ * @param {object} pageBreakBeforeFct
65
+ * @returns {Array} an array of pages
66
+ */
67
+ layoutDocument(docStructure, pdfDocument, styleDictionary, defaultStyle, background, header, footer, watermark, pageBreakBeforeFct) {
68
+ function addPageBreaksIfNecessary(linearNodeList, pages) {
69
+ if (typeof pageBreakBeforeFct !== 'function') {
70
+ return false;
71
+ }
72
+ const hasRenderableContent = node => {
73
+ if (!node || node.positions.length === 0) {
74
+ return false;
75
+ }
76
+ if (node.text === '' && !node.listMarker) {
77
+ return false;
78
+ }
79
+ return true;
80
+ };
81
+ linearNodeList = linearNodeList.filter(hasRenderableContent);
82
+ const nodesByPage = [];
83
+ linearNodeList.forEach((node, index) => {
84
+ let nodeInfo = {};
85
+ ['id', 'text', 'ul', 'ol', 'table', 'image', 'qr', 'canvas', 'svg', 'columns', 'headlineLevel', 'style', 'pageBreak', 'pageOrientation', 'width', 'height'].forEach(key => {
86
+ if (node[key] !== undefined) {
87
+ nodeInfo[key] = node[key];
88
+ }
89
+ });
90
+ nodeInfo.startPosition = node.positions[0];
91
+ nodeInfo.pageNumbers = Array.from(new Set(node.positions.map(node => node.pageNumber)));
92
+ nodeInfo.pages = pages.length;
93
+ nodeInfo.stack = Array.isArray(node.stack);
94
+ node.nodeInfo = nodeInfo;
95
+ nodeInfo.pageNumbers.forEach(pageNumber => {
96
+ nodesByPage[pageNumber] = nodesByPage[pageNumber] || [];
97
+ nodesByPage[pageNumber].push({
98
+ index,
99
+ nodeInfo
100
+ });
101
+ });
102
+ });
103
+ const findFirstNodeAtOrAfter = (nodes, index) => {
104
+ let low = 0;
105
+ let high = nodes.length;
106
+ while (low < high) {
107
+ const middle = Math.floor((low + high) / 2);
108
+ if (nodes[middle].index < index) {
109
+ low = middle + 1;
110
+ } else {
111
+ high = middle;
112
+ }
113
+ }
114
+ return low;
115
+ };
116
+ const getNodeInfos = (nodes, start, end) => nodes.slice(start, end).map(entry => entry.nodeInfo);
117
+ for (let index = 0; index < linearNodeList.length; index++) {
118
+ let node = linearNodeList[index];
119
+ if (node.pageBreak !== 'before' && !node.pageBreakCalculated) {
120
+ node.pageBreakCalculated = true;
121
+ let pageNumber = node.nodeInfo.pageNumbers[0];
122
+ const nodesOnPage = nodesByPage[pageNumber] || [];
123
+ const nodeOnPageIndex = findFirstNodeAtOrAfter(nodesOnPage, index);
124
+ if (pageBreakBeforeFct(node.nodeInfo, {
125
+ getFollowingNodesOnPage: () => getNodeInfos(nodesOnPage, nodeOnPageIndex + 1),
126
+ getNodesOnNextPage: () => {
127
+ const nextPageNodes = nodesByPage[pageNumber + 1] || [];
128
+ return getNodeInfos(nextPageNodes, findFirstNodeAtOrAfter(nextPageNodes, index + 1));
129
+ },
130
+ getPreviousNodesOnPage: () => getNodeInfos(nodesOnPage, 0, nodeOnPageIndex)
131
+ })) {
132
+ node.pageBreak = 'before';
133
+ return true;
134
+ }
135
+ }
136
+ }
137
+ return false;
138
+ }
139
+ this.docPreprocessor = new _DocPreprocessor.default();
140
+ this.docMeasure = new _DocMeasure.default(pdfDocument, styleDictionary, defaultStyle, this.svgMeasure, this.tableLayouts);
141
+ function resetXYs(result) {
142
+ result.linearNodeList.forEach(node => {
143
+ node.resetXY();
144
+ });
145
+ }
146
+ this.breakableBlocks.clear();
147
+ let result;
148
+ let repeatLayout;
149
+ do {
150
+ const breakableBlockCount = this.breakableBlocks.size;
151
+ result = this.tryLayoutDocument(docStructure, pdfDocument, styleDictionary, defaultStyle, background, header, footer, watermark);
152
+ // Reuse the normal layout pass to restore consumed text and table state.
153
+ repeatLayout = this.breakableBlocks.size !== breakableBlockCount || addPageBreaksIfNecessary(result.pageBreakNodes, result.pages);
154
+ if (repeatLayout) {
155
+ resetXYs(result);
156
+ }
157
+ } while (repeatLayout);
158
+ return result.pages;
159
+ }
160
+ tryLayoutDocument(docStructure, pdfDocument, styleDictionary, defaultStyle, background, header, footer, watermark) {
161
+ const isNecessaryAddFirstPage = docStructure => {
162
+ if (docStructure.stack && docStructure.stack.length > 0 && docStructure.stack[0].section) {
163
+ return false;
164
+ } else if (docStructure.section) {
165
+ return false;
166
+ }
167
+ return true;
168
+ };
169
+ this.linearNodeList = [];
170
+ this.contentNodes = [];
171
+ docStructure = this.docPreprocessor.preprocessDocument(docStructure);
172
+ docStructure = this.docMeasure.measureDocument(docStructure);
173
+ this.writer = new _PageElementWriter.default(new _DocumentContext.default(), this.unbreakableOverflow);
174
+ this.writer.context().addListener('pageAdded', page => {
175
+ let backgroundGetter = background;
176
+ if (page.customProperties['background'] || page.customProperties['background'] === null) {
177
+ backgroundGetter = page.customProperties['background'];
178
+ }
179
+ this.addBackground(backgroundGetter);
180
+ });
181
+ if (isNecessaryAddFirstPage(docStructure)) {
182
+ this.writer.addPage(this.pageSize, null, this.pageMargins);
183
+ }
184
+ this.processNode(docStructure);
185
+ (0, _pageNumbering.labelPages)(this.writer.context().pages); // w-pdfmaker: section page numbering
186
+ // Backgrounds, headers and footers must not participate in page break decisions.
187
+ const pageBreakNodes = this.contentNodes.slice();
188
+ this.addHeadersAndFooters(header, footer);
189
+ this.addWatermark(watermark, pdfDocument, defaultStyle);
190
+ return {
191
+ pages: this.writer.context().pages,
192
+ linearNodeList: this.linearNodeList,
193
+ pageBreakNodes
194
+ };
195
+ }
196
+ addBackground(background) {
197
+ let backgroundGetter = typeof background === 'function' ? background : () => background;
198
+ let context = this.writer.context();
199
+ let pageSize = context.getCurrentPage().pageSize;
200
+ let pageBackground = backgroundGetter(context.page + 1, pageSize);
201
+ if (pageBackground) {
202
+ const repeatables = this.writer.repeatables;
203
+ this.writer.repeatables = [];
204
+ this.backgroundLevel++;
205
+ try {
206
+ const page = context.getCurrentPage();
207
+ const itemsLength = page.items.length;
208
+ this.writer.beginUnbreakableBlock(pageSize.width, pageSize.height);
209
+ pageBackground = this.docPreprocessor.preprocessBlock(pageBackground);
210
+ this.processNode(this.docMeasure.measureBlock(pageBackground));
211
+ this.writer.commitUnbreakableBlock(0, 0);
212
+ context.backgroundLength[context.page] += page.items.length - itemsLength;
213
+ } finally {
214
+ this.writer.repeatables = repeatables;
215
+ this.backgroundLevel--;
216
+ }
217
+ }
218
+ }
219
+ addDynamicRepeatable(nodeGetter, sizeFunction, customPropertyName) {
220
+ let pages = this.writer.context().pages;
221
+ for (let pageIndex = 0, l = pages.length; pageIndex < l; pageIndex++) {
222
+ this.writer.context().page = pageIndex;
223
+ let customProperties = this.writer.context().getCurrentPage().customProperties;
224
+ let pageNodeGetter = nodeGetter;
225
+ if (customProperties[customPropertyName] || customProperties[customPropertyName] === null) {
226
+ pageNodeGetter = customProperties[customPropertyName];
227
+ }
228
+ if (typeof pageNodeGetter === 'undefined' || pageNodeGetter === null) {
229
+ continue;
230
+ }
231
+ let node = pageNodeGetter(pageIndex + 1, l, this.writer.context().pages[pageIndex].pageSize, pages[pageIndex].pageLabel);
232
+ if (node) {
233
+ let sizes = sizeFunction(this.writer.context().getCurrentPage().pageSize, this.writer.context().getCurrentPage().pageMargins);
234
+ this.writer.beginUnbreakableBlock(sizes.width, sizes.height);
235
+ node = this.docPreprocessor.preprocessBlock(node);
236
+ this.processNode(this.docMeasure.measureBlock(node));
237
+ this.writer.commitUnbreakableBlock(sizes.x, sizes.y);
238
+ }
239
+ }
240
+ }
241
+ addHeadersAndFooters(header, footer) {
242
+ const headerSizeFct = (pageSize, pageMargins) => ({
243
+ x: 0,
244
+ y: 0,
245
+ width: pageSize.width,
246
+ height: pageMargins.top
247
+ });
248
+ const footerSizeFct = (pageSize, pageMargins) => ({
249
+ x: 0,
250
+ y: pageSize.height - pageMargins.bottom,
251
+ width: pageSize.width,
252
+ height: pageMargins.bottom
253
+ });
254
+ this.addDynamicRepeatable(header, headerSizeFct, 'header');
255
+ this.addDynamicRepeatable(footer, footerSizeFct, 'footer');
256
+ }
257
+ addWatermark(watermark, pdfDocument, defaultStyle) {
258
+ let pages = this.writer.context().pages;
259
+ for (let i = 0, l = pages.length; i < l; i++) {
260
+ let pageWatermark = watermark;
261
+ if (pages[i].customProperties['watermark'] || pages[i].customProperties['watermark'] === null) {
262
+ pageWatermark = pages[i].customProperties['watermark'];
263
+ }
264
+ if (pageWatermark === undefined || pageWatermark === null) {
265
+ continue;
266
+ }
267
+ if ((0, _variableType.isString)(pageWatermark)) {
268
+ pageWatermark = {
269
+ 'text': pageWatermark
270
+ };
271
+ }
272
+ if (!pageWatermark.text) {
273
+ // empty watermark text
274
+ continue;
275
+ }
276
+ pages[i].watermark = getWatermarkObject({
277
+ ...pageWatermark
278
+ }, pages[i].pageSize, pdfDocument, defaultStyle);
279
+ }
280
+ function getWatermarkObject(watermark, pageSize, pdfDocument, defaultStyle) {
281
+ watermark.font = watermark.font || defaultStyle.font || 'Roboto';
282
+ watermark.fontSize = watermark.fontSize || 'auto';
283
+ watermark.color = watermark.color || 'black';
284
+ watermark.opacity = (0, _variableType.isNumber)(watermark.opacity) ? watermark.opacity : 0.6;
285
+ watermark.bold = watermark.bold || false;
286
+ watermark.italics = watermark.italics || false;
287
+ watermark.angle = (0, _variableType.isValue)(watermark.angle) ? watermark.angle : null;
288
+ if (watermark.angle === null) {
289
+ watermark.angle = Math.atan2(pageSize.height, pageSize.width) * -180 / Math.PI;
290
+ }
291
+ if (watermark.fontSize === 'auto') {
292
+ watermark.fontSize = getWatermarkFontSize(pageSize, watermark, pdfDocument);
293
+ }
294
+ let watermarkObject = {
295
+ text: watermark.text,
296
+ font: pdfDocument.provideFont(watermark.font, watermark.bold, watermark.italics),
297
+ fontSize: watermark.fontSize,
298
+ color: watermark.color,
299
+ opacity: watermark.opacity,
300
+ angle: watermark.angle
301
+ };
302
+ watermarkObject._size = getWatermarkSize(watermark, pdfDocument);
303
+ return watermarkObject;
304
+ }
305
+ function getWatermarkSize(watermark, pdfDocument) {
306
+ let textInlines = new _TextInlines.default(pdfDocument);
307
+ let styleContextStack = new _StyleContextStack.default(null, {
308
+ font: watermark.font,
309
+ bold: watermark.bold,
310
+ italics: watermark.italics
311
+ });
312
+ styleContextStack.push({
313
+ fontSize: watermark.fontSize
314
+ });
315
+ let size = textInlines.sizeOfText(watermark.text, styleContextStack);
316
+ let rotatedSize = textInlines.sizeOfRotatedText(watermark.text, watermark.angle, styleContextStack);
317
+ return {
318
+ size: size,
319
+ rotatedSize: rotatedSize
320
+ };
321
+ }
322
+ function getWatermarkFontSize(pageSize, watermark, pdfDocument) {
323
+ let textInlines = new _TextInlines.default(pdfDocument);
324
+ let styleContextStack = new _StyleContextStack.default(null, {
325
+ font: watermark.font,
326
+ bold: watermark.bold,
327
+ italics: watermark.italics
328
+ });
329
+ let rotatedSize;
330
+
331
+ /**
332
+ * Binary search the best font size.
333
+ * Initial bounds [0, 1000]
334
+ * Break when range < 1
335
+ */
336
+ let a = 0;
337
+ let b = 1000;
338
+ let c = (a + b) / 2;
339
+ while (Math.abs(a - b) > 1) {
340
+ styleContextStack.push({
341
+ fontSize: c
342
+ });
343
+ rotatedSize = textInlines.sizeOfRotatedText(watermark.text, watermark.angle, styleContextStack);
344
+ if (rotatedSize.width > pageSize.width) {
345
+ b = c;
346
+ c = (a + b) / 2;
347
+ } else if (rotatedSize.width < pageSize.width) {
348
+ if (rotatedSize.height > pageSize.height) {
349
+ b = c;
350
+ c = (a + b) / 2;
351
+ } else {
352
+ a = c;
353
+ c = (a + b) / 2;
354
+ }
355
+ }
356
+ styleContextStack.pop();
357
+ }
358
+ /*
359
+ End binary search
360
+ */
361
+ return c;
362
+ }
363
+ }
364
+ processNode(node, isVerticalAlignmentAllowed = false) {
365
+ const applyMargins = callback => {
366
+ let margin = node._margin;
367
+ if (node.pageBreak === 'before') {
368
+ this.writer.moveToNextPage(node.pageOrientation);
369
+ } else if (node.pageBreak === 'beforeOdd') {
370
+ this.writer.moveToNextPage(node.pageOrientation);
371
+ if ((this.writer.context().page + 1) % 2 === 0) {
372
+ this.writer.moveToNextPage(node.pageOrientation);
373
+ }
374
+ } else if (node.pageBreak === 'beforeEven') {
375
+ this.writer.moveToNextPage(node.pageOrientation);
376
+ if ((this.writer.context().page + 1) % 2 === 1) {
377
+ this.writer.moveToNextPage(node.pageOrientation);
378
+ }
379
+ }
380
+ const isDetachedBlock = node.relativePosition || node.absolutePosition;
381
+ if (this.breakableBlocks.has(node) && !isDetachedBlock) {
382
+ this.moveToNextPageIfNeeded();
383
+ }
384
+
385
+ // Detached nodes have no margins, their position is only determined by 'x' and 'y'
386
+ if (margin && !isDetachedBlock) {
387
+ const availableHeight = this.writer.context().availableHeight;
388
+ // If top margin is bigger than available space, move to next page
389
+ // Necessary for nodes inside tables
390
+ if (availableHeight - margin[1] < 0) {
391
+ // Consume the whole available space
392
+ this.writer.context().moveDown(availableHeight);
393
+ if (this.writer.context().inSnakingColumns() && !this.writer.context().isInNestedNonSnakingGroup()) {
394
+ this.snakingAwarePageBreak(node.pageOrientation);
395
+ } else {
396
+ this.writer.moveToNextPage(node.pageOrientation);
397
+ }
398
+ /**
399
+ * TODO - Something to consider:
400
+ * Right now the node starts at the top of next page (after header)
401
+ * Another option would be to apply just the top margin that has not been consumed in the page before
402
+ * It would something like: this.write.context().moveDown(margin[1] - availableHeight)
403
+ */
404
+ } else {
405
+ this.writer.context().moveDown(margin[1]);
406
+ }
407
+ // Apply lateral margins
408
+ this.writer.context().addMargin(margin[0], margin[2]);
409
+ }
410
+ const contentPage = this.writer.context().getCurrentPage();
411
+ const contentTop = this.writer.context().y;
412
+ callback();
413
+
414
+ // Measure before a bottom margin or an explicit break can change the page.
415
+ // Margins belong to the aligned box even when they do not fit on this page.
416
+ node.__height = contentPage && contentPage === this.writer.context().getCurrentPage() ? this.writer.context().y - contentTop : undefined;
417
+ if (node.__height !== undefined && margin && !isDetachedBlock) {
418
+ node.__height += margin[1] + margin[3];
419
+ }
420
+
421
+ // Detached nodes have no margins, their position is only determined by 'x' and 'y'
422
+ if (margin && !isDetachedBlock) {
423
+ const availableHeight = this.writer.context().availableHeight;
424
+ // If bottom margin is bigger than available space, move to next page
425
+ // Necessary for nodes inside tables
426
+ if (availableHeight - margin[3] < 0) {
427
+ this.writer.context().moveDown(availableHeight);
428
+ if (this.writer.context().inSnakingColumns() && !this.writer.context().isInNestedNonSnakingGroup()) {
429
+ this.snakingAwarePageBreak(node.pageOrientation);
430
+ } else {
431
+ this.writer.moveToNextPage(node.pageOrientation);
432
+ }
433
+ /**
434
+ * TODO - Something to consider:
435
+ * Right now next node starts at the top of next page (after header)
436
+ * Another option would be to apply the bottom margin that has not been consumed in the next page?
437
+ * It would something like: this.write.context().moveDown(margin[3] - availableHeight)
438
+ */
439
+ } else {
440
+ this.writer.context().moveDown(margin[3]);
441
+ }
442
+ // Apply lateral margins
443
+ this.writer.context().addMargin(-margin[0], -margin[2]);
444
+ }
445
+ if (node.pageBreak === 'after') {
446
+ this.writer.moveToNextPage(node.pageOrientation);
447
+ } else if (node.pageBreak === 'afterOdd') {
448
+ this.writer.moveToNextPage(node.pageOrientation);
449
+ if ((this.writer.context().page + 1) % 2 === 0) {
450
+ this.writer.moveToNextPage(node.pageOrientation);
451
+ }
452
+ } else if (node.pageBreak === 'afterEven') {
453
+ this.writer.moveToNextPage(node.pageOrientation);
454
+ if ((this.writer.context().page + 1) % 2 === 1) {
455
+ this.writer.moveToNextPage(node.pageOrientation);
456
+ }
457
+ }
458
+ };
459
+ this.linearNodeList.push(node);
460
+ if (this.backgroundLevel === 0) {
461
+ this.contentNodes.push(node);
462
+ }
463
+ decorateNode(node);
464
+ applyMargins(() => {
465
+ let verticalAlignment = node.verticalAlignment;
466
+ if (isVerticalAlignmentAllowed && verticalAlignment) {
467
+ var verticalAlignmentPage = this.writer.context().getCurrentPage();
468
+ var verticalAlignmentBegin = this.writer.beginVerticalAlignment(verticalAlignment);
469
+ }
470
+ let unbreakable = node.unbreakable && !this.breakableBlocks.has(node);
471
+ if (unbreakable) {
472
+ this.writer.beginUnbreakableBlock();
473
+ }
474
+ let absPosition = node.absolutePosition;
475
+ if (absPosition) {
476
+ var previousAbsolutePosition = this.writer.context().isAbsolutePosition;
477
+ this.writer.context().isAbsolutePosition = true;
478
+ this.writer.context().beginDetachedBlock();
479
+ this.writer.context().moveTo(absPosition.x || 0, absPosition.y || 0);
480
+ }
481
+ let relPosition = node.relativePosition;
482
+ if (relPosition) {
483
+ this.writer.context().beginDetachedBlock();
484
+ this.writer.context().moveToRelative(relPosition.x || 0, relPosition.y || 0);
485
+ }
486
+ if (node.stack) {
487
+ this.processVerticalContainer(node);
488
+ } else if (node.section) {
489
+ this.processSection(node);
490
+ } else if (node.columns) {
491
+ this.processColumns(node);
492
+ } else if (node.ul) {
493
+ this.processList(false, node);
494
+ } else if (node.ol) {
495
+ this.processList(true, node);
496
+ } else if (node.table) {
497
+ this.processTable(node);
498
+ } else if (node.text !== undefined) {
499
+ this.processLeaf(node);
500
+ } else if (node.toc) {
501
+ this.processToc(node);
502
+ } else if (node.image) {
503
+ this.processImage(node);
504
+ } else if (node.svg) {
505
+ this.processSVG(node);
506
+ } else if (node.canvas) {
507
+ this.processCanvas(node);
508
+ } else if (node.qr) {
509
+ this.processQr(node);
510
+ } else if (node.attachment) {
511
+ this.processAttachment(node);
512
+ } else if (!node._span) {
513
+ throw new Error(`Unrecognized document structure: ${(0, _node.stringifyNode)(node)}`);
514
+ }
515
+ if (absPosition) {
516
+ this.writer.context().isAbsolutePosition = previousAbsolutePosition;
517
+ }
518
+ if (absPosition || relPosition) {
519
+ this.writer.context().endDetachedBlock();
520
+ }
521
+ if (unbreakable) {
522
+ if (this.writer.commitUnbreakableBlock()) {
523
+ this.releaseUnbreakableBlock(node);
524
+ }
525
+ }
526
+ if (isVerticalAlignmentAllowed && verticalAlignment) {
527
+ // A transform cannot start on one page and finish on another, even
528
+ // when all of the cell's content moved to the next page together.
529
+ verticalAlignmentBegin.item.isCellContentMultiPage = verticalAlignmentPage !== this.writer.context().getCurrentPage();
530
+ this.verticalAlignmentItemStack.push({
531
+ begin: verticalAlignmentBegin,
532
+ end: this.writer.endVerticalAlignment(verticalAlignment)
533
+ });
534
+ }
535
+ });
536
+ }
537
+ releaseUnbreakableBlock(node) {
538
+ const isPlainStack = block => block.stack && !block.absolutePosition && !block.relativePosition && !block.pageBreak && (!block._margin || block._margin.every(value => value === 0));
539
+ this.breakableBlocks.add(node);
540
+ // Single-child wrappers with identical geometry overflow together.
541
+ while (isPlainStack(node) && node.stack.length === 1) {
542
+ const child = node.stack[0];
543
+ if (!child.unbreakable || !isPlainStack(child)) {
544
+ break;
545
+ }
546
+ this.breakableBlocks.add(child);
547
+ node = child;
548
+ }
549
+ }
550
+
551
+ /**
552
+ * Helper for page breaks that respects snaking column context.
553
+ * When in snaking columns, first tries moving to next column.
554
+ * If no columns available, moves to next page and resets x to left margin.
555
+ * @param {string} pageOrientation - Optional page orientation for the new page
556
+ * @param {TableProcessor} [tableProcessor] - Reapply table alignment in the new column
557
+ */
558
+ snakingAwarePageBreak(pageOrientation, tableProcessor) {
559
+ let ctx = this.writer.context();
560
+ let snakingSnapshot = ctx.getSnakingSnapshot();
561
+ if (!snakingSnapshot) {
562
+ return;
563
+ }
564
+
565
+ // Try flowing to next column first
566
+ if (this.writer.canMoveToNextColumn()) {
567
+ this.writer.moveToNextColumn(tableProcessor ? context => tableProcessor.alignTable(context) : undefined);
568
+ return;
569
+ }
570
+
571
+ // No more columns available, move to new page
572
+ this.writer.moveToNextPage(pageOrientation, context => {
573
+ // Reset and align the column before inserting repeated table headers.
574
+ let savedLastColumnWidth = context.lastColumnWidth;
575
+ context.resetSnakingColumnsForNewPage();
576
+ context.lastColumnWidth = savedLastColumnWidth;
577
+ if (tableProcessor) {
578
+ tableProcessor.alignTable(context);
579
+ }
580
+ });
581
+ }
582
+
583
+ // vertical container
584
+ processVerticalContainer(node) {
585
+ node.stack.forEach(item => {
586
+ this.processNode(item);
587
+ addAll(node.positions, item.positions);
588
+
589
+ //TODO: paragraph gap
590
+ }, this);
591
+ }
592
+
593
+ // section
594
+ processSection(sectionNode) {
595
+ // TODO: properties
596
+
597
+ let {
598
+ pageSize,
599
+ pageOrientation,
600
+ pageMargins,
601
+ header,
602
+ footer,
603
+ background,
604
+ watermark
605
+ } = sectionNode;
606
+ let page = this.writer.context().getCurrentPage();
607
+ if (!page || page && page.items.length) {
608
+ // move to new empty page
609
+ // page definition inherit from current page
610
+ if (pageSize === 'inherit') {
611
+ pageSize = page ? {
612
+ width: page.pageSize.width,
613
+ height: page.pageSize.height
614
+ } : undefined;
615
+ }
616
+ if (pageOrientation === 'inherit') {
617
+ pageOrientation = page ? page.pageSize.orientation : undefined;
618
+ }
619
+ if (pageMargins === 'inherit') {
620
+ pageMargins = page ? page.pageMargins : undefined;
621
+ }
622
+ if (header === 'inherit') {
623
+ header = page ? page.customProperties.header : undefined;
624
+ }
625
+ if (footer === 'inherit') {
626
+ footer = page ? page.customProperties.footer : undefined;
627
+ }
628
+ if (background === 'inherit') {
629
+ background = page ? page.customProperties.background : undefined;
630
+ }
631
+ if (watermark === 'inherit') {
632
+ watermark = page ? page.customProperties.watermark : undefined;
633
+ }
634
+ if (header && typeof header !== 'function' && header !== null) {
635
+ header = (0, _tools.convertToDynamicContent)(header);
636
+ }
637
+ if (footer && typeof footer !== 'function' && footer !== null) {
638
+ footer = (0, _tools.convertToDynamicContent)(footer);
639
+ }
640
+ let customProperties = {};
641
+ if (typeof header !== 'undefined') {
642
+ customProperties.header = header;
643
+ }
644
+ if (typeof footer !== 'undefined') {
645
+ customProperties.footer = footer;
646
+ }
647
+ if (typeof background !== 'undefined') {
648
+ customProperties.background = background;
649
+ }
650
+ if (typeof watermark !== 'undefined') {
651
+ customProperties.watermark = watermark;
652
+ }
653
+ this.writer.addPage(pageSize || this.pageSize, pageOrientation, pageMargins || this.pageMargins, customProperties);
654
+ this.writer.context().getCurrentPage().pageNumbering = sectionNode.pageNumbering; // w-pdfmaker: see labelPages()
655
+ }
656
+ this.processNode(sectionNode.section);
657
+ }
658
+
659
+ // columns
660
+ processColumns(columnNode) {
661
+ this.nestedLevel++;
662
+ let columns = columnNode.columns;
663
+ let availableWidth = this.writer.context().availableWidth;
664
+ let gaps = gapArray(columnNode._gap);
665
+ if (gaps) {
666
+ availableWidth -= (gaps.length - 1) * columnNode._gap;
667
+ }
668
+ _columnCalculator.default.buildColumnWidths(columns, availableWidth);
669
+ let result = this.processRow({
670
+ marginX: columnNode._margin ? [columnNode._margin[0], columnNode._margin[2]] : [0, 0],
671
+ cells: columns,
672
+ widths: columns,
673
+ gaps,
674
+ snakingColumns: columnNode.snakingColumns
675
+ });
676
+ addAll(columnNode.positions, result.positions);
677
+ this.nestedLevel--;
678
+ if (this.nestedLevel === 0) {
679
+ this.writer.context().resetMarginXTopParent();
680
+ }
681
+ function gapArray(gap) {
682
+ if (!gap) {
683
+ return null;
684
+ }
685
+ let gaps = [];
686
+ gaps.push(0);
687
+ for (let i = columns.length - 1; i > 0; i--) {
688
+ gaps.push(gap);
689
+ }
690
+ return gaps;
691
+ }
692
+ }
693
+
694
+ /**
695
+ * Searches for a cell in the same row that starts a rowspan and is positioned immediately before the current cell.
696
+ * Alternatively, it finds a cell where the colspan initiating the rowspan extends to the cell just before the current one.
697
+ *
698
+ * @param {Array<object>} arr - An array representing cells in a row.
699
+ * @param {number} i - The index of the current cell to search backward from.
700
+ * @returns {object|null} The starting cell of the rowspan if found; otherwise, `null`.
701
+ */
702
+ _findStartingRowSpanCell(arr, i) {
703
+ let requiredColspan = 1;
704
+ for (let index = i - 1; index >= 0; index--) {
705
+ if (!arr[index]._span) {
706
+ if (arr[index].rowSpan > 1 && (arr[index].colSpan || 1) === requiredColspan) {
707
+ return arr[index];
708
+ } else {
709
+ return null;
710
+ }
711
+ }
712
+ requiredColspan++;
713
+ }
714
+ return null;
715
+ }
716
+
717
+ /**
718
+ * Retrieves a page break description for a specified page from a list of page breaks.
719
+ *
720
+ * @param {Array<object>} pageBreaks - An array of page break descriptions, each containing `prevPage` properties.
721
+ * @param {number} page - The page number to find the associated page break for.
722
+ * @returns {object|undefined} The page break description object for the specified page if found; otherwise, `undefined`.
723
+ */
724
+ _getPageBreak(pageBreaks, page) {
725
+ return pageBreaks.find(desc => desc.prevPage === page);
726
+ }
727
+ _getPageBreakListBySpan(tableNode, page, rowIndex) {
728
+ if (!tableNode || !tableNode._breaksBySpan) {
729
+ return null;
730
+ }
731
+ const breaksList = tableNode._breaksBySpan.filter(desc => desc.prevPage === page && rowIndex <= desc.rowIndexOfSpanEnd);
732
+ let y = Number.MAX_VALUE,
733
+ prevY = Number.MIN_VALUE;
734
+ breaksList.forEach(b => {
735
+ prevY = Math.max(b.prevY, prevY);
736
+ y = Math.min(b.y, y);
737
+ });
738
+ return {
739
+ prevPage: page,
740
+ prevY: prevY,
741
+ y: y
742
+ };
743
+ }
744
+ _findSameRowPageBreakByRowSpanData(breaksBySpan, page, rowIndex) {
745
+ if (!breaksBySpan) {
746
+ return null;
747
+ }
748
+ return breaksBySpan.find(desc => desc.prevPage === page && rowIndex === desc.rowIndexOfSpanEnd);
749
+ }
750
+ _addRowSpanPageBreaks(pageBreaks, breaksBySpan, rowIndex, firstPage, lastPage) {
751
+ if (!breaksBySpan || firstPage >= lastPage) {
752
+ return;
753
+ }
754
+
755
+ // Track row breaks and active spans together, without searching the lists per page.
756
+ const breaksByPage = new Map(pageBreaks.map(rowBreak => [rowBreak.prevPage, {
757
+ rowBreak
758
+ }]));
759
+ let hasEndingSpan = false;
760
+ breaksBySpan.forEach(spanBreak => {
761
+ const page = spanBreak.prevPage;
762
+ if (page < firstPage || page >= lastPage || rowIndex > spanBreak.rowIndexOfSpanEnd) {
763
+ return;
764
+ }
765
+ let entry = breaksByPage.get(page);
766
+ if (!entry) {
767
+ entry = {};
768
+ breaksByPage.set(page, entry);
769
+ }
770
+ if (entry.spanBreak) {
771
+ this._resolveBreakY(entry.spanBreak, spanBreak, entry.spanBreak);
772
+ } else {
773
+ entry.spanBreak = {
774
+ prevPage: page,
775
+ prevY: spanBreak.prevY,
776
+ y: spanBreak.y
777
+ };
778
+ }
779
+ if (rowIndex === spanBreak.rowIndexOfSpanEnd) {
780
+ entry.endsHere = true;
781
+ hasEndingSpan = true;
782
+ }
783
+ });
784
+ if (!hasEndingSpan) {
785
+ return;
786
+ }
787
+ breaksByPage.forEach(({
788
+ rowBreak,
789
+ spanBreak,
790
+ endsHere
791
+ }) => {
792
+ if (!endsHere) {
793
+ return;
794
+ }
795
+ if (rowBreak) {
796
+ this._resolveBreakY(rowBreak, spanBreak, rowBreak);
797
+ } else {
798
+ pageBreaks.push(spanBreak);
799
+ }
800
+ });
801
+ pageBreaks.sort((a, b) => a.prevPage - b.prevPage);
802
+ }
803
+ _updatePageBreaksData(pageBreaks, tableNode, rowIndex) {
804
+ Object.keys(tableNode._bottomByPage).forEach(p => {
805
+ const page = Number(p);
806
+ const pageBreak = this._getPageBreak(pageBreaks, page);
807
+ if (pageBreak) {
808
+ pageBreak.prevY = Math.max(pageBreak.prevY, tableNode._bottomByPage[page]);
809
+ }
810
+ if (tableNode._breaksBySpan && tableNode._breaksBySpan.length > 0) {
811
+ const breaksBySpanList = tableNode._breaksBySpan.filter(pb => pb.prevPage === page && rowIndex <= pb.rowIndexOfSpanEnd);
812
+ if (breaksBySpanList && breaksBySpanList.length > 0) {
813
+ breaksBySpanList.forEach(b => {
814
+ b.prevY = Math.max(b.prevY, tableNode._bottomByPage[page]);
815
+ });
816
+ }
817
+ }
818
+ });
819
+ }
820
+
821
+ /**
822
+ * Resolves the Y-coordinates for a target object by comparing two break points.
823
+ *
824
+ * @param {object} break1 - The first break point with `prevY` and `y` properties.
825
+ * @param {object} break2 - The second break point with `prevY` and `y` properties.
826
+ * @param {object} target - The target object to be updated with resolved Y-coordinates.
827
+ * @property {number} target.prevY - Updated to the maximum `prevY` value between `break1` and `break2`.
828
+ * @property {number} target.y - Updated to the minimum `y` value between `break1` and `break2`.
829
+ */
830
+ _resolveBreakY(break1, break2, target) {
831
+ target.prevY = Math.max(break1.prevY, break2.prevY);
832
+ target.y = Math.min(break1.y, break2.y);
833
+ }
834
+ _storePageBreakData(data, startsRowSpan, pageBreaks, tableNode) {
835
+ if (!startsRowSpan) {
836
+ let pageDesc = this._getPageBreak(pageBreaks, data.prevPage);
837
+ let pageDescBySpan = this._getPageBreakListBySpan(tableNode, data.prevPage, data.rowIndex);
838
+ if (!pageDesc) {
839
+ pageDesc = {
840
+ ...data
841
+ };
842
+ pageBreaks.push(pageDesc);
843
+ }
844
+ if (pageDescBySpan) {
845
+ this._resolveBreakY(pageDesc, pageDescBySpan, pageDesc);
846
+ }
847
+ this._resolveBreakY(pageDesc, data, pageDesc);
848
+ } else {
849
+ const breaksBySpan = tableNode && tableNode._breaksBySpan || null;
850
+ let pageDescBySpan = this._findSameRowPageBreakByRowSpanData(breaksBySpan, data.prevPage, data.rowIndex);
851
+ if (!pageDescBySpan) {
852
+ pageDescBySpan = {
853
+ ...data,
854
+ rowIndexOfSpanEnd: data.rowIndex + data.rowSpan - 1
855
+ };
856
+ if (!tableNode._breaksBySpan) {
857
+ tableNode._breaksBySpan = [];
858
+ }
859
+ tableNode._breaksBySpan.push(pageDescBySpan);
860
+ }
861
+ pageDescBySpan.prevY = Math.max(pageDescBySpan.prevY, data.prevY);
862
+ pageDescBySpan.y = Math.min(pageDescBySpan.y, data.y);
863
+ let pageDesc = this._getPageBreak(pageBreaks, data.prevPage);
864
+ if (pageDesc) {
865
+ this._resolveBreakY(pageDesc, pageDescBySpan, pageDesc);
866
+ }
867
+ }
868
+ }
869
+ /**
870
+ * Calculates the left offset for a column based on the specified gap values.
871
+ *
872
+ * @param {number} i - The index of the column for which the offset is being calculated.
873
+ * @param {Array<number>} gaps - An array of gap values for each column.
874
+ * @returns {number} The left offset for the column. Returns `gaps[i]` if it exists, otherwise `0`.
875
+ */
876
+ _colLeftOffset(i, gaps) {
877
+ if (gaps && gaps.length > i) {
878
+ return gaps[i];
879
+ }
880
+ return 0;
881
+ }
882
+
883
+ /**
884
+ * Retrieves the ending cell for a row span in case it exists in a specified table column.
885
+ *
886
+ * @param {Array<Array<object>>} tableBody - The table body, represented as a 2D array of cell objects.
887
+ * @param {number} rowIndex - The index of the starting row for the row span.
888
+ * @param {object} column - The column object containing row span information.
889
+ * @param {number} columnIndex - The index of the column within the row.
890
+ * @returns {object|null} The cell at the end of the row span if it exists; otherwise, `null`.
891
+ * @throws {Error} If the row span extends beyond the total row count.
892
+ */
893
+ _getRowSpanEndingCell(tableBody, rowIndex, column, columnIndex) {
894
+ if (column.rowSpan && column.rowSpan > 1) {
895
+ let endingRow = rowIndex + column.rowSpan - 1;
896
+ if (endingRow >= tableBody.length) {
897
+ throw new Error(`Row span for column ${columnIndex} (with indexes starting from 0) exceeded row count`);
898
+ }
899
+ return tableBody[endingRow][columnIndex];
900
+ }
901
+ return null;
902
+ }
903
+ processRow({
904
+ marginX = [0, 0],
905
+ dontBreakRows = false,
906
+ rowsWithoutPageBreak = 0,
907
+ cells,
908
+ widths,
909
+ gaps,
910
+ tableNode,
911
+ tableBody,
912
+ rowIndex,
913
+ height,
914
+ snakingColumns = false
915
+ }) {
916
+ const isUnbreakableRow = dontBreakRows || rowIndex <= rowsWithoutPageBreak - 1;
917
+ const rowContext = this.writer.context();
918
+ const detachedBlock = rowContext.detachedBlock;
919
+ const repeatablesAtRowStart = this.writer.repeatables.length;
920
+ let pageBreaks = [];
921
+ let pageBreaksByRowSpan = [];
922
+ let positions = [];
923
+ let willBreakByHeight = false;
924
+ let verticalAlignmentCells = {};
925
+ widths = widths || cells;
926
+
927
+ // Check if row should break by height
928
+ if (!isUnbreakableRow && height > this.writer.context().availableHeight) {
929
+ willBreakByHeight = true;
930
+ }
931
+
932
+ // Use the marginX if we are in a top level table/column (not nested)
933
+ const marginXParent = this.nestedLevel === 1 ? marginX : null;
934
+ const _bottomByPage = tableNode ? tableNode._bottomByPage : null;
935
+ // Pass column gap and widths to context snapshot for snaking columns
936
+ // to advance correctly and reset to first-column width on new pages.
937
+ const columnGapForGroup = gaps && gaps.length > 1 ? gaps[1] : 0;
938
+ const columnWidthsForContext = widths.map(w => w._calcWidth);
939
+ this.writer.context().beginColumnGroup(marginXParent, _bottomByPage, snakingColumns, columnGapForGroup, columnWidthsForContext);
940
+
941
+ // IMPORTANT: We iterate ALL columns even when snakingColumns is enabled.
942
+ // This is intentional — beginColumn() must be called for each column to set up
943
+ // proper geometry (widths, offsets) and rowspan/colspan tracking. The
944
+ // completeColumnGroup() call at the end depends on this bookkeeping to compute
945
+ // heights correctly. Content processing is skipped for columns > 0 via
946
+ // skipForSnaking below, but the column structure must still be established.
947
+ for (let i = 0, l = cells.length; i < l; i++) {
948
+ let cell = cells[i];
949
+ let cellIndexBegin = i;
950
+
951
+ // Page change handler
952
+ const storePageBreakClosure = data => {
953
+ // Page breaks in another context or detached block do not split this row.
954
+ if (this.writer.context() !== rowContext || rowContext.detachedBlock !== detachedBlock) {
955
+ return;
956
+ }
957
+ // Each row needs its own break position. Headers belonging to nested
958
+ // tables are inside this row's borders, unlike its own/ancestor headers.
959
+ data = {
960
+ ...data
961
+ };
962
+ if (tableNode) {
963
+ for (let j = repeatablesAtRowStart; j < this.writer.repeatables.length; j++) {
964
+ data.y -= this.writer.repeatables[j].height;
965
+ }
966
+ }
967
+ const startsRowSpan = cell.rowSpan && cell.rowSpan > 1;
968
+ if (startsRowSpan) {
969
+ data.rowSpan = cell.rowSpan;
970
+ }
971
+ data.rowIndex = rowIndex;
972
+ this._storePageBreakData(data, startsRowSpan, pageBreaks, tableNode);
973
+ };
974
+ this.writer.addListener('pageChanged', storePageBreakClosure);
975
+ let width = widths[i]._calcWidth;
976
+ let leftOffset = this._colLeftOffset(i, gaps);
977
+ // Check if exists and retrieve the cell that started the rowspan in case we are in the cell just after
978
+ let startingSpanCell = this._findStartingRowSpanCell(cells, i);
979
+ if (cell.colSpan && cell.colSpan > 1) {
980
+ for (let j = 1; j < cell.colSpan; j++) {
981
+ width += widths[++i]._calcWidth + gaps[i];
982
+ }
983
+ }
984
+
985
+ // if rowspan starts in this cell, we retrieve the last cell affected by the rowspan
986
+ const rowSpanRightEndingCell = this._getRowSpanEndingCell(tableBody, rowIndex, cell, i);
987
+ const rowSpanLeftEndingCell = this._getRowSpanEndingCell(tableBody, rowIndex, cell, cellIndexBegin);
988
+ if (rowSpanRightEndingCell) {
989
+ // We store a reference of the ending cell in the first cell of the rowspan
990
+ cell._endingCell = rowSpanRightEndingCell;
991
+ cell._endingCell._startingRowSpanY = cell._startingRowSpanY;
992
+ cell._endingCell._startingRowSpanPage = cell._startingRowSpanPage;
993
+ }
994
+ if (rowSpanLeftEndingCell) {
995
+ // We store a reference of the left ending cell in the first cell of the rowspan
996
+ cell._leftEndingCell = rowSpanLeftEndingCell;
997
+ cell._leftEndingCell._startingRowSpanY = cell._startingRowSpanY;
998
+ cell._leftEndingCell._startingRowSpanPage = cell._startingRowSpanPage;
999
+ }
1000
+
1001
+ // If we are after a cell that started a rowspan
1002
+ let endOfRowSpanCell = null;
1003
+ if (startingSpanCell && startingSpanCell._endingCell) {
1004
+ // Reference to the last cell of the rowspan
1005
+ endOfRowSpanCell = startingSpanCell._endingCell;
1006
+ // Store if we are in an unbreakable block when we save the context and the originalX
1007
+ if (this.writer.transactionLevel > 0) {
1008
+ endOfRowSpanCell._isUnbreakableContext = true;
1009
+ endOfRowSpanCell._originalXOffset = this.writer.originalX;
1010
+ }
1011
+ }
1012
+
1013
+ // We pass the endingSpanCell reference to store the context just after processing rowspan cell
1014
+ this.writer.context().beginColumn(width, leftOffset, endOfRowSpanCell);
1015
+
1016
+ // When snaking, only process content from the first column (i === 0).
1017
+ // Content overflows into subsequent columns via moveToNextColumn().
1018
+ // We skip content processing here but NOT the beginColumn() call above —
1019
+ // the column geometry setup is still needed for proper layout bookkeeping.
1020
+ const skipForSnaking = snakingColumns && i > 0;
1021
+ if (!cell._span && !skipForSnaking) {
1022
+ if (cell.verticalAlignment) {
1023
+ cell._verticalAlignmentFirstPage = {
1024
+ start: this.writer.getCurrentPositionOnPage(),
1025
+ ends: [],
1026
+ hasPageBreak: false
1027
+ };
1028
+ }
1029
+ this.processNode(cell, true);
1030
+ this.writer.context().updateBottomByPage();
1031
+ if (cell.verticalAlignment) {
1032
+ verticalAlignmentCells[cellIndexBegin] = this.verticalAlignmentItemStack.length - 1;
1033
+ }
1034
+ addAll(positions, cell.positions);
1035
+ } else if (cell._columnEndingContext) {
1036
+ let discountY = 0;
1037
+ if (dontBreakRows) {
1038
+ // Calculate how many points we have to discount to Y when dontBreakRows and rowSpan are combined
1039
+ const ctxBeforeRowSpanLastRow = this.writer.contextStack[this.writer.contextStack.length - 1];
1040
+ // Explicit page breaks can leave the row without an unbreakable context.
1041
+ const startsOnCurrentPage = ctxBeforeRowSpanLastRow && typeof cell._startingRowSpanPage === 'number' && cell._startingRowSpanPage === ctxBeforeRowSpanLastRow.page;
1042
+ if (startsOnCurrentPage && typeof cell._startingRowSpanY === 'number') {
1043
+ discountY = ctxBeforeRowSpanLastRow.y - cell._startingRowSpanY;
1044
+ }
1045
+
1046
+ // Do not increase Y by applying a negative discount.
1047
+ discountY = Math.max(0, discountY);
1048
+ }
1049
+ let originalXOffset = 0;
1050
+ // If context was saved from an unbreakable block and we are not in an unbreakable block anymore
1051
+ // We have to sum the originalX (X before starting unbreakable block) to X
1052
+ if (cell._isUnbreakableContext && !this.writer.transactionLevel) {
1053
+ originalXOffset = cell._originalXOffset;
1054
+ }
1055
+ // row-span ending
1056
+ // Recover the context after processing the rowspanned cell
1057
+ this.writer.context().markEnding(cell, originalXOffset, discountY);
1058
+ }
1059
+ this.writer.removeListener('pageChanged', storePageBreakClosure);
1060
+ }
1061
+
1062
+ // Check if last cell is part of a span
1063
+ let endingSpanCell = null;
1064
+ const lastColumn = cells.length > 0 ? cells[cells.length - 1] : null;
1065
+ if (lastColumn) {
1066
+ // Previous column cell has a rowspan
1067
+ if (lastColumn._endingCell) {
1068
+ endingSpanCell = lastColumn._endingCell;
1069
+ // Previous column cell is part of a span
1070
+ } else if (lastColumn._span === true) {
1071
+ // We get the cell that started the span where we set a reference to the ending cell
1072
+ const startingSpanCell = this._findStartingRowSpanCell(cells, cells.length);
1073
+ if (startingSpanCell) {
1074
+ // Context will be stored here (ending cell)
1075
+ endingSpanCell = startingSpanCell._endingCell;
1076
+ // Store if we are in an unbreakable block when we save the context and the originalX
1077
+ if (this.writer.transactionLevel > 0) {
1078
+ endingSpanCell._isUnbreakableContext = true;
1079
+ endingSpanCell._originalXOffset = this.writer.originalX;
1080
+ }
1081
+ }
1082
+ }
1083
+ }
1084
+
1085
+ // If content did not break page, check if we should break by height
1086
+ if (willBreakByHeight && !isUnbreakableRow && pageBreaks.length === 0) {
1087
+ this.writer.context().moveDown(this.writer.context().availableHeight);
1088
+ if (snakingColumns) {
1089
+ this.snakingAwarePageBreak();
1090
+ } else {
1091
+ this.writer.moveToNextPage();
1092
+ }
1093
+ }
1094
+ const bottomByPage = this.writer.context().completeColumnGroup(height, endingSpanCell);
1095
+ if (tableNode) {
1096
+ tableNode._bottomByPage = bottomByPage;
1097
+ // If there are page breaks in this row, update data with prevY of last cell
1098
+ this._updatePageBreaksData(pageBreaks, tableNode, rowIndex);
1099
+ }
1100
+ let rowHeight = this.writer.context().height;
1101
+ for (let i = 0, l = cells.length; i < l; i++) {
1102
+ let cell = cells[i];
1103
+ if (!cell._span && cell.verticalAlignment) {
1104
+ let itemBegin = this.verticalAlignmentItemStack[verticalAlignmentCells[i]].begin.item;
1105
+ itemBegin.viewHeight = rowHeight;
1106
+ itemBegin.nodeHeight = cell.__height;
1107
+ itemBegin.cell = cell;
1108
+ itemBegin.isCellContentMultiPage = itemBegin.isCellContentMultiPage || !itemBegin.cell.positions.every(item => item.pageNumber === itemBegin.cell.positions[0].pageNumber);
1109
+ // Keep this occurrence's positions when the same cell is processed again.
1110
+ const firstPage = cell._verticalAlignmentFirstPage;
1111
+ itemBegin.getViewHeight = function () {
1112
+ if (firstPage && (this.cell.rowSpan > 1 || firstPage.hasPageBreak || firstPage.ends.some(end => end.pageNumber !== firstPage.start.pageNumber))) {
1113
+ // Fragment insertion updates these positions, including moves between
1114
+ // whole unbreakable rows and through enclosing temporary contexts.
1115
+ const bottom = firstPage.ends.reduce((value, end) => end.pageNumber === firstPage.start.pageNumber ? Math.max(value, end.top) : value, firstPage.start.top);
1116
+ return bottom - firstPage.start.top;
1117
+ }
1118
+ return this.viewHeight;
1119
+ };
1120
+ itemBegin.getNodeHeight = function () {
1121
+ return this.nodeHeight;
1122
+ };
1123
+ let itemEnd = this.verticalAlignmentItemStack[verticalAlignmentCells[i]].end.item;
1124
+ itemEnd.isCellContentMultiPage = itemBegin.isCellContentMultiPage;
1125
+ itemEnd.getViewHeight = itemBegin.getViewHeight.bind(itemBegin);
1126
+ itemEnd.getNodeHeight = itemBegin.getNodeHeight.bind(itemBegin);
1127
+ }
1128
+ }
1129
+ return {
1130
+ pageBreaksBySpan: pageBreaksByRowSpan,
1131
+ pageBreaks: pageBreaks,
1132
+ positions: positions
1133
+ };
1134
+ }
1135
+
1136
+ // lists
1137
+ processList(orderedList, node) {
1138
+ const backgroundLevel = this.backgroundLevel;
1139
+ const addMarkerToFirstLeaf = line => {
1140
+ // I'm not very happy with the way list processing is implemented
1141
+ // (both code and algorithm should be rethinked)
1142
+ // Background lines must only consume markers from lists in that background.
1143
+ if (nextMarker && this.backgroundLevel === backgroundLevel) {
1144
+ let marker = nextMarker;
1145
+ nextMarker = null;
1146
+ if (marker.canvas) {
1147
+ let vector = marker.canvas[0];
1148
+ (0, _tools.offsetVector)(vector, -marker._minWidth, 0);
1149
+ this.writer.addVector(vector);
1150
+ } else if (marker._inlines) {
1151
+ let markerLine = new _Line.default(this.pageSize.width);
1152
+ markerLine.addInline(marker._inlines[0]);
1153
+ markerLine.x = -marker._minWidth;
1154
+ markerLine.y = line.getAscenderHeight() - markerLine.getAscenderHeight();
1155
+ this.writer.addLine(markerLine, true);
1156
+ }
1157
+ }
1158
+ };
1159
+ let items = orderedList ? node.ol : node.ul;
1160
+ let gapSize = node._gapSize;
1161
+ this.writer.context().addMargin(gapSize.width);
1162
+ let nextMarker;
1163
+ this.writer.addListener('lineAdded', addMarkerToFirstLeaf);
1164
+ items.forEach(item => {
1165
+ nextMarker = item.listMarker;
1166
+ this.processNode(item);
1167
+ addAll(node.positions, item.positions);
1168
+ });
1169
+ this.writer.removeListener('lineAdded', addMarkerToFirstLeaf);
1170
+ this.writer.context().addMargin(-gapSize.width);
1171
+ }
1172
+ moveToNextPageIfNeeded(tableProcessor) {
1173
+ const context = this.writer.context();
1174
+ // Released children must retain their positioned parent's current page and origin.
1175
+ if (context.detachedBlock) {
1176
+ return;
1177
+ }
1178
+ const snapshot = context.snapshots[context.snapshots.length - 1];
1179
+ // Content in a sibling column does not precede this block in its own column.
1180
+ if (snapshot && !snapshot.snakingColumns && snapshot.columnStart && snapshot.columnStart.page === context.page && snapshot.columnStart.itemsLength === context.getCurrentPage().items.length) {
1181
+ return;
1182
+ }
1183
+ const pageTop = context.pageMargins.top + this.writer.repeatables.reduce((height, repeatable) => height + repeatable.height, 0);
1184
+ const backgroundLength = context.backgroundLength[context.page] || 0;
1185
+ if (context.y > pageTop && context.getCurrentPage().items.length > backgroundLength) {
1186
+ const resetColumns = context.inSnakingColumns() && !context.isInNestedNonSnakingGroup();
1187
+ this.writer.moveToNextPage(undefined, resetColumns ? () => {
1188
+ if (tableProcessor) {
1189
+ context.addMargin(-tableProcessor.alignmentOffset, tableProcessor.alignmentOffset);
1190
+ }
1191
+ context.resetSnakingColumnsForNewPage();
1192
+ if (tableProcessor) {
1193
+ tableProcessor.alignTable(context);
1194
+ if (tableProcessor.cleanUpRepeatables) {
1195
+ // Row continuations use the header's origin without resetting columns.
1196
+ this.writer.repeatables[this.writer.repeatables.length - 1].xOffset = context.x;
1197
+ }
1198
+ }
1199
+ } : undefined);
1200
+ }
1201
+ }
1202
+
1203
+ // tables
1204
+ processTable(tableNode) {
1205
+ // Page breaks and row bottoms belong to the current layout pass only.
1206
+ delete tableNode._bottomByPage;
1207
+ delete tableNode._breaksBySpan;
1208
+ tableNode.table.body.forEach(row => row.forEach(cell => {
1209
+ delete cell._willBreak;
1210
+ delete cell._bottomY;
1211
+ delete cell._verticalAlignmentFirstPage;
1212
+ }));
1213
+ this.nestedLevel++;
1214
+ let processor = new _TableProcessor.default(tableNode, this.breakableBlocks);
1215
+ if (this.breakableBlocks.has(tableNode.table.body[0]) || this.breakableBlocks.has(tableNode.table)) {
1216
+ this.moveToNextPageIfNeeded();
1217
+ }
1218
+ processor.beginTable(this.writer);
1219
+ let rowHeights = tableNode.table.heights;
1220
+ let lastRowHeight = 0;
1221
+ for (let i = 0, l = tableNode.table.body.length; i < l; i++) {
1222
+ if (i > 0 && this.breakableBlocks.has(tableNode.table.body[i]) && !tableNode.table.body[i].some(cell => cell._rowSpanCurrentOffset)) {
1223
+ const pageBefore = this.writer.context().page;
1224
+ this.moveToNextPageIfNeeded(processor);
1225
+ if (this.writer.context().page !== pageBefore && !processor.headerRows && processor.layout.hLineWhenBroken !== false) {
1226
+ processor.drawHorizontalLine(i, this.writer);
1227
+ }
1228
+ }
1229
+ // Between table rows: check if we should move to the next snaking column.
1230
+ // This must happen AFTER the previous row's endRow (borders drawn) and
1231
+ // BEFORE this row's beginRow. At this point, the table row column group
1232
+ // has been completed, so canMoveToNextColumn() works correctly.
1233
+ if (i > 0 && this.writer.context().inSnakingColumns()) {
1234
+ // Estimate minimum space for next row: use last row's height as heuristic,
1235
+ // or fall back to a minimum of padding + line height + border
1236
+ let minRowHeight = lastRowHeight > 0 ? lastRowHeight : processor.rowPaddingTop + 14 + processor.rowPaddingBottom + processor.bottomLineWidth + processor.topLineWidth;
1237
+ if (this.writer.context().availableHeight < minRowHeight) {
1238
+ // Column selection needs the container origin, before table alignment.
1239
+ if (processor.alignmentOffset) {
1240
+ this.writer.context().addMargin(-processor.alignmentOffset, processor.alignmentOffset);
1241
+ }
1242
+ this.snakingAwarePageBreak(undefined, processor);
1243
+
1244
+ // Skip border when headerRows present (header repeat includes it)
1245
+ if (processor.layout.hLineWhenBroken !== false && !processor.headerRows) {
1246
+ processor.drawHorizontalLine(i, this.writer);
1247
+ }
1248
+ }
1249
+ }
1250
+ let rowYBefore = this.writer.context().y;
1251
+
1252
+ // if dontBreakRows and row starts a rowspan
1253
+ // we store the 'y' of the beginning of each rowSpan
1254
+ if (tableNode.table.dontBreakRows && !this.breakableBlocks.has(tableNode.table.body[i])) {
1255
+ tableNode.table.body[i].forEach(cell => {
1256
+ if (cell.rowSpan && cell.rowSpan > 1) {
1257
+ cell._startingRowSpanY = this.writer.context().y;
1258
+ cell._startingRowSpanPage = this.writer.context().page;
1259
+ }
1260
+ });
1261
+ }
1262
+ processor.beginRow(i, this.writer);
1263
+ let height;
1264
+ if (typeof rowHeights === 'function') {
1265
+ height = rowHeights(i);
1266
+ } else if (Array.isArray(rowHeights)) {
1267
+ height = rowHeights[i];
1268
+ } else {
1269
+ height = rowHeights;
1270
+ }
1271
+ if (height === 'auto') {
1272
+ height = undefined;
1273
+ }
1274
+ const pageBeforeProcessing = this.writer.context().page;
1275
+ let result = this.processRow({
1276
+ marginX: tableNode._margin ? [tableNode._margin[0], tableNode._margin[2]] : [0, 0],
1277
+ dontBreakRows: processor.dontBreakRows,
1278
+ rowsWithoutPageBreak: processor.rowsWithoutPageBreak,
1279
+ cells: tableNode.table.body[i],
1280
+ widths: tableNode.table.widths,
1281
+ gaps: tableNode._offsets.offsets,
1282
+ tableBody: tableNode.table.body,
1283
+ tableNode,
1284
+ rowIndex: i,
1285
+ height
1286
+ });
1287
+ addAll(tableNode.positions, result.positions);
1288
+ this._addRowSpanPageBreaks(result.pageBreaks, tableNode._breaksBySpan, i, pageBeforeProcessing, this.writer.context().page);
1289
+ processor.endRow(i, this.writer, result.pageBreaks);
1290
+
1291
+ // Track the height of the completed row for the next row's estimate
1292
+ let rowYAfter = this.writer.context().y;
1293
+ if (this.writer.context().page === pageBeforeProcessing) {
1294
+ lastRowHeight = rowYAfter - rowYBefore;
1295
+ }
1296
+ }
1297
+ processor.endTable(this.writer);
1298
+ this.nestedLevel--;
1299
+ if (this.nestedLevel === 0) {
1300
+ this.writer.context().resetMarginXTopParent();
1301
+ }
1302
+ }
1303
+
1304
+ // leafs (texts)
1305
+ processLeaf(node) {
1306
+ let line = this.buildNextLine(node);
1307
+ if (line && (node.tocItem || node.id)) {
1308
+ line._node = node;
1309
+ }
1310
+ let currentHeight = line ? line.getHeight() : 0;
1311
+ let maxHeight = node.maxHeight ?? -1;
1312
+ if (line) {
1313
+ let nodeId = (0, _node.getNodeId)(node);
1314
+ if (nodeId) {
1315
+ line.id = nodeId;
1316
+ }
1317
+ }
1318
+ if (node.outline) {
1319
+ line._outline = {
1320
+ id: node.id,
1321
+ parentId: node.outlineParentId,
1322
+ text: node.outlineText || node.text,
1323
+ expanded: node.outlineExpanded || false
1324
+ };
1325
+ } else if (Array.isArray(node.text)) {
1326
+ for (let i = 0, l = node.text.length; i < l; i++) {
1327
+ let item = node.text[i];
1328
+ if (item.outline) {
1329
+ line._outline = {
1330
+ id: item.id,
1331
+ parentId: item.outlineParentId,
1332
+ text: item.outlineText || item.text,
1333
+ expanded: item.outlineExpanded || false
1334
+ };
1335
+ }
1336
+ }
1337
+ }
1338
+ if (node._tocItemRef) {
1339
+ line._pageNodeRef = node._tocItemRef;
1340
+ }
1341
+ if (node._pageRef) {
1342
+ line._pageNodeRef = node._pageRef._nodeRef;
1343
+ }
1344
+ if (line && line.inlines && Array.isArray(line.inlines)) {
1345
+ for (let i = 0, l = line.inlines.length; i < l; i++) {
1346
+ if (line.inlines[i]._tocItemRef) {
1347
+ line.inlines[i]._pageNodeRef = line.inlines[i]._tocItemRef;
1348
+ }
1349
+ if (line.inlines[i]._pageRef) {
1350
+ line.inlines[i]._pageNodeRef = line.inlines[i]._pageRef._nodeRef;
1351
+ }
1352
+ }
1353
+ }
1354
+ let triedNewPage = false;
1355
+ while (line && (maxHeight === -1 || currentHeight <= maxHeight)) {
1356
+ // Check if line fits vertically in current context
1357
+ if (line.getHeight() > this.writer.context().availableHeight && this.writer.context().y > this.writer.context().pageMargins.top) {
1358
+ // Line doesn't fit, forced move to next page/column
1359
+ // Only do snaking-specific break if we're in snaking columns AND NOT inside
1360
+ // a nested non-snaking group (like a table row). Table cells should use
1361
+ // standard page breaks — column breaks happen between table rows instead.
1362
+ if (this.writer.context().inSnakingColumns() && !this.writer.context().isInNestedNonSnakingGroup()) {
1363
+ let context = this.writer.context();
1364
+ let pageCount = context.pages.length;
1365
+ this.snakingAwarePageBreak(node.pageOrientation);
1366
+ if (context.pages.length > pageCount) {
1367
+ // Existing pages may have different geometry. Once a new page's columns
1368
+ // are exhausted without placing text, more new pages cannot help.
1369
+ if (triedNewPage) {
1370
+ throw new Error('Content cannot fit on a page within the available space.');
1371
+ }
1372
+ triedNewPage = true;
1373
+ }
1374
+
1375
+ // Always reflow text after a snaking break (column or page).
1376
+ // This ensures text adapts to the new column width, whether it's narrower or wider.
1377
+ if (line.inlines && line.inlines.length > 0) {
1378
+ node._inlines.unshift(...line.inlines);
1379
+ }
1380
+ // Rebuild line with new width
1381
+ line = this.buildNextLine(node);
1382
+ continue;
1383
+ } else {
1384
+ this.writer.moveToNextPage(node.pageOrientation);
1385
+ }
1386
+ }
1387
+ let positions = this.writer.addLine(line);
1388
+ node.positions.push(positions);
1389
+ triedNewPage = false;
1390
+ line = this.buildNextLine(node);
1391
+ if (line) {
1392
+ currentHeight += line.getHeight();
1393
+ }
1394
+ }
1395
+ }
1396
+ processToc(node) {
1397
+ if (!node.toc._table && node.toc.hideEmpty === true) {
1398
+ return;
1399
+ }
1400
+ if (node.toc.title) {
1401
+ this.processNode(node.toc.title);
1402
+ }
1403
+ if (node.toc._table) {
1404
+ this.processNode(node.toc._table);
1405
+ }
1406
+ }
1407
+ buildNextLine(textNode) {
1408
+ function cloneInline(inline) {
1409
+ let newInline = inline.constructor();
1410
+ for (let key in inline) {
1411
+ newInline[key] = inline[key];
1412
+ }
1413
+ return newInline;
1414
+ }
1415
+ function findMaxFitLength(characters, maxWidth, measureFn) {
1416
+ let low = 1;
1417
+ let high = characters.length;
1418
+ let bestFit = 1;
1419
+ while (low <= high) {
1420
+ const mid = Math.floor((low + high) / 2);
1421
+ const part = characters.slice(0, mid).join('');
1422
+ const width = measureFn(part);
1423
+ if (width <= maxWidth) {
1424
+ bestFit = mid;
1425
+ low = mid + 1;
1426
+ } else {
1427
+ high = mid - 1;
1428
+ }
1429
+ }
1430
+ return bestFit;
1431
+ }
1432
+ if (!textNode._inlines || textNode._inlines.length === 0) {
1433
+ return null;
1434
+ }
1435
+ let line = new _Line.default(this.writer.context().availableWidth);
1436
+ const textInlines = new _TextInlines.default(null);
1437
+ let isForceContinue = false;
1438
+ while (textNode._inlines && textNode._inlines.length > 0 && (line.hasEnoughSpaceForInline(textNode._inlines[0], textNode._inlines.slice(1)) || isForceContinue)) {
1439
+ let isHardWrap = false;
1440
+ let inline = textNode._inlines.shift();
1441
+ if (!inline.noWrap && inline.text.length > 1 && inline.width > line.getAvailableWidth()) {
1442
+ const characters = Array.from(inline.text);
1443
+ let maxChars = findMaxFitLength(characters, line.getAvailableWidth(), txt => textInlines.widthOfText(txt, inline));
1444
+ if (maxChars < characters.length) {
1445
+ let newInline = cloneInline(inline);
1446
+ newInline.text = characters.slice(maxChars).join('');
1447
+ inline.text = characters.slice(0, maxChars).join('');
1448
+ newInline.width = textInlines.widthOfText(newInline.text, newInline);
1449
+ inline.width = textInlines.widthOfText(inline.text, inline);
1450
+ textNode._inlines.unshift(newInline);
1451
+ isHardWrap = true;
1452
+ }
1453
+ }
1454
+ line.addInline(inline);
1455
+ isForceContinue = inline.noNewLine && !isHardWrap;
1456
+ }
1457
+ line.lastLineInParagraph = textNode._inlines.length === 0;
1458
+ return line;
1459
+ }
1460
+
1461
+ // images
1462
+ processImage(node) {
1463
+ let position = this.writer.addImage(node);
1464
+ node.positions.push(position);
1465
+ }
1466
+ processCanvas(node) {
1467
+ let positions = this.writer.addCanvas(node);
1468
+ addAll(node.positions, positions);
1469
+ }
1470
+ processSVG(node) {
1471
+ let position = this.writer.addSVG(node);
1472
+ node.positions.push(position);
1473
+ }
1474
+ processQr(node) {
1475
+ let position = this.writer.addQr(node);
1476
+ node.positions.push(position);
1477
+ }
1478
+ processAttachment(node) {
1479
+ let position = this.writer.addAttachment(node);
1480
+ node.positions.push(position);
1481
+ }
1482
+ }
1483
+ function decorateNode(node) {
1484
+ let x = node.x;
1485
+ let y = node.y;
1486
+ node.positions = [];
1487
+ if (Array.isArray(node.canvas)) {
1488
+ node.canvas.forEach(vector => {
1489
+ let x = vector.x;
1490
+ let y = vector.y;
1491
+ let x1 = vector.x1;
1492
+ let y1 = vector.y1;
1493
+ let x2 = vector.x2;
1494
+ let y2 = vector.y2;
1495
+ let points = vector.type === 'polyline' ? vector.points.map(point => ({
1496
+ x: point.x,
1497
+ y: point.y
1498
+ })) : null;
1499
+ vector.resetXY = () => {
1500
+ vector.x = x;
1501
+ vector.y = y;
1502
+ vector.x1 = x1;
1503
+ vector.y1 = y1;
1504
+ vector.x2 = x2;
1505
+ vector.y2 = y2;
1506
+ if (points) {
1507
+ points.forEach((point, index) => {
1508
+ vector.points[index].x = point.x;
1509
+ vector.points[index].y = point.y;
1510
+ });
1511
+ }
1512
+ };
1513
+ });
1514
+ }
1515
+ node.resetXY = () => {
1516
+ node.x = x;
1517
+ node.y = y;
1518
+ if (Array.isArray(node.canvas)) {
1519
+ node.canvas.forEach(vector => {
1520
+ vector.resetXY();
1521
+ });
1522
+ }
1523
+ };
1524
+ }
1525
+ var _default = exports.default = LayoutBuilder;