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