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