@digicole/pdfmake-rtl 1.0.0

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