pdfmake-acroforms 0.3.4

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 (115) hide show
  1. package/CHANGELOG.md +60 -0
  2. package/LICENSE +21 -0
  3. package/README.md +75 -0
  4. package/build/fonts/Roboto/Roboto-Italic.ttf +0 -0
  5. package/build/fonts/Roboto/Roboto-Medium.ttf +0 -0
  6. package/build/fonts/Roboto/Roboto-MediumItalic.ttf +0 -0
  7. package/build/fonts/Roboto/Roboto-Regular.ttf +0 -0
  8. package/build/fonts/Roboto.js +27 -0
  9. package/build/pdfmake.js +67806 -0
  10. package/build/pdfmake.js.map +1 -0
  11. package/build/pdfmake.min.js +3 -0
  12. package/build/pdfmake.min.js.map +1 -0
  13. package/build/standard-fonts/Courier.js +27 -0
  14. package/build/standard-fonts/Helvetica.js +27 -0
  15. package/build/standard-fonts/Symbol.js +21 -0
  16. package/build/standard-fonts/Times.js +27 -0
  17. package/build/standard-fonts/ZapfDingbats.js +21 -0
  18. package/build/vfs_fonts.js +6 -0
  19. package/build-vfs.js +44 -0
  20. package/fonts/Roboto/Roboto-Italic.ttf +0 -0
  21. package/fonts/Roboto/Roboto-Medium.ttf +0 -0
  22. package/fonts/Roboto/Roboto-MediumItalic.ttf +0 -0
  23. package/fonts/Roboto/Roboto-Regular.ttf +0 -0
  24. package/fonts/Roboto.js +8 -0
  25. package/js/3rd-party/svg-to-pdfkit/source.js +3823 -0
  26. package/js/3rd-party/svg-to-pdfkit.js +7 -0
  27. package/js/DocMeasure.js +675 -0
  28. package/js/DocPreprocessor.js +258 -0
  29. package/js/DocumentContext.js +310 -0
  30. package/js/ElementWriter.js +399 -0
  31. package/js/LayoutBuilder.js +1202 -0
  32. package/js/Line.js +101 -0
  33. package/js/OutputDocument.js +64 -0
  34. package/js/OutputDocumentServer.js +29 -0
  35. package/js/PDFDocument.js +145 -0
  36. package/js/PageElementWriter.js +164 -0
  37. package/js/PageSize.js +74 -0
  38. package/js/Printer.js +288 -0
  39. package/js/Renderer.js +513 -0
  40. package/js/SVGMeasure.js +92 -0
  41. package/js/StyleContextStack.js +191 -0
  42. package/js/TableProcessor.js +562 -0
  43. package/js/TextBreaker.js +179 -0
  44. package/js/TextDecorator.js +152 -0
  45. package/js/TextInlines.js +212 -0
  46. package/js/URLResolver.js +43 -0
  47. package/js/base.js +59 -0
  48. package/js/browser-extensions/OutputDocumentBrowser.js +82 -0
  49. package/js/browser-extensions/fonts/Roboto.js +38 -0
  50. package/js/browser-extensions/index.js +53 -0
  51. package/js/browser-extensions/pdfMake.js +3 -0
  52. package/js/browser-extensions/standard-fonts/Courier.js +38 -0
  53. package/js/browser-extensions/standard-fonts/Helvetica.js +38 -0
  54. package/js/browser-extensions/standard-fonts/Symbol.js +23 -0
  55. package/js/browser-extensions/standard-fonts/Times.js +38 -0
  56. package/js/browser-extensions/standard-fonts/ZapfDingbats.js +23 -0
  57. package/js/browser-extensions/virtual-fs-cjs.js +3 -0
  58. package/js/columnCalculator.js +148 -0
  59. package/js/helpers/node.js +122 -0
  60. package/js/helpers/tools.js +46 -0
  61. package/js/helpers/variableType.js +59 -0
  62. package/js/index.js +15 -0
  63. package/js/qrEnc.js +721 -0
  64. package/js/standardPageSizes.js +56 -0
  65. package/js/tableLayouts.js +98 -0
  66. package/js/virtual-fs.js +60 -0
  67. package/package.json +94 -0
  68. package/src/3rd-party/svg-to-pdfkit/LICENSE +9 -0
  69. package/src/3rd-party/svg-to-pdfkit/source.js +2745 -0
  70. package/src/3rd-party/svg-to-pdfkit.js +3 -0
  71. package/src/DocMeasure.js +768 -0
  72. package/src/DocPreprocessor.js +289 -0
  73. package/src/DocumentContext.js +345 -0
  74. package/src/ElementWriter.js +468 -0
  75. package/src/LayoutBuilder.js +1366 -0
  76. package/src/Line.js +108 -0
  77. package/src/OutputDocument.js +64 -0
  78. package/src/OutputDocumentServer.js +32 -0
  79. package/src/PDFDocument.js +178 -0
  80. package/src/PageElementWriter.js +191 -0
  81. package/src/PageSize.js +53 -0
  82. package/src/Printer.js +306 -0
  83. package/src/Renderer.js +546 -0
  84. package/src/SVGMeasure.js +109 -0
  85. package/src/StyleContextStack.js +208 -0
  86. package/src/TableProcessor.js +620 -0
  87. package/src/TextBreaker.js +181 -0
  88. package/src/TextDecorator.js +175 -0
  89. package/src/TextInlines.js +229 -0
  90. package/src/URLResolver.js +43 -0
  91. package/src/base.js +70 -0
  92. package/src/browser-extensions/OutputDocumentBrowser.js +80 -0
  93. package/src/browser-extensions/fonts/Roboto.js +27 -0
  94. package/src/browser-extensions/index.js +55 -0
  95. package/src/browser-extensions/pdfMake.js +1 -0
  96. package/src/browser-extensions/standard-fonts/Courier.js +27 -0
  97. package/src/browser-extensions/standard-fonts/Helvetica.js +27 -0
  98. package/src/browser-extensions/standard-fonts/Symbol.js +21 -0
  99. package/src/browser-extensions/standard-fonts/Times.js +27 -0
  100. package/src/browser-extensions/standard-fonts/ZapfDingbats.js +21 -0
  101. package/src/browser-extensions/virtual-fs-cjs.js +1 -0
  102. package/src/columnCalculator.js +154 -0
  103. package/src/helpers/node.js +134 -0
  104. package/src/helpers/tools.js +44 -0
  105. package/src/helpers/variableType.js +50 -0
  106. package/src/index.js +16 -0
  107. package/src/qrEnc.js +796 -0
  108. package/src/standardPageSizes.js +52 -0
  109. package/src/tableLayouts.js +100 -0
  110. package/src/virtual-fs.js +66 -0
  111. package/standard-fonts/Courier.js +8 -0
  112. package/standard-fonts/Helvetica.js +8 -0
  113. package/standard-fonts/Symbol.js +5 -0
  114. package/standard-fonts/Times.js +8 -0
  115. package/standard-fonts/ZapfDingbats.js +5 -0
@@ -0,0 +1,1366 @@
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 { offsetVector, convertToDynamicContent } from './helpers/tools';
11
+ import TextInlines from './TextInlines';
12
+ import StyleContextStack from './StyleContextStack';
13
+
14
+ function addAll(target, otherArray) {
15
+ otherArray.forEach(item => {
16
+ target.push(item);
17
+ });
18
+ }
19
+
20
+ /**
21
+ * Layout engine which turns document-definition-object into a set of pages, lines, inlines
22
+ * and vectors ready to be rendered into a PDF
23
+ */
24
+ class LayoutBuilder {
25
+ /**
26
+ * @param {object} pageSize - an object defining page width and height
27
+ * @param {object} pageMargins - an object defining top, left, right and bottom margins
28
+ * @param {object} svgMeasure
29
+ */
30
+ constructor(pageSize, pageMargins, svgMeasure) {
31
+ this.pageSize = pageSize;
32
+ this.pageMargins = pageMargins;
33
+ this.svgMeasure = svgMeasure;
34
+ this.tableLayouts = {};
35
+ this.nestedLevel = 0;
36
+ this.verticalAlignmentItemStack = [];
37
+ }
38
+
39
+ registerTableLayouts(tableLayouts) {
40
+ this.tableLayouts = { ...this.tableLayouts, ...tableLayouts };// pack(this.tableLayouts, tableLayouts);
41
+ }
42
+
43
+ /**
44
+ * Executes layout engine on document-definition-object and creates an array of pages
45
+ * containing positioned Blocks, Lines and inlines
46
+ *
47
+ * @param {object} docStructure document-definition-object
48
+ * @param {object} pdfDocument pdfkit document
49
+ * @param {object} styleDictionary dictionary with style definitions
50
+ * @param {object} defaultStyle default style definition
51
+ * @param {object} background
52
+ * @param {object} header
53
+ * @param {object} footer
54
+ * @param {object} watermark
55
+ * @param {object} pageBreakBeforeFct
56
+ * @returns {Array} an array of pages
57
+ */
58
+ layoutDocument(
59
+ docStructure,
60
+ pdfDocument,
61
+ styleDictionary,
62
+ defaultStyle,
63
+ background,
64
+ header,
65
+ footer,
66
+ watermark,
67
+ pageBreakBeforeFct
68
+ ) {
69
+
70
+ function addPageBreaksIfNecessary(linearNodeList, pages) {
71
+
72
+ if (typeof pageBreakBeforeFct !== 'function') {
73
+ return false;
74
+ }
75
+
76
+ const hasRenderableContent = node => {
77
+ if (!node || node.positions.length === 0) {
78
+ return false;
79
+ }
80
+ if (node.text === '' && !node.listMarker) {
81
+ return false;
82
+ }
83
+ return true;
84
+ };
85
+
86
+ linearNodeList = linearNodeList.filter(hasRenderableContent);
87
+
88
+ linearNodeList.forEach(node => {
89
+ let nodeInfo = {};
90
+ [
91
+ 'id', 'text', 'ul', 'ol', 'table', 'image', 'qr', 'canvas', 'svg', 'columns',
92
+ 'headlineLevel', 'style', 'pageBreak', 'pageOrientation', 'acroForm', 'type', 'options',
93
+ 'width', 'height'
94
+ ].forEach(key => {
95
+ if (node[key] !== undefined) {
96
+ nodeInfo[key] = node[key];
97
+ }
98
+ });
99
+ nodeInfo.startPosition = node.positions[0];
100
+ nodeInfo.pageNumbers = Array.from(new Set(node.positions.map(node => node.pageNumber)));
101
+ nodeInfo.pages = pages.length;
102
+ nodeInfo.stack = Array.isArray(node.stack);
103
+
104
+ node.nodeInfo = nodeInfo;
105
+ });
106
+
107
+ for (let index = 0; index < linearNodeList.length; index++) {
108
+ let node = linearNodeList[index];
109
+ if (node.pageBreak !== 'before' && !node.pageBreakCalculated) {
110
+ node.pageBreakCalculated = true;
111
+ let pageNumber = node.nodeInfo.pageNumbers[0];
112
+
113
+ if (
114
+ pageBreakBeforeFct(node.nodeInfo, {
115
+ getFollowingNodesOnPage: () => {
116
+ let followingNodesOnPage = [];
117
+ for (let ii = index + 1, l = linearNodeList.length; ii < l; ii++) {
118
+ if (linearNodeList[ii].nodeInfo.pageNumbers.indexOf(pageNumber) > -1) {
119
+ followingNodesOnPage.push(linearNodeList[ii].nodeInfo);
120
+ }
121
+ }
122
+ return followingNodesOnPage;
123
+ },
124
+ getNodesOnNextPage: () => {
125
+ let nodesOnNextPage = [];
126
+ for (let ii = index + 1, l = linearNodeList.length; ii < l; ii++) {
127
+ if (linearNodeList[ii].nodeInfo.pageNumbers.indexOf(pageNumber + 1) > -1) {
128
+ nodesOnNextPage.push(linearNodeList[ii].nodeInfo);
129
+ }
130
+ }
131
+ return nodesOnNextPage;
132
+ },
133
+ getPreviousNodesOnPage: () => {
134
+ let previousNodesOnPage = [];
135
+ for (let ii = 0; ii < index; ii++) {
136
+ if (linearNodeList[ii].nodeInfo.pageNumbers.indexOf(pageNumber) > -1) {
137
+ previousNodesOnPage.push(linearNodeList[ii].nodeInfo);
138
+ }
139
+ }
140
+ return previousNodesOnPage;
141
+ },
142
+ })
143
+ ) {
144
+ node.pageBreak = 'before';
145
+ return true;
146
+ }
147
+ }
148
+ }
149
+
150
+ return false;
151
+ }
152
+
153
+ this.docPreprocessor = new DocPreprocessor();
154
+ this.docMeasure = new DocMeasure(pdfDocument, styleDictionary, defaultStyle, this.svgMeasure, this.tableLayouts);
155
+
156
+ function resetXYs(result) {
157
+ result.linearNodeList.forEach(node => {
158
+ node.resetXY();
159
+ });
160
+ }
161
+
162
+ let result = this.tryLayoutDocument(docStructure, pdfDocument, styleDictionary, defaultStyle, background, header, footer, watermark);
163
+ while (addPageBreaksIfNecessary(result.linearNodeList, result.pages)) {
164
+ resetXYs(result);
165
+ result = this.tryLayoutDocument(docStructure, pdfDocument, styleDictionary, defaultStyle, background, header, footer, watermark);
166
+ }
167
+
168
+ return result.pages;
169
+ }
170
+
171
+ tryLayoutDocument(
172
+ docStructure,
173
+ pdfDocument,
174
+ styleDictionary,
175
+ defaultStyle,
176
+ background,
177
+ header,
178
+ footer,
179
+ watermark
180
+ ) {
181
+
182
+ const isNecessaryAddFirstPage = (docStructure) => {
183
+ if (docStructure.stack && docStructure.stack.length > 0 && docStructure.stack[0].section) {
184
+ return false;
185
+ } else if (docStructure.section) {
186
+ return false;
187
+ }
188
+
189
+ return true;
190
+ };
191
+
192
+ this.linearNodeList = [];
193
+ docStructure = this.docPreprocessor.preprocessDocument(docStructure);
194
+ docStructure = this.docMeasure.measureDocument(docStructure);
195
+
196
+ this.writer = new PageElementWriter(new DocumentContext());
197
+
198
+ this.writer.context().addListener('pageAdded', (page) => {
199
+ let backgroundGetter = background;
200
+ if (page.customProperties['background'] || page.customProperties['background'] === null) {
201
+ backgroundGetter = page.customProperties['background'];
202
+ }
203
+
204
+ this.addBackground(backgroundGetter);
205
+ });
206
+
207
+ if (isNecessaryAddFirstPage(docStructure)) {
208
+ this.writer.addPage(
209
+ this.pageSize,
210
+ null,
211
+ this.pageMargins
212
+ );
213
+ }
214
+
215
+ this.processNode(docStructure);
216
+ this.addHeadersAndFooters(header, footer);
217
+ this.addWatermark(watermark, pdfDocument, defaultStyle);
218
+
219
+ return { pages: this.writer.context().pages, linearNodeList: this.linearNodeList };
220
+ }
221
+
222
+ addBackground(background) {
223
+ let backgroundGetter = typeof background === 'function' ? background : () => background;
224
+
225
+ let context = this.writer.context();
226
+ let pageSize = context.getCurrentPage().pageSize;
227
+
228
+ let pageBackground = backgroundGetter(context.page + 1, pageSize);
229
+
230
+ if (pageBackground) {
231
+ this.writer.beginUnbreakableBlock(pageSize.width, pageSize.height);
232
+ pageBackground = this.docPreprocessor.preprocessBlock(pageBackground);
233
+ this.processNode(this.docMeasure.measureBlock(pageBackground));
234
+ this.writer.commitUnbreakableBlock(0, 0);
235
+ context.backgroundLength[context.page] += pageBackground.positions.length;
236
+ }
237
+ }
238
+
239
+ addDynamicRepeatable(nodeGetter, sizeFunction, customPropertyName) {
240
+ let pages = this.writer.context().pages;
241
+
242
+ for (let pageIndex = 0, l = pages.length; pageIndex < l; pageIndex++) {
243
+ this.writer.context().page = pageIndex;
244
+
245
+ let customProperties = this.writer.context().getCurrentPage().customProperties;
246
+
247
+ let pageNodeGetter = nodeGetter;
248
+ if (customProperties[customPropertyName] || customProperties[customPropertyName] === null) {
249
+ pageNodeGetter = customProperties[customPropertyName];
250
+ }
251
+
252
+ if ((typeof pageNodeGetter === 'undefined') || (pageNodeGetter === null)) {
253
+ continue;
254
+ }
255
+
256
+ let node = pageNodeGetter(pageIndex + 1, l, this.writer.context().pages[pageIndex].pageSize);
257
+
258
+ if (node) {
259
+ let sizes = sizeFunction(this.writer.context().getCurrentPage().pageSize, this.writer.context().getCurrentPage().pageMargins);
260
+ this.writer.beginUnbreakableBlock(sizes.width, sizes.height);
261
+ node = this.docPreprocessor.preprocessBlock(node);
262
+ this.processNode(this.docMeasure.measureBlock(node));
263
+ this.writer.commitUnbreakableBlock(sizes.x, sizes.y);
264
+ }
265
+ }
266
+ }
267
+
268
+ addHeadersAndFooters(header, footer) {
269
+ const headerSizeFct = (pageSize, pageMargins) => ({
270
+ x: 0,
271
+ y: 0,
272
+ width: pageSize.width,
273
+ height: pageMargins.top
274
+ });
275
+
276
+ const footerSizeFct = (pageSize, pageMargins) => ({
277
+ x: 0,
278
+ y: pageSize.height - pageMargins.bottom,
279
+ width: pageSize.width,
280
+ height: pageMargins.bottom
281
+ });
282
+
283
+ this.addDynamicRepeatable(header, headerSizeFct, 'header');
284
+ this.addDynamicRepeatable(footer, footerSizeFct, 'footer');
285
+ }
286
+
287
+ addWatermark(watermark, pdfDocument, defaultStyle) {
288
+ let pages = this.writer.context().pages;
289
+ for (let i = 0, l = pages.length; i < l; i++) {
290
+ let pageWatermark = watermark;
291
+ if (pages[i].customProperties['watermark'] || pages[i].customProperties['watermark'] === null) {
292
+ pageWatermark = pages[i].customProperties['watermark'];
293
+ }
294
+
295
+ if (pageWatermark === undefined || pageWatermark === null) {
296
+ continue;
297
+ }
298
+
299
+ if (isString(pageWatermark)) {
300
+ pageWatermark = { 'text': pageWatermark };
301
+ }
302
+
303
+ if (!pageWatermark.text) { // empty watermark text
304
+ continue;
305
+ }
306
+
307
+ pages[i].watermark = getWatermarkObject({ ...pageWatermark }, pages[i].pageSize, pdfDocument, defaultStyle);
308
+ }
309
+
310
+ function getWatermarkObject(watermark, pageSize, pdfDocument, defaultStyle) {
311
+ watermark.font = watermark.font || defaultStyle.font || 'Roboto';
312
+ watermark.fontSize = watermark.fontSize || 'auto';
313
+ watermark.color = watermark.color || 'black';
314
+ watermark.opacity = isNumber(watermark.opacity) ? watermark.opacity : 0.6;
315
+ watermark.bold = watermark.bold || false;
316
+ watermark.italics = watermark.italics || false;
317
+ watermark.angle = isValue(watermark.angle) ? watermark.angle : null;
318
+
319
+ if (watermark.angle === null) {
320
+ watermark.angle = Math.atan2(pageSize.height, pageSize.width) * -180 / Math.PI;
321
+ }
322
+
323
+ if (watermark.fontSize === 'auto') {
324
+ watermark.fontSize = getWatermarkFontSize(pageSize, watermark, pdfDocument);
325
+ }
326
+
327
+ let watermarkObject = {
328
+ text: watermark.text,
329
+ font: pdfDocument.provideFont(watermark.font, watermark.bold, watermark.italics),
330
+ fontSize: watermark.fontSize,
331
+ color: watermark.color,
332
+ opacity: watermark.opacity,
333
+ angle: watermark.angle
334
+ };
335
+
336
+ watermarkObject._size = getWatermarkSize(watermark, pdfDocument);
337
+
338
+ return watermarkObject;
339
+ }
340
+
341
+ function getWatermarkSize(watermark, pdfDocument) {
342
+ let textInlines = new TextInlines(pdfDocument);
343
+ let styleContextStack = new StyleContextStack(null, { font: watermark.font, bold: watermark.bold, italics: watermark.italics });
344
+
345
+ styleContextStack.push({
346
+ fontSize: watermark.fontSize
347
+ });
348
+
349
+ let size = textInlines.sizeOfText(watermark.text, styleContextStack);
350
+ let rotatedSize = textInlines.sizeOfRotatedText(watermark.text, watermark.angle, styleContextStack);
351
+
352
+ return { size: size, rotatedSize: rotatedSize };
353
+ }
354
+
355
+ function getWatermarkFontSize(pageSize, watermark, pdfDocument) {
356
+ let textInlines = new TextInlines(pdfDocument);
357
+ let styleContextStack = new StyleContextStack(null, { font: watermark.font, bold: watermark.bold, italics: watermark.italics });
358
+ let rotatedSize;
359
+
360
+ /**
361
+ * Binary search the best font size.
362
+ * Initial bounds [0, 1000]
363
+ * Break when range < 1
364
+ */
365
+ let a = 0;
366
+ let b = 1000;
367
+ let c = (a + b) / 2;
368
+ while (Math.abs(a - b) > 1) {
369
+ styleContextStack.push({
370
+ fontSize: c
371
+ });
372
+ rotatedSize = textInlines.sizeOfRotatedText(watermark.text, watermark.angle, styleContextStack);
373
+
374
+ if (rotatedSize.width > pageSize.width) {
375
+ b = c;
376
+ c = (a + b) / 2;
377
+ } else if (rotatedSize.width < pageSize.width) {
378
+ if (rotatedSize.height > pageSize.height) {
379
+ b = c;
380
+ c = (a + b) / 2;
381
+ } else {
382
+ a = c;
383
+ c = (a + b) / 2;
384
+ }
385
+ }
386
+ styleContextStack.pop();
387
+ }
388
+ /*
389
+ End binary search
390
+ */
391
+ return c;
392
+ }
393
+ }
394
+
395
+ processNode(node, isVerticalAlignmentAllowed = false) {
396
+ const applyMargins = callback => {
397
+ let margin = node._margin;
398
+
399
+ if (node.pageBreak === 'before') {
400
+ this.writer.moveToNextPage(node.pageOrientation);
401
+ } else if (node.pageBreak === 'beforeOdd') {
402
+ this.writer.moveToNextPage(node.pageOrientation);
403
+ if ((this.writer.context().page + 1) % 2 === 1) {
404
+ this.writer.moveToNextPage(node.pageOrientation);
405
+ }
406
+ } else if (node.pageBreak === 'beforeEven') {
407
+ this.writer.moveToNextPage(node.pageOrientation);
408
+ if ((this.writer.context().page + 1) % 2 === 0) {
409
+ this.writer.moveToNextPage(node.pageOrientation);
410
+ }
411
+ }
412
+
413
+ const isDetachedBlock = node.relativePosition || node.absolutePosition;
414
+
415
+ // Detached nodes have no margins, their position is only determined by 'x' and 'y'
416
+ if (margin && !isDetachedBlock) {
417
+ const availableHeight = this.writer.context().availableHeight;
418
+ // If top margin is bigger than available space, move to next page
419
+ // Necessary for nodes inside tables
420
+ if (availableHeight - margin[1] < 0) {
421
+ // Consume the whole available space
422
+ this.writer.context().moveDown(availableHeight);
423
+ this.writer.moveToNextPage(node.pageOrientation);
424
+ /**
425
+ * TODO - Something to consider:
426
+ * Right now the node starts at the top of next page (after header)
427
+ * Another option would be to apply just the top margin that has not been consumed in the page before
428
+ * It would something like: this.write.context().moveDown(margin[1] - availableHeight)
429
+ */
430
+ } else {
431
+ this.writer.context().moveDown(margin[1]);
432
+ }
433
+ // Apply lateral margins
434
+ this.writer.context().addMargin(margin[0], margin[2]);
435
+ }
436
+ callback();
437
+
438
+ // Detached nodes have no margins, their position is only determined by 'x' and 'y'
439
+ if (margin && !isDetachedBlock) {
440
+ const availableHeight = this.writer.context().availableHeight;
441
+ // If bottom margin is bigger than available space, move to next page
442
+ // Necessary for nodes inside tables
443
+ if (availableHeight - margin[3] < 0) {
444
+ this.writer.context().moveDown(availableHeight);
445
+ this.writer.moveToNextPage(node.pageOrientation);
446
+ /**
447
+ * TODO - Something to consider:
448
+ * Right now next node starts at the top of next page (after header)
449
+ * Another option would be to apply the bottom margin that has not been consumed in the next page?
450
+ * It would something like: this.write.context().moveDown(margin[3] - availableHeight)
451
+ */
452
+ } else {
453
+ this.writer.context().moveDown(margin[3]);
454
+ }
455
+ // Apply lateral margins
456
+ this.writer.context().addMargin(-margin[0], -margin[2]);
457
+ }
458
+
459
+ if (node.pageBreak === 'after') {
460
+ this.writer.moveToNextPage(node.pageOrientation);
461
+ } else if (node.pageBreak === 'afterOdd') {
462
+ this.writer.moveToNextPage(node.pageOrientation);
463
+ if ((this.writer.context().page + 1) % 2 === 1) {
464
+ this.writer.moveToNextPage(node.pageOrientation);
465
+ }
466
+ } else if (node.pageBreak === 'afterEven') {
467
+ this.writer.moveToNextPage(node.pageOrientation);
468
+ if ((this.writer.context().page + 1) % 2 === 0) {
469
+ this.writer.moveToNextPage(node.pageOrientation);
470
+ }
471
+ }
472
+ };
473
+
474
+ this.linearNodeList.push(node);
475
+ decorateNode(node);
476
+
477
+ if (this.writer.context().getCurrentPage() !== null) {
478
+ var prevTop = this.writer.context().getCurrentPosition().top;
479
+ }
480
+
481
+ applyMargins(() => {
482
+ let verticalAlignment = node.verticalAlignment;
483
+ if (isVerticalAlignmentAllowed && verticalAlignment) {
484
+ var verticalAlignmentBegin = this.writer.beginVerticalAlignment(verticalAlignment);
485
+ }
486
+
487
+ let unbreakable = node.unbreakable;
488
+ if (unbreakable) {
489
+ this.writer.beginUnbreakableBlock();
490
+ }
491
+
492
+ let absPosition = node.absolutePosition;
493
+ if (absPosition) {
494
+ this.writer.context().beginDetachedBlock();
495
+ this.writer.context().moveTo(absPosition.x || 0, absPosition.y || 0);
496
+ }
497
+
498
+ let relPosition = node.relativePosition;
499
+ if (relPosition) {
500
+ this.writer.context().beginDetachedBlock();
501
+ this.writer.context().moveToRelative(relPosition.x || 0, relPosition.y || 0);
502
+ }
503
+
504
+ if (node.stack) {
505
+ this.processVerticalContainer(node);
506
+ } else if (node.section) {
507
+ this.processSection(node);
508
+ } else if (node.columns) {
509
+ this.processColumns(node);
510
+ } else if (node.ul) {
511
+ this.processList(false, node);
512
+ } else if (node.ol) {
513
+ this.processList(true, node);
514
+ } else if (node.table) {
515
+ this.processTable(node);
516
+ } else if (node.text !== undefined) {
517
+ this.processLeaf(node);
518
+ } else if (node.toc) {
519
+ this.processToc(node);
520
+ } else if (node.image) {
521
+ this.processImage(node);
522
+ } else if (node.svg) {
523
+ this.processSVG(node);
524
+ } else if (node.canvas) {
525
+ this.processCanvas(node);
526
+ } else if (node.qr) {
527
+ this.processQr(node);
528
+ } else if (node.attachment) {
529
+ this.processAttachment(node);
530
+ } else if (node.acroform) {
531
+ this.processAcroForm(node);
532
+ } else if (!node._span) {
533
+ throw new Error(`Unrecognized document structure: ${stringifyNode(node)}`);
534
+ }
535
+
536
+ if (absPosition || relPosition) {
537
+ this.writer.context().endDetachedBlock();
538
+ }
539
+
540
+ if (unbreakable) {
541
+ this.writer.commitUnbreakableBlock();
542
+ }
543
+
544
+ if (isVerticalAlignmentAllowed && verticalAlignment) {
545
+ this.verticalAlignmentItemStack.push({
546
+ begin: verticalAlignmentBegin,
547
+ end: this.writer.endVerticalAlignment(verticalAlignment)
548
+ });
549
+ }
550
+ });
551
+
552
+ if (prevTop !== undefined) {
553
+ // TODO: for vertical alignment and does not work (at least) when page break in node
554
+ node.__height = this.writer.context().getCurrentPosition().top - prevTop;
555
+ }
556
+ }
557
+
558
+ // vertical container
559
+ processVerticalContainer(node) {
560
+ node.stack.forEach(item => {
561
+ this.processNode(item);
562
+ addAll(node.positions, item.positions);
563
+
564
+ //TODO: paragraph gap
565
+ }, this);
566
+ }
567
+
568
+ // section
569
+ processSection(sectionNode) {
570
+ // TODO: properties
571
+
572
+ let page = this.writer.context().getCurrentPage();
573
+ if (!page || (page && page.items.length)) { // move to new empty page
574
+ // page definition inherit from current page
575
+ if (sectionNode.pageSize === 'inherit') {
576
+ sectionNode.pageSize = page ? { width: page.pageSize.width, height: page.pageSize.height } : undefined;
577
+ }
578
+ if (sectionNode.pageOrientation === 'inherit') {
579
+ sectionNode.pageOrientation = page ? page.pageSize.orientation : undefined;
580
+ }
581
+ if (sectionNode.pageMargins === 'inherit') {
582
+ sectionNode.pageMargins = page ? page.pageMargins : undefined;
583
+ }
584
+
585
+ if (sectionNode.header === 'inherit') {
586
+ sectionNode.header = page ? page.customProperties.header : undefined;
587
+ }
588
+
589
+ if (sectionNode.footer === 'inherit') {
590
+ sectionNode.footer = page ? page.customProperties.footer : undefined;
591
+ }
592
+
593
+ if (sectionNode.background === 'inherit') {
594
+ sectionNode.background = page ? page.customProperties.background : undefined;
595
+ }
596
+
597
+ if (sectionNode.watermark === 'inherit') {
598
+ sectionNode.watermark = page ? page.customProperties.watermark : undefined;
599
+ }
600
+
601
+ if (sectionNode.header && typeof sectionNode.header !== 'function' && sectionNode.header !== null) {
602
+ sectionNode.header = convertToDynamicContent(sectionNode.header);
603
+ }
604
+
605
+ if (sectionNode.footer && typeof sectionNode.footer !== 'function' && sectionNode.footer !== null) {
606
+ sectionNode.footer = convertToDynamicContent(sectionNode.footer);
607
+ }
608
+
609
+ let customProperties = {};
610
+ if (typeof sectionNode.header !== 'undefined') {
611
+ customProperties.header = sectionNode.header;
612
+ }
613
+
614
+ if (typeof sectionNode.footer !== 'undefined') {
615
+ customProperties.footer = sectionNode.footer;
616
+ }
617
+
618
+ if (typeof sectionNode.background !== 'undefined') {
619
+ customProperties.background = sectionNode.background;
620
+ }
621
+
622
+ if (typeof sectionNode.watermark !== 'undefined') {
623
+ customProperties.watermark = sectionNode.watermark;
624
+ }
625
+
626
+ this.writer.addPage(
627
+ sectionNode.pageSize || this.pageSize,
628
+ sectionNode.pageOrientation,
629
+ sectionNode.pageMargins || this.pageMargins,
630
+ customProperties
631
+ );
632
+ }
633
+
634
+ this.processNode(sectionNode.section);
635
+ }
636
+
637
+ // columns
638
+ processColumns(columnNode) {
639
+ this.nestedLevel++;
640
+ let columns = columnNode.columns;
641
+ let availableWidth = this.writer.context().availableWidth;
642
+ let gaps = gapArray(columnNode._gap);
643
+
644
+ if (gaps) {
645
+ availableWidth -= (gaps.length - 1) * columnNode._gap;
646
+ }
647
+
648
+ ColumnCalculator.buildColumnWidths(columns, availableWidth);
649
+ let result = this.processRow({
650
+ marginX: columnNode._margin ? [columnNode._margin[0], columnNode._margin[2]] : [0, 0],
651
+ cells: columns,
652
+ widths: columns,
653
+ gaps
654
+ });
655
+ addAll(columnNode.positions, result.positions);
656
+ this.nestedLevel--;
657
+ if (this.nestedLevel === 0) {
658
+ this.writer.context().resetMarginXTopParent();
659
+ }
660
+ function gapArray(gap) {
661
+ if (!gap) {
662
+ return null;
663
+ }
664
+
665
+ let gaps = [];
666
+ gaps.push(0);
667
+
668
+ for (let i = columns.length - 1; i > 0; i--) {
669
+ gaps.push(gap);
670
+ }
671
+
672
+ return gaps;
673
+ }
674
+ }
675
+
676
+ /**
677
+ * Searches for a cell in the same row that starts a rowspan and is positioned immediately before the current cell.
678
+ * Alternatively, it finds a cell where the colspan initiating the rowspan extends to the cell just before the current one.
679
+ *
680
+ * @param {Array<object>} arr - An array representing cells in a row.
681
+ * @param {number} i - The index of the current cell to search backward from.
682
+ * @returns {object|null} The starting cell of the rowspan if found; otherwise, `null`.
683
+ */
684
+ _findStartingRowSpanCell(arr, i) {
685
+ let requiredColspan = 1;
686
+ for (let index = i - 1; index >= 0; index--) {
687
+ if (!arr[index]._span) {
688
+ if (arr[index].rowSpan > 1 && (arr[index].colSpan || 1) === requiredColspan) {
689
+ return arr[index];
690
+ } else {
691
+ return null;
692
+ }
693
+ }
694
+ requiredColspan++;
695
+ }
696
+ return null;
697
+ }
698
+
699
+ /**
700
+ * Retrieves a page break description for a specified page from a list of page breaks.
701
+ *
702
+ * @param {Array<object>} pageBreaks - An array of page break descriptions, each containing `prevPage` properties.
703
+ * @param {number} page - The page number to find the associated page break for.
704
+ * @returns {object|undefined} The page break description object for the specified page if found; otherwise, `undefined`.
705
+ */
706
+ _getPageBreak(pageBreaks, page) {
707
+ return pageBreaks.find(desc => desc.prevPage === page);
708
+ }
709
+
710
+ _getPageBreakListBySpan(tableNode, page, rowIndex) {
711
+ if (!tableNode || !tableNode._breaksBySpan) {
712
+ return null;
713
+ }
714
+ const breaksList = tableNode._breaksBySpan.filter(desc => desc.prevPage === page && rowIndex <= desc.rowIndexOfSpanEnd);
715
+
716
+ let y = Number.MAX_VALUE,
717
+ prevY = Number.MIN_VALUE;
718
+
719
+ breaksList.forEach(b => {
720
+ prevY = Math.max(b.prevY, prevY);
721
+ y = Math.min(b.y, y);
722
+ });
723
+
724
+ return {
725
+ prevPage: page,
726
+ prevY: prevY,
727
+ y: y
728
+ };
729
+ }
730
+
731
+ _findSameRowPageBreakByRowSpanData(breaksBySpan, page, rowIndex) {
732
+ if (!breaksBySpan) {
733
+ return null;
734
+ }
735
+ return breaksBySpan.find(desc => desc.prevPage === page && rowIndex === desc.rowIndexOfSpanEnd);
736
+ }
737
+
738
+ _updatePageBreaksData(pageBreaks, tableNode, rowIndex) {
739
+ Object.keys(tableNode._bottomByPage).forEach(p => {
740
+ const page = Number(p);
741
+ const pageBreak = this._getPageBreak(pageBreaks, page);
742
+ if (pageBreak) {
743
+ pageBreak.prevY = Math.max(pageBreak.prevY, tableNode._bottomByPage[page]);
744
+ }
745
+ if (tableNode._breaksBySpan && tableNode._breaksBySpan.length > 0) {
746
+ const breaksBySpanList = tableNode._breaksBySpan.filter(pb => pb.prevPage === page && rowIndex <= pb.rowIndexOfSpanEnd);
747
+
748
+ if (breaksBySpanList && breaksBySpanList.length > 0) {
749
+ breaksBySpanList.forEach(b => {
750
+ b.prevY = Math.max(b.prevY, tableNode._bottomByPage[page]);
751
+ });
752
+ }
753
+ }
754
+ });
755
+ }
756
+
757
+ /**
758
+ * Resolves the Y-coordinates for a target object by comparing two break points.
759
+ *
760
+ * @param {object} break1 - The first break point with `prevY` and `y` properties.
761
+ * @param {object} break2 - The second break point with `prevY` and `y` properties.
762
+ * @param {object} target - The target object to be updated with resolved Y-coordinates.
763
+ * @property {number} target.prevY - Updated to the maximum `prevY` value between `break1` and `break2`.
764
+ * @property {number} target.y - Updated to the minimum `y` value between `break1` and `break2`.
765
+ */
766
+ _resolveBreakY(break1, break2, target) {
767
+ target.prevY = Math.max(break1.prevY, break2.prevY);
768
+ target.y = Math.min(break1.y, break2.y);
769
+ };
770
+
771
+ _storePageBreakData(data, startsRowSpan, pageBreaks, tableNode) {
772
+ if (!startsRowSpan) {
773
+ let pageDesc = this._getPageBreak(pageBreaks, data.prevPage);
774
+ let pageDescBySpan = this._getPageBreakListBySpan(tableNode, data.prevPage, data.rowIndex);
775
+ if (!pageDesc) {
776
+ pageDesc = {
777
+ ...data
778
+ };
779
+ pageBreaks.push(pageDesc);
780
+ }
781
+ if (pageDescBySpan) {
782
+ this._resolveBreakY(pageDesc, pageDescBySpan, pageDesc);
783
+ }
784
+ this._resolveBreakY(pageDesc, data, pageDesc);
785
+ } else {
786
+ const breaksBySpan = tableNode && tableNode._breaksBySpan || null;
787
+ let pageDescBySpan = this._findSameRowPageBreakByRowSpanData(breaksBySpan, data.prevPage, data.rowIndex);
788
+ if (!pageDescBySpan) {
789
+ pageDescBySpan = {
790
+ ...data,
791
+ rowIndexOfSpanEnd: data.rowIndex + data.rowSpan - 1
792
+ };
793
+ if (!tableNode._breaksBySpan) {
794
+ tableNode._breaksBySpan = [];
795
+ }
796
+ tableNode._breaksBySpan.push(pageDescBySpan);
797
+ }
798
+ pageDescBySpan.prevY = Math.max(pageDescBySpan.prevY, data.prevY);
799
+ pageDescBySpan.y = Math.min(pageDescBySpan.y, data.y);
800
+ let pageDesc = this._getPageBreak(pageBreaks, data.prevPage);
801
+ if (pageDesc) {
802
+ this._resolveBreakY(pageDesc, pageDescBySpan, pageDesc);
803
+ }
804
+ }
805
+ };
806
+
807
+ /**
808
+ * Calculates the left offset for a column based on the specified gap values.
809
+ *
810
+ * @param {number} i - The index of the column for which the offset is being calculated.
811
+ * @param {Array<number>} gaps - An array of gap values for each column.
812
+ * @returns {number} The left offset for the column. Returns `gaps[i]` if it exists, otherwise `0`.
813
+ */
814
+ _colLeftOffset(i, gaps) {
815
+ if (gaps && gaps.length > i) {
816
+ return gaps[i];
817
+ }
818
+ return 0;
819
+ }
820
+
821
+ /**
822
+ * Retrieves the ending cell for a row span in case it exists in a specified table column.
823
+ *
824
+ * @param {Array<Array<object>>} tableBody - The table body, represented as a 2D array of cell objects.
825
+ * @param {number} rowIndex - The index of the starting row for the row span.
826
+ * @param {object} column - The column object containing row span information.
827
+ * @param {number} columnIndex - The index of the column within the row.
828
+ * @returns {object|null} The cell at the end of the row span if it exists; otherwise, `null`.
829
+ * @throws {Error} If the row span extends beyond the total row count.
830
+ */
831
+ _getRowSpanEndingCell(tableBody, rowIndex, column, columnIndex) {
832
+ if (column.rowSpan && column.rowSpan > 1) {
833
+ let endingRow = rowIndex + column.rowSpan - 1;
834
+ if (endingRow >= tableBody.length) {
835
+ throw new Error(`Row span for column ${columnIndex} (with indexes starting from 0) exceeded row count`);
836
+ }
837
+ return tableBody[endingRow][columnIndex];
838
+ }
839
+
840
+ return null;
841
+ }
842
+
843
+ processRow({ marginX = [0, 0], dontBreakRows = false, rowsWithoutPageBreak = 0, cells, widths, gaps, tableNode, tableBody, rowIndex, height }) {
844
+ const isUnbreakableRow = dontBreakRows || rowIndex <= rowsWithoutPageBreak - 1;
845
+ let pageBreaks = [];
846
+ let pageBreaksByRowSpan = [];
847
+ let positions = [];
848
+ let willBreakByHeight = false;
849
+ let verticalAlignmentCells = {};
850
+ widths = widths || cells;
851
+
852
+ // Check if row should break by height
853
+ if (!isUnbreakableRow && height > this.writer.context().availableHeight) {
854
+ willBreakByHeight = true;
855
+ }
856
+
857
+ // Use the marginX if we are in a top level table/column (not nested)
858
+ const marginXParent = this.nestedLevel === 1 ? marginX : null;
859
+ const _bottomByPage = tableNode ? tableNode._bottomByPage : null;
860
+ this.writer.context().beginColumnGroup(marginXParent, _bottomByPage);
861
+
862
+ for (let i = 0, l = cells.length; i < l; i++) {
863
+ let cell = cells[i];
864
+ let cellIndexBegin = i;
865
+
866
+ // Page change handler
867
+ const storePageBreakClosure = data => {
868
+ const startsRowSpan = cell.rowSpan && cell.rowSpan > 1;
869
+ if (startsRowSpan) {
870
+ data.rowSpan = cell.rowSpan;
871
+ }
872
+ data.rowIndex = rowIndex;
873
+ this._storePageBreakData(data, startsRowSpan, pageBreaks, tableNode);
874
+ };
875
+
876
+ this.writer.addListener('pageChanged', storePageBreakClosure);
877
+
878
+ let width = widths[i]._calcWidth;
879
+ let leftOffset = this._colLeftOffset(i, gaps);
880
+ // Check if exists and retrieve the cell that started the rowspan in case we are in the cell just after
881
+ let startingSpanCell = this._findStartingRowSpanCell(cells, i);
882
+
883
+ if (cell.colSpan && cell.colSpan > 1) {
884
+ for (let j = 1; j < cell.colSpan; j++) {
885
+ width += widths[++i]._calcWidth + gaps[i];
886
+ }
887
+ }
888
+
889
+ // if rowspan starts in this cell, we retrieve the last cell affected by the rowspan
890
+ const rowSpanRightEndingCell = this._getRowSpanEndingCell(tableBody, rowIndex, cell, i);
891
+ const rowSpanLeftEndingCell = this._getRowSpanEndingCell(tableBody, rowIndex, cell, cellIndexBegin);
892
+ if (rowSpanRightEndingCell) {
893
+ // We store a reference of the ending cell in the first cell of the rowspan
894
+ cell._endingCell = rowSpanRightEndingCell;
895
+ cell._endingCell._startingRowSpanY = cell._startingRowSpanY;
896
+ }
897
+ if (rowSpanLeftEndingCell) {
898
+ // We store a reference of the left ending cell in the first cell of the rowspan
899
+ cell._leftEndingCell = rowSpanLeftEndingCell;
900
+ cell._leftEndingCell._startingRowSpanY = cell._startingRowSpanY;
901
+ }
902
+
903
+ // If we are after a cell that started a rowspan
904
+ let endOfRowSpanCell = null;
905
+ if (startingSpanCell && startingSpanCell._endingCell) {
906
+ // Reference to the last cell of the rowspan
907
+ endOfRowSpanCell = startingSpanCell._endingCell;
908
+ // Store if we are in an unbreakable block when we save the context and the originalX
909
+ if (this.writer.transactionLevel > 0) {
910
+ endOfRowSpanCell._isUnbreakableContext = true;
911
+ endOfRowSpanCell._originalXOffset = this.writer.originalX;
912
+ }
913
+ }
914
+
915
+ // We pass the endingSpanCell reference to store the context just after processing rowspan cell
916
+ this.writer.context().beginColumn(width, leftOffset, endOfRowSpanCell);
917
+
918
+ if (!cell._span) {
919
+ this.processNode(cell, true);
920
+ this.writer.context().updateBottomByPage();
921
+
922
+ if (cell.verticalAlignment) {
923
+ verticalAlignmentCells[cellIndexBegin] = this.verticalAlignmentItemStack.length - 1;
924
+ }
925
+
926
+ addAll(positions, cell.positions);
927
+ } else if (cell._columnEndingContext) {
928
+ let discountY = 0;
929
+ if (dontBreakRows) {
930
+ // Calculate how many points we have to discount to Y when dontBreakRows and rowSpan are combined
931
+ const ctxBeforeRowSpanLastRow = this.writer.contextStack[this.writer.contextStack.length - 1];
932
+ discountY = ctxBeforeRowSpanLastRow.y - cell._startingRowSpanY;
933
+ }
934
+ let originalXOffset = 0;
935
+ // If context was saved from an unbreakable block and we are not in an unbreakable block anymore
936
+ // We have to sum the originalX (X before starting unbreakable block) to X
937
+ if (cell._isUnbreakableContext && !this.writer.transactionLevel) {
938
+ originalXOffset = cell._originalXOffset;
939
+ }
940
+ // row-span ending
941
+ // Recover the context after processing the rowspanned cell
942
+ this.writer.context().markEnding(cell, originalXOffset, discountY);
943
+ }
944
+ this.writer.removeListener('pageChanged', storePageBreakClosure);
945
+ }
946
+
947
+ // Check if last cell is part of a span
948
+ let endingSpanCell = null;
949
+ const lastColumn = cells.length > 0 ? cells[cells.length - 1] : null;
950
+ if (lastColumn) {
951
+ // Previous column cell has a rowspan
952
+ if (lastColumn._endingCell) {
953
+ endingSpanCell = lastColumn._endingCell;
954
+ // Previous column cell is part of a span
955
+ } else if (lastColumn._span === true) {
956
+ // We get the cell that started the span where we set a reference to the ending cell
957
+ const startingSpanCell = this._findStartingRowSpanCell(cells, cells.length);
958
+ if (startingSpanCell) {
959
+ // Context will be stored here (ending cell)
960
+ endingSpanCell = startingSpanCell._endingCell;
961
+ // Store if we are in an unbreakable block when we save the context and the originalX
962
+ if (this.writer.transactionLevel > 0) {
963
+ endingSpanCell._isUnbreakableContext = true;
964
+ endingSpanCell._originalXOffset = this.writer.originalX;
965
+ }
966
+ }
967
+ }
968
+ }
969
+
970
+ // If content did not break page, check if we should break by height
971
+ if (willBreakByHeight && !isUnbreakableRow && pageBreaks.length === 0) {
972
+ this.writer.context().moveDown(this.writer.context().availableHeight);
973
+ this.writer.moveToNextPage();
974
+ }
975
+
976
+ const bottomByPage = this.writer.context().completeColumnGroup(height, endingSpanCell);
977
+
978
+ if (tableNode) {
979
+ tableNode._bottomByPage = bottomByPage;
980
+ // If there are page breaks in this row, update data with prevY of last cell
981
+ this._updatePageBreaksData(pageBreaks, tableNode, rowIndex);
982
+ }
983
+
984
+ let rowHeight = this.writer.context().height;
985
+ for (let i = 0, l = cells.length; i < l; i++) {
986
+ let cell = cells[i];
987
+ if (!cell._span && cell.verticalAlignment) {
988
+ let itemBegin = this.verticalAlignmentItemStack[verticalAlignmentCells[i]].begin.item;
989
+ itemBegin.viewHeight = rowHeight;
990
+ itemBegin.nodeHeight = cell.__height;
991
+ itemBegin.cell = cell;
992
+ itemBegin.bottomY = this.writer.context().y;
993
+ itemBegin.isCellContentMultiPage = !itemBegin.cell.positions.every(item => item.pageNumber === itemBegin.cell.positions[0].pageNumber);
994
+ itemBegin.getViewHeight = function() {
995
+ if (this.cell._willBreak) {
996
+ return this.cell._bottomY - this.cell._rowTopPageY;
997
+ }
998
+
999
+ if (this.cell.rowSpan && this.cell.rowSpan > 1) {
1000
+ if (dontBreakRows) {
1001
+ let rowTopPageY = this.cell._leftEndingCell._startingRowSpanY + this.cell._leftEndingCell._rowTopPageYPadding;
1002
+ return this.cell._leftEndingCell._rowTopPageY - rowTopPageY + this.cell._leftEndingCell._bottomY;
1003
+ } else {
1004
+ if (this.cell.positions[0].pageNumber !== this.cell._leftEndingCell._lastPageNumber) {
1005
+ return this.bottomY - this.cell._leftEndingCell._bottomY;
1006
+ }
1007
+
1008
+ return this.viewHeight + this.cell._leftEndingCell._bottomY - this.bottomY;
1009
+ }
1010
+ }
1011
+
1012
+ return this.viewHeight;
1013
+ };
1014
+ itemBegin.getNodeHeight = function() {
1015
+ return this.nodeHeight;
1016
+ };
1017
+
1018
+ let itemEnd = this.verticalAlignmentItemStack[verticalAlignmentCells[i]].end.item;
1019
+ itemEnd.isCellContentMultiPage = itemBegin.isCellContentMultiPage;
1020
+ }
1021
+ }
1022
+
1023
+ return {
1024
+ pageBreaksBySpan: pageBreaksByRowSpan,
1025
+ pageBreaks: pageBreaks,
1026
+ positions: positions
1027
+ };
1028
+ }
1029
+
1030
+ // lists
1031
+ processList(orderedList, node) {
1032
+ const addMarkerToFirstLeaf = line => {
1033
+ // I'm not very happy with the way list processing is implemented
1034
+ // (both code and algorithm should be rethinked)
1035
+ if (nextMarker) {
1036
+ let marker = nextMarker;
1037
+ nextMarker = null;
1038
+
1039
+ if (marker.canvas) {
1040
+ let vector = marker.canvas[0];
1041
+
1042
+ offsetVector(vector, -marker._minWidth, 0);
1043
+ this.writer.addVector(vector);
1044
+ } else if (marker._inlines) {
1045
+ let markerLine = new Line(this.pageSize.width);
1046
+ markerLine.addInline(marker._inlines[0]);
1047
+ markerLine.x = -marker._minWidth;
1048
+ markerLine.y = line.getAscenderHeight() - markerLine.getAscenderHeight();
1049
+ this.writer.addLine(markerLine, true);
1050
+ }
1051
+ }
1052
+ };
1053
+
1054
+ let items = orderedList ? node.ol : node.ul;
1055
+ let gapSize = node._gapSize;
1056
+
1057
+ this.writer.context().addMargin(gapSize.width);
1058
+
1059
+ let nextMarker;
1060
+
1061
+ this.writer.addListener('lineAdded', addMarkerToFirstLeaf);
1062
+
1063
+ items.forEach(item => {
1064
+ nextMarker = item.listMarker;
1065
+ this.processNode(item);
1066
+ addAll(node.positions, item.positions);
1067
+ });
1068
+
1069
+ this.writer.removeListener('lineAdded', addMarkerToFirstLeaf);
1070
+
1071
+ this.writer.context().addMargin(-gapSize.width);
1072
+ }
1073
+
1074
+ // tables
1075
+ processTable(tableNode) {
1076
+ this.nestedLevel++;
1077
+ let processor = new TableProcessor(tableNode);
1078
+
1079
+ processor.beginTable(this.writer);
1080
+
1081
+ let rowHeights = tableNode.table.heights;
1082
+ for (let i = 0, l = tableNode.table.body.length; i < l; i++) {
1083
+ // if dontBreakRows and row starts a rowspan
1084
+ // we store the 'y' of the beginning of each rowSpan
1085
+ if (processor.dontBreakRows) {
1086
+ tableNode.table.body[i].forEach(cell => {
1087
+ if (cell.rowSpan && cell.rowSpan > 1) {
1088
+ cell._startingRowSpanY = this.writer.context().y;
1089
+ }
1090
+ });
1091
+ }
1092
+
1093
+ processor.beginRow(i, this.writer);
1094
+
1095
+ let height;
1096
+ if (typeof rowHeights === 'function') {
1097
+ height = rowHeights(i);
1098
+ } else if (Array.isArray(rowHeights)) {
1099
+ height = rowHeights[i];
1100
+ } else {
1101
+ height = rowHeights;
1102
+ }
1103
+
1104
+ if (height === 'auto') {
1105
+ height = undefined;
1106
+ }
1107
+
1108
+ const pageBeforeProcessing = this.writer.context().page;
1109
+
1110
+ let result = this.processRow({
1111
+ marginX: tableNode._margin ? [tableNode._margin[0], tableNode._margin[2]] : [0, 0],
1112
+ dontBreakRows: processor.dontBreakRows,
1113
+ rowsWithoutPageBreak: processor.rowsWithoutPageBreak,
1114
+ cells: tableNode.table.body[i],
1115
+ widths: tableNode.table.widths,
1116
+ gaps: tableNode._offsets.offsets,
1117
+ tableBody: tableNode.table.body,
1118
+ tableNode,
1119
+ rowIndex: i,
1120
+ height
1121
+ });
1122
+
1123
+ addAll(tableNode.positions, result.positions);
1124
+
1125
+ if (!result.pageBreaks || result.pageBreaks.length === 0) {
1126
+ const breaksBySpan = tableNode && tableNode._breaksBySpan || null;
1127
+ const breakBySpanData = this._findSameRowPageBreakByRowSpanData(breaksBySpan, pageBeforeProcessing, i);
1128
+ if (breakBySpanData) {
1129
+ const finalBreakBySpanData = this._getPageBreakListBySpan(tableNode, breakBySpanData.prevPage, i);
1130
+ result.pageBreaks.push(finalBreakBySpanData);
1131
+ }
1132
+ }
1133
+
1134
+ processor.endRow(i, this.writer, result.pageBreaks);
1135
+ }
1136
+
1137
+ processor.endTable(this.writer);
1138
+ this.nestedLevel--;
1139
+ if (this.nestedLevel === 0) {
1140
+ this.writer.context().resetMarginXTopParent();
1141
+ }
1142
+ }
1143
+
1144
+ // leafs (texts, acroform))
1145
+ processLeaf(node) {
1146
+ let line = this.buildNextLine(node);
1147
+ if (line && (node.tocItem || node.id)) {
1148
+ line._node = node;
1149
+ }
1150
+ let currentHeight = (line) ? line.getHeight() : 0;
1151
+ let maxHeight = node.maxHeight || -1;
1152
+
1153
+ if (line) {
1154
+ let nodeId = getNodeId(node);
1155
+ if (nodeId) {
1156
+ line.id = nodeId;
1157
+ }
1158
+ }
1159
+
1160
+ if (node.outline) {
1161
+ line._outline = {
1162
+ id: node.id,
1163
+ parentId: node.outlineParentId,
1164
+ text: node.outlineText || node.text,
1165
+ expanded: node.outlineExpanded || false
1166
+ };
1167
+ } else if (Array.isArray(node.text)) {
1168
+ for (let i = 0, l = node.text.length; i < l; i++) {
1169
+ let item = node.text[i];
1170
+ if (item.outline) {
1171
+ line._outline = {
1172
+ id: item.id,
1173
+ parentId: item.outlineParentId,
1174
+ text: item.outlineText || item.text,
1175
+ expanded: item.outlineExpanded || false
1176
+ };
1177
+ }
1178
+ }
1179
+ }
1180
+
1181
+ if (node._tocItemRef) {
1182
+ line._pageNodeRef = node._tocItemRef;
1183
+ }
1184
+
1185
+ if (node._pageRef) {
1186
+ line._pageNodeRef = node._pageRef._nodeRef;
1187
+ }
1188
+
1189
+ if (line && line.inlines && Array.isArray(line.inlines)) {
1190
+ for (let i = 0, l = line.inlines.length; i < l; i++) {
1191
+ if (line.inlines[i]._tocItemRef) {
1192
+ line.inlines[i]._pageNodeRef = line.inlines[i]._tocItemRef;
1193
+ }
1194
+
1195
+ if (line.inlines[i]._pageRef) {
1196
+ line.inlines[i]._pageNodeRef = line.inlines[i]._pageRef._nodeRef;
1197
+ }
1198
+ }
1199
+ }
1200
+
1201
+ while (line && (maxHeight === -1 || currentHeight < maxHeight)) {
1202
+ let positions = this.writer.addLine(line);
1203
+ node.positions.push(positions);
1204
+ line = this.buildNextLine(node);
1205
+ if (line) {
1206
+ currentHeight += line.getHeight();
1207
+ }
1208
+ }
1209
+ }
1210
+
1211
+ processToc(node) {
1212
+ if (!node.toc._table && node.toc.hideEmpty === true) {
1213
+ return;
1214
+ }
1215
+
1216
+ if (node.toc.title) {
1217
+ this.processNode(node.toc.title);
1218
+ }
1219
+ if (node.toc._table) {
1220
+ this.processNode(node.toc._table);
1221
+ }
1222
+ }
1223
+
1224
+ buildNextLine(textNode) {
1225
+
1226
+ function cloneInline(inline) {
1227
+ let newInline = inline.constructor();
1228
+ for (let key in inline) {
1229
+ newInline[key] = inline[key];
1230
+ }
1231
+ return newInline;
1232
+ }
1233
+
1234
+ function findMaxFitLength(text, maxWidth, measureFn) {
1235
+ let low = 1;
1236
+ let high = text.length;
1237
+ let bestFit = 1;
1238
+
1239
+ while (low <= high) {
1240
+ const mid = Math.floor((low + high) / 2);
1241
+ const part = text.substring(0, mid);
1242
+ const width = measureFn(part);
1243
+
1244
+ if (width <= maxWidth) {
1245
+ bestFit = mid;
1246
+ low = mid + 1;
1247
+ } else {
1248
+ high = mid - 1;
1249
+ }
1250
+ }
1251
+
1252
+ return bestFit;
1253
+ }
1254
+
1255
+ if (!textNode._inlines || textNode._inlines.length === 0) {
1256
+ return null;
1257
+ }
1258
+
1259
+ let line = new Line(this.writer.context().availableWidth);
1260
+ const textInlines = new TextInlines(null);
1261
+
1262
+ let isForceContinue = false;
1263
+ while (textNode._inlines && textNode._inlines.length > 0 &&
1264
+ (line.hasEnoughSpaceForInline(textNode._inlines[0], textNode._inlines.slice(1)) || isForceContinue)) {
1265
+ let isHardWrap = false;
1266
+ let inline = textNode._inlines.shift();
1267
+ isForceContinue = false;
1268
+
1269
+ if (!inline.noWrap && inline.text && inline.text.length > 1 && inline.width > line.getAvailableWidth()) {
1270
+ let maxChars = findMaxFitLength(inline.text, line.getAvailableWidth(), (txt) =>
1271
+ textInlines.widthOfText(txt, inline)
1272
+ );
1273
+ if (maxChars < inline.text.length) {
1274
+ let newInline = cloneInline(inline);
1275
+
1276
+ newInline.text = inline.text.substr(maxChars);
1277
+ inline.text = inline.text.substr(0, maxChars);
1278
+
1279
+ newInline.width = textInlines.widthOfText(newInline.text, newInline);
1280
+ inline.width = textInlines.widthOfText(inline.text, inline);
1281
+
1282
+ textNode._inlines.unshift(newInline);
1283
+ isHardWrap = true;
1284
+ }
1285
+ }
1286
+
1287
+ line.addInline(inline);
1288
+
1289
+ isForceContinue = inline.noNewLine && !isHardWrap;
1290
+ }
1291
+
1292
+ line.lastLineInParagraph = textNode._inlines.length === 0;
1293
+
1294
+ return line;
1295
+ }
1296
+
1297
+ // images
1298
+ processImage(node) {
1299
+ let position = this.writer.addImage(node);
1300
+ node.positions.push(position);
1301
+ }
1302
+
1303
+ processCanvas(node) {
1304
+ let positions = this.writer.addCanvas(node);
1305
+ addAll(node.positions, positions);
1306
+ }
1307
+
1308
+ processSVG(node) {
1309
+ let position = this.writer.addSVG(node);
1310
+ node.positions.push(position);
1311
+ }
1312
+
1313
+ processQr(node) {
1314
+ let position = this.writer.addQr(node);
1315
+ node.positions.push(position);
1316
+ }
1317
+
1318
+ processAcroForm (node) {
1319
+ let availableWidth = this.writer.context().availableWidth;
1320
+ let position = this.writer.addAcroForm(node);
1321
+ node.positions.push(position);
1322
+ node.availableWidth = availableWidth;
1323
+ }
1324
+
1325
+ processAttachment(node) {
1326
+ let position = this.writer.addAttachment(node);
1327
+ node.positions.push(position);
1328
+ }
1329
+ }
1330
+
1331
+ function decorateNode(node) {
1332
+ let x = node.x;
1333
+ let y = node.y;
1334
+ node.positions = [];
1335
+
1336
+ if (Array.isArray(node.canvas)) {
1337
+ node.canvas.forEach(vector => {
1338
+ let x = vector.x;
1339
+ let y = vector.y;
1340
+ let x1 = vector.x1;
1341
+ let y1 = vector.y1;
1342
+ let x2 = vector.x2;
1343
+ let y2 = vector.y2;
1344
+ vector.resetXY = () => {
1345
+ vector.x = x;
1346
+ vector.y = y;
1347
+ vector.x1 = x1;
1348
+ vector.y1 = y1;
1349
+ vector.x2 = x2;
1350
+ vector.y2 = y2;
1351
+ };
1352
+ });
1353
+ }
1354
+
1355
+ node.resetXY = () => {
1356
+ node.x = x;
1357
+ node.y = y;
1358
+ if (Array.isArray(node.canvas)) {
1359
+ node.canvas.forEach(vector => {
1360
+ vector.resetXY();
1361
+ });
1362
+ }
1363
+ };
1364
+ }
1365
+
1366
+ export default LayoutBuilder;