@flowaccount/pdfmake 1.0.7 → 1.0.8

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.
@@ -1,2242 +1,2242 @@
1
- 'use strict';
2
-
3
- var cloneDeep = require('lodash/cloneDeep');
4
- var TraversalTracker = require('./traversalTracker');
5
- var DocPreprocessor = require('./docPreprocessor');
6
- var DocMeasure = require('./docMeasure');
7
- var DocumentContext = require('./documentContext');
8
- var PageElementWriter = require('./pageElementWriter');
9
- var ColumnCalculator = require('./columnCalculator');
10
- var TableProcessor = require('./tableProcessor');
11
- var Line = require('./line');
12
- var isString = require('./helpers').isString;
13
- var isArray = require('./helpers').isArray;
14
- var isUndefined = require('./helpers').isUndefined;
15
- var isNull = require('./helpers').isNull;
16
- var pack = require('./helpers').pack;
17
- var offsetVector = require('./helpers').offsetVector;
18
- var fontStringify = require('./helpers').fontStringify;
19
- var getNodeId = require('./helpers').getNodeId;
20
- var isFunction = require('./helpers').isFunction;
21
- var TextTools = require('./textTools');
22
- var StyleContextStack = require('./styleContextStack');
23
- var isNumber = require('./helpers').isNumber;
24
-
25
- var footerBreak = false;
26
- var testTracker;
27
- var testWriter;
28
- var testVerticalAlignStack = [];
29
- var testResult = false;
30
- var currentLayoutBuilder;
31
-
32
- function addAll(target, otherArray) {
33
- if (!isArray(target) || !isArray(otherArray) || otherArray.length === 0) {
34
- return;
35
- }
36
-
37
- otherArray.forEach(function (item) {
38
- target.push(item);
39
- });
40
- }
41
-
42
- /**
43
- * Creates an instance of LayoutBuilder - layout engine which turns document-definition-object
44
- * into a set of pages, lines, inlines and vectors ready to be rendered into a PDF
45
- *
46
- * @param {Object} pageSize - an object defining page width and height
47
- * @param {Object} pageMargins - an object defining top, left, right and bottom margins
48
- */
49
- function LayoutBuilder(pageSize, pageMargins, imageMeasure, svgMeasure) {
50
- this.pageSize = pageSize;
51
- this.pageMargins = pageMargins;
52
- this.tracker = new TraversalTracker();
53
- this.imageMeasure = imageMeasure;
54
- this.svgMeasure = svgMeasure;
55
- this.tableLayouts = {};
56
- this.nestedLevel = 0;
57
- this.verticalAlignItemStack = [];
58
- this.heightHeaderAndFooter = {};
59
-
60
- this._footerColumnGuides = null;
61
- this._footerGapOption = null;
62
- }
63
-
64
- LayoutBuilder.prototype.registerTableLayouts = function (tableLayouts) {
65
- this.tableLayouts = pack(this.tableLayouts, tableLayouts);
66
- };
67
-
68
- /**
69
- * Executes layout engine on document-definition-object and creates an array of pages
70
- * containing positioned Blocks, Lines and inlines
71
- *
72
- * @param {Object} docStructure document-definition-object
73
- * @param {Object} fontProvider font provider
74
- * @param {Object} styleDictionary dictionary with style definitions
75
- * @param {Object} defaultStyle default style definition
76
- * @return {Array} an array of pages
77
- */
78
- LayoutBuilder.prototype.layoutDocument = function (docStructure, fontProvider, styleDictionary, defaultStyle, background, header, footer, images, watermark, pageBreakBeforeFct) {
79
-
80
- function addPageBreaksIfNecessary(linearNodeList, pages) {
81
-
82
- if (!isFunction(pageBreakBeforeFct)) {
83
- return false;
84
- }
85
-
86
- linearNodeList = linearNodeList.filter(function (node) {
87
- return node.positions.length > 0;
88
- });
89
-
90
- linearNodeList.forEach(function (node) {
91
- var nodeInfo = {};
92
- [
93
- 'id', 'text', 'ul', 'ol', 'table', 'image', 'qr', 'canvas', 'svg', 'columns', 'layers',
94
- 'headlineLevel', 'style', 'pageBreak', 'pageOrientation',
95
- 'width', 'height'
96
- ].forEach(function (key) {
97
- if (node[key] !== undefined) {
98
- nodeInfo[key] = node[key];
99
- }
100
- });
101
- nodeInfo.startPosition = node.positions[0];
102
- nodeInfo.pageNumbers = Array.from(new Set(node.positions.map(function (node) { return node.pageNumber; })));
103
- nodeInfo.pages = pages.length;
104
- nodeInfo.stack = isArray(node.stack);
105
- nodeInfo.layers = isArray(node.layers);
106
-
107
- node.nodeInfo = nodeInfo;
108
- });
109
-
110
- for (var index = 0; index < linearNodeList.length; index++) {
111
- var node = linearNodeList[index];
112
- if (node.pageBreak !== 'before' && !node.pageBreakCalculated) {
113
- node.pageBreakCalculated = true;
114
- var pageNumber = node.nodeInfo.pageNumbers[0];
115
- var followingNodesOnPage = [];
116
- var nodesOnNextPage = [];
117
- var previousNodesOnPage = [];
118
- if (pageBreakBeforeFct.length > 1) {
119
- for (var ii = index + 1, l = linearNodeList.length; ii < l; ii++) {
120
- if (linearNodeList[ii].nodeInfo.pageNumbers.indexOf(pageNumber) > -1) {
121
- followingNodesOnPage.push(linearNodeList[ii].nodeInfo);
122
- }
123
- if (pageBreakBeforeFct.length > 2 && linearNodeList[ii].nodeInfo.pageNumbers.indexOf(pageNumber + 1) > -1) {
124
- nodesOnNextPage.push(linearNodeList[ii].nodeInfo);
125
- }
126
- }
127
- }
128
- if (pageBreakBeforeFct.length > 3) {
129
- for (var jj = 0; jj < index; jj++) {
130
- if (linearNodeList[jj].nodeInfo.pageNumbers.indexOf(pageNumber) > -1) {
131
- previousNodesOnPage.push(linearNodeList[jj].nodeInfo);
132
- }
133
- }
134
- }
135
- if (pageBreakBeforeFct(node.nodeInfo, followingNodesOnPage, nodesOnNextPage, previousNodesOnPage)) {
136
- node.pageBreak = 'before';
137
- return true;
138
- }
139
- }
140
- }
141
-
142
- return false;
143
- }
144
-
145
- this.docPreprocessor = new DocPreprocessor();
146
- this.docMeasure = new DocMeasure(fontProvider, styleDictionary, defaultStyle, this.imageMeasure, this.svgMeasure, this.tableLayouts, images);
147
-
148
-
149
- function resetXYs(result) {
150
- result.linearNodeList.forEach(function (node) {
151
- node.resetXY();
152
- });
153
- }
154
-
155
- var result = this.tryLayoutDocument(docStructure, fontProvider, styleDictionary, defaultStyle, background, header, footer, images, watermark);
156
- while (addPageBreaksIfNecessary(result.linearNodeList, result.pages)) {
157
- resetXYs(result);
158
- result = this.tryLayoutDocument(docStructure, fontProvider, styleDictionary, defaultStyle, background, header, footer, images, watermark);
159
- }
160
-
161
- return result.pages;
162
- };
163
-
164
- LayoutBuilder.prototype.tryLayoutDocument = function (docStructure, fontProvider, styleDictionary, defaultStyle, background, header, footer, images, watermark) {
165
- footerBreak = false;
166
-
167
- this.verticalAlignItemStack = this.verticalAlignItemStack || [];
168
- this.linearNodeList = [];
169
- this.writer = new PageElementWriter(
170
- new DocumentContext(this.pageSize, this.pageMargins, this._footerGapOption), this.tracker);
171
-
172
- this.heightHeaderAndFooter = this.addHeadersAndFooters(header, footer) || {};
173
- if (!isUndefined(this.heightHeaderAndFooter.header)) {
174
- this.pageMargins.top = this.heightHeaderAndFooter.header + 1;
175
- }
176
-
177
- if (isArray(docStructure) && docStructure[2] && isArray(docStructure[2]) && docStructure[2][0] && docStructure[2][0].remark) {
178
- var tableRemark = docStructure[2][0].remark;
179
- var remarkLabel = docStructure[2][0];
180
- var remarkDetail = docStructure[2][1] && docStructure[2][1].text;
181
-
182
- docStructure[2].splice(0, 1);
183
- if (docStructure[2].length > 0) {
184
- docStructure[2].splice(0, 1);
185
- }
186
-
187
- var labelRow = [];
188
- var detailRow = [];
189
-
190
- labelRow.push(remarkLabel);
191
- detailRow.push({ remarktest: true, text: remarkDetail });
192
-
193
- tableRemark.table.body.push(labelRow);
194
- tableRemark.table.body.push(detailRow);
195
-
196
- tableRemark.table.headerRows = 1;
197
-
198
- docStructure[2].push(tableRemark);
199
- }
200
-
201
- this.linearNodeList = [];
202
- docStructure = this.docPreprocessor.preprocessDocument(docStructure);
203
- docStructure = this.docMeasure.measureDocument(docStructure);
204
-
205
- this.verticalAlignItemStack = [];
206
- this.writer = new PageElementWriter(
207
- new DocumentContext(this.pageSize, this.pageMargins, this._footerGapOption), this.tracker);
208
-
209
- var _this = this;
210
- this.writer.context().tracker.startTracking('pageAdded', function () {
211
- _this.addBackground(background);
212
- });
213
-
214
- this.addBackground(background);
215
- this.processNode(docStructure);
216
- this.addHeadersAndFooters(header, footer,
217
- (this.heightHeaderAndFooter.header || 0) + 1,
218
- (this.heightHeaderAndFooter.footer || 0) + 1);
219
- if (watermark != null) {
220
- this.addWatermark(watermark, fontProvider, defaultStyle);
221
- }
222
-
223
- return { pages: this.writer.context().pages, linearNodeList: this.linearNodeList };
224
- };
225
-
226
- LayoutBuilder.prototype.applyFooterGapOption = function(opt) {
227
- if (opt === true) {
228
- opt = { enabled: true };
229
- }
230
-
231
- if (!opt) return;
232
-
233
- if (typeof opt !== 'object') {
234
- this._footerGapOption = { enabled: true, forcePageBreakForAllRows: false };
235
- return;
236
- }
237
-
238
- this._footerGapOption = {
239
- enabled: opt.enabled !== false,
240
- minRowHeight: typeof opt.minRowHeight === 'number' ? opt.minRowHeight : undefined, // Optional fallback - system auto-calculates from cell content if not provided
241
- forcePageBreakForAllRows: opt.forcePageBreakForAllRows === true, // Force page break for all rows (not just inline images)
242
- columns: opt.columns ? {
243
- widths: Array.isArray(opt.columns.widths) ? opt.columns.widths.slice() : undefined,
244
- widthLength: opt.columns.widths.length || 0,
245
- stops: Array.isArray(opt.columns.stops) ? opt.columns.stops.slice() : undefined,
246
- style: opt.columns.style ? Object.assign({}, opt.columns.style) : {},
247
- includeOuter: opt.columns.includeOuter !== false
248
- } : null
249
- };
250
- };
251
-
252
- LayoutBuilder.prototype.addBackground = function (background) {
253
- var backgroundGetter = isFunction(background) ? background : function () {
254
- return background;
255
- };
256
-
257
- var context = this.writer.context();
258
- var pageSize = context.getCurrentPage().pageSize;
259
-
260
- var pageBackground = backgroundGetter(context.page + 1, pageSize);
261
-
262
- if (pageBackground) {
263
- this.writer.beginUnbreakableBlock(pageSize.width, pageSize.height);
264
- pageBackground = this.docPreprocessor.preprocessDocument(pageBackground);
265
- this.processNode(this.docMeasure.measureDocument(pageBackground));
266
- this.writer.commitUnbreakableBlock(0, 0);
267
- context.backgroundLength[context.page] += pageBackground.positions.length;
268
- }
269
- };
270
-
271
- LayoutBuilder.prototype.addStaticRepeatable = function (headerOrFooter, sizeFunction) {
272
- return this.addDynamicRepeatable(function () {
273
- return JSON.parse(JSON.stringify(headerOrFooter)); // copy to new object
274
- }, sizeFunction);
275
- };
276
-
277
- LayoutBuilder.prototype.addDynamicRepeatable = function (nodeGetter, sizeFunction) {
278
- var pages = this.writer.context().pages;
279
- var measuredHeight;
280
-
281
- for (var pageIndex = 0, l = pages.length; pageIndex < l; pageIndex++) {
282
- this.writer.context().page = pageIndex;
283
-
284
- var node = nodeGetter(pageIndex + 1, l, this.writer.context().pages[pageIndex].pageSize);
285
-
286
- if (node) {
287
- var sizes = sizeFunction(this.writer.context().getCurrentPage().pageSize, this.pageMargins);
288
- this.writer.beginUnbreakableBlock(sizes.width, sizes.height);
289
- node = this.docPreprocessor.preprocessDocument(node);
290
- this.processNode(this.docMeasure.measureDocument(node));
291
- this.writer.commitUnbreakableBlock(sizes.x, sizes.y);
292
- if (!isUndefined(node._height)) {
293
- measuredHeight = node._height;
294
- }
295
- }
296
- }
297
-
298
- return measuredHeight;
299
- };
300
-
301
- LayoutBuilder.prototype.addHeadersAndFooters = function (header, footer, headerHeight, footerHeight) {
302
- var measured = { header: undefined, footer: undefined };
303
-
304
- var headerSizeFct = function (pageSize) {
305
- var effectiveHeight = headerHeight;
306
- if (isUndefined(effectiveHeight)) {
307
- effectiveHeight = pageSize.height;
308
- }
309
- return {
310
- x: 0,
311
- y: 0,
312
- width: pageSize.width,
313
- height: effectiveHeight
314
- };
315
- };
316
-
317
- var footerSizeFct = function (pageSize) {
318
- var effectiveHeight = footerHeight;
319
- if (isUndefined(effectiveHeight)) {
320
- effectiveHeight = pageSize.height;
321
- }
322
- return {
323
- x: 0,
324
- y: pageSize.height - effectiveHeight,
325
- width: pageSize.width,
326
- height: effectiveHeight
327
- };
328
- };
329
-
330
- if (this._footerGapOption && !this.writer.context()._footerGapOption) {
331
- this.writer.context()._footerGapOption = this._footerGapOption;
332
- }
333
-
334
- if (isFunction(header)) {
335
- measured.header = this.addDynamicRepeatable(header, headerSizeFct);
336
- } else if (header) {
337
- measured.header = this.addStaticRepeatable(header, headerSizeFct);
338
- }
339
-
340
- if (isFunction(footer)) {
341
- measured.footer = this.addDynamicRepeatable(footer, footerSizeFct);
342
- } else if (footer) {
343
- measured.footer = this.addStaticRepeatable(footer, footerSizeFct);
344
- }
345
-
346
- return measured;
347
- };
348
-
349
- LayoutBuilder.prototype.addWatermark = function (watermark, fontProvider, defaultStyle) {
350
- if (isString(watermark)) {
351
- watermark = { 'text': watermark };
352
- }
353
-
354
- if (!watermark.text) { // empty watermark text
355
- return;
356
- }
357
-
358
- var pages = this.writer.context().pages;
359
- for (var i = 0, l = pages.length; i < l; i++) {
360
- pages[i].watermark = getWatermarkObject({ ...watermark }, pages[i].pageSize, fontProvider, defaultStyle);
361
- }
362
-
363
- function getWatermarkObject(watermark, pageSize, fontProvider, defaultStyle) {
364
- watermark.font = watermark.font || defaultStyle.font || 'Roboto';
365
- watermark.fontSize = watermark.fontSize || 'auto';
366
- watermark.color = watermark.color || 'black';
367
- watermark.opacity = isNumber(watermark.opacity) ? watermark.opacity : 0.6;
368
- watermark.bold = watermark.bold || false;
369
- watermark.italics = watermark.italics || false;
370
- watermark.angle = !isUndefined(watermark.angle) && !isNull(watermark.angle) ? watermark.angle : null;
371
-
372
- if (watermark.angle === null) {
373
- watermark.angle = Math.atan2(pageSize.height, pageSize.width) * -180 / Math.PI;
374
- }
375
-
376
- if (watermark.fontSize === 'auto') {
377
- watermark.fontSize = getWatermarkFontSize(pageSize, watermark, fontProvider);
378
- }
379
-
380
- var watermarkObject = {
381
- text: watermark.text,
382
- font: fontProvider.provideFont(watermark.font, watermark.bold, watermark.italics),
383
- fontSize: watermark.fontSize,
384
- color: watermark.color,
385
- opacity: watermark.opacity,
386
- angle: watermark.angle
387
- };
388
-
389
- watermarkObject._size = getWatermarkSize(watermark, fontProvider);
390
-
391
- return watermarkObject;
392
- }
393
-
394
- function getWatermarkSize(watermark, fontProvider) {
395
- var textTools = new TextTools(fontProvider);
396
- var styleContextStack = new StyleContextStack(null, { font: watermark.font, bold: watermark.bold, italics: watermark.italics });
397
-
398
- styleContextStack.push({
399
- fontSize: watermark.fontSize
400
- });
401
-
402
- var size = textTools.sizeOfString(watermark.text, styleContextStack);
403
- var rotatedSize = textTools.sizeOfRotatedText(watermark.text, watermark.angle, styleContextStack);
404
-
405
- return { size: size, rotatedSize: rotatedSize };
406
- }
407
-
408
- function getWatermarkFontSize(pageSize, watermark, fontProvider) {
409
- var textTools = new TextTools(fontProvider);
410
- var styleContextStack = new StyleContextStack(null, { font: watermark.font, bold: watermark.bold, italics: watermark.italics });
411
- var rotatedSize;
412
-
413
- /**
414
- * Binary search the best font size.
415
- * Initial bounds [0, 1000]
416
- * Break when range < 1
417
- */
418
- var a = 0;
419
- var b = 1000;
420
- var c = (a + b) / 2;
421
- while (Math.abs(a - b) > 1) {
422
- styleContextStack.push({
423
- fontSize: c
424
- });
425
- rotatedSize = textTools.sizeOfRotatedText(watermark.text, watermark.angle, styleContextStack);
426
- if (rotatedSize.width > pageSize.width) {
427
- b = c;
428
- c = (a + b) / 2;
429
- } else if (rotatedSize.width < pageSize.width) {
430
- if (rotatedSize.height > pageSize.height) {
431
- b = c;
432
- c = (a + b) / 2;
433
- } else {
434
- a = c;
435
- c = (a + b) / 2;
436
- }
437
- }
438
- styleContextStack.pop();
439
- }
440
- /*
441
- End binary search
442
- */
443
- return c;
444
- }
445
- };
446
-
447
- function decorateNode(node) {
448
- var x = node.x, y = node.y;
449
- node.positions = [];
450
-
451
- if (isArray(node.canvas)) {
452
- node.canvas.forEach(function (vector) {
453
- var x = vector.x, y = vector.y, x1 = vector.x1, y1 = vector.y1, x2 = vector.x2, y2 = vector.y2;
454
- vector.resetXY = function () {
455
- vector.x = x;
456
- vector.y = y;
457
- vector.x1 = x1;
458
- vector.y1 = y1;
459
- vector.x2 = x2;
460
- vector.y2 = y2;
461
- };
462
- });
463
- }
464
-
465
- node.resetXY = function () {
466
- node.x = x;
467
- node.y = y;
468
- if (isArray(node.canvas)) {
469
- node.canvas.forEach(function (vector) {
470
- vector.resetXY();
471
- });
472
- }
473
- };
474
- }
475
-
476
- LayoutBuilder.prototype.processNode = function (node) {
477
- var self = this;
478
-
479
- if (footerBreak && (node.footerBreak || node.footer)) {
480
- return;
481
- }
482
-
483
- if (node && node.unbreakable && node.summary && node.table && node.table.body &&
484
- node.table.body[0] && node.table.body[0][0] && node.table.body[0][0].summaryBreak) {
485
- testTracker = new TraversalTracker();
486
- testWriter = new PageElementWriter(self.writer.context(), testTracker);
487
- testVerticalAlignStack = self.verticalAlignItemStack.slice();
488
- currentLayoutBuilder = self;
489
- testResult = false;
490
- var nodeForTest = cloneDeep(node);
491
- if (nodeForTest.table.body[0]) {
492
- nodeForTest.table.body[0].splice(0, 1);
493
- }
494
- processNode_test(nodeForTest);
495
- currentLayoutBuilder = null;
496
- if (testResult && node.table.body[0]) {
497
- node.table.body[0].splice(0, 1);
498
- }
499
- }
500
-
501
- this.linearNodeList.push(node);
502
- decorateNode(node);
503
-
504
- var prevTop = self.writer.context().getCurrentPosition().top;
505
-
506
- applyMargins(function () {
507
- var unbreakable = node.unbreakable;
508
- if (unbreakable) {
509
- self.writer.beginUnbreakableBlock();
510
- }
511
-
512
- var absPosition = node.absolutePosition;
513
- if (absPosition) {
514
- self.writer.context().beginDetachedBlock();
515
- self.writer.context().moveTo(absPosition.x || 0, absPosition.y || 0);
516
- }
517
-
518
- var relPosition = node.relativePosition;
519
- if (relPosition) {
520
- self.writer.context().beginDetachedBlock();
521
- self.writer.context().moveToRelative(relPosition.x || 0, relPosition.y || 0);
522
- }
523
-
524
- var verticalAlignBegin;
525
- if (node.verticalAlign) {
526
- verticalAlignBegin = self.writer.beginVerticalAlign(node.verticalAlign);
527
- }
528
-
529
- if (node.stack) {
530
- // Handle _footerGapOption for breakable stacks
531
- var footerGapEnabled = !unbreakable && node.footer && node._footerGapOption && node._footerGapOption.enabled;
532
- var preRenderState = null;
533
-
534
- if (footerGapEnabled) {
535
- var ctx = self.writer.context();
536
- var currentPage = ctx.getCurrentPage();
537
- preRenderState = {
538
- startY: ctx.y,
539
- startPage: ctx.page,
540
- availableHeight: ctx.availableHeight,
541
- itemCount: currentPage ? currentPage.items.length : 0,
542
- x: ctx.x,
543
- summaryRenderedPage: null
544
- };
545
- }
546
-
547
- // Process the stack
548
- self.processVerticalContainer(node);
549
-
550
- // Track which page summary was rendered on (summary is first item, unbreakable)
551
- if (preRenderState && node.stack && node.stack[0]) {
552
- var summaryNode = node.stack[0];
553
- if (summaryNode.summary || summaryNode.unbreakable) {
554
- // Summary is unbreakable, check if it was pushed to a new page
555
- // by comparing its height with available space at startPage
556
- var summaryHeight = Math.abs(summaryNode._height || 0);
557
- if (summaryHeight <= preRenderState.availableHeight) {
558
- // Summary fit on startPage
559
- preRenderState.summaryRenderedPage = preRenderState.startPage;
560
- } else {
561
- // Summary was pushed to next page
562
- preRenderState.summaryRenderedPage = preRenderState.startPage + 1;
563
- }
564
- }
565
- }
566
-
567
- // Post-render repositioning
568
- if (footerGapEnabled && preRenderState) {
569
- var ctx = self.writer.context();
570
-
571
- // Only reposition if on same page (single-page content)
572
- if (ctx.page === preRenderState.startPage) {
573
- var renderedHeight = ctx.y - preRenderState.startY;
574
- var gapHeight = preRenderState.availableHeight - renderedHeight;
575
-
576
- if (gapHeight > 0) {
577
- var currentPage = ctx.getCurrentPage();
578
-
579
- // SINGLE-PAGE: Draw guide lines in the gap area
580
- var gapTopY = preRenderState.startY;
581
- var colSpec = node._footerGapOption.columns || self._footerGapOption.columns || null;
582
- if (colSpec) {
583
- var rawWidths = colSpec.content.vLines || [];
584
- if (rawWidths && rawWidths.length > 1) {
585
- var style = (colSpec.style || {});
586
- var lw = style.lineWidth != null ? style.lineWidth : 0.5;
587
- var lc = style.color || '#000000';
588
- var dashCfg = style.dash;
589
- var includeOuter = colSpec.includeOuter !== false;
590
- var startIndex = includeOuter ? 0 : 1;
591
- var endIndex = includeOuter ? rawWidths.length : rawWidths.length - 1;
592
-
593
- for (var ci = startIndex; ci < endIndex; ci++) {
594
- var xGuide = ctx.x + rawWidths[ci] - 0.25;
595
- currentPage.items.push({
596
- type: 'vector',
597
- item: {
598
- type: 'line',
599
- x1: xGuide,
600
- y1: gapTopY,
601
- x2: xGuide,
602
- y2: gapTopY + gapHeight,
603
- lineWidth: lw,
604
- lineColor: lc,
605
- dash: dashCfg ? {
606
- length: dashCfg.length,
607
- space: dashCfg.space != null ? dashCfg.space : dashCfg.gap
608
- } : undefined,
609
- _footerGuideLine: true
610
- }
611
- });
612
- }
613
- }
614
- }
615
-
616
- // Reposition only items that belong to footer stack content
617
- // Iterate ALL items (backgrounds are inserted at lower indices, not appended)
618
- // Filter by Y position to exclude non-footer items
619
- for (var i = 0; i < currentPage.items.length; i++) {
620
- var item = currentPage.items[i];
621
-
622
- // Skip the guide lines we just added (they're already positioned correctly)
623
- if (item.item && item.item._footerGuideLine) {
624
- continue;
625
- }
626
-
627
- // Get the item's starting Y position
628
- var itemStartY = null;
629
- if (item.item && typeof item.item.y1 === 'number') {
630
- itemStartY = item.item.y1;
631
- } else if (item.item && typeof item.item.y === 'number') {
632
- itemStartY = item.item.y;
633
- }
634
-
635
- // Only reposition items that START at or after footer stack's Y position
636
- // This excludes outer table border lines that extend from earlier rows
637
- if (itemStartY !== null && itemStartY < preRenderState.startY) {
638
- continue;
639
- }
640
-
641
- // Reposition this item
642
- if (item.item && typeof item.item.y === 'number') {
643
- item.item.y += gapHeight;
644
- }
645
- if (item.item && typeof item.item.y1 === 'number') {
646
- item.item.y1 += gapHeight;
647
- }
648
- if (item.item && typeof item.item.y2 === 'number') {
649
- item.item.y2 += gapHeight;
650
- }
651
- // Handle polylines (points array)
652
- if (item.item && item.item.points && Array.isArray(item.item.points)) {
653
- for (var pi = 0; pi < item.item.points.length; pi++) {
654
- if (typeof item.item.points[pi].y === 'number') {
655
- item.item.points[pi].y += gapHeight;
656
- }
657
- }
658
- }
659
- }
660
- ctx.moveDown(gapHeight);
661
- }
662
- } else {
663
- // MULTI-PAGE: Process ALL pages from startPage+1 to current page
664
- // Only move FOOTER items to bottom, keep remark at top
665
- var pages = ctx.pages;
666
- var pageMargins = ctx.pageMargins;
667
-
668
- // Helper function to recursively find node with _isFooterTable
669
- function findFooterTableNode(n) {
670
- if (!n) return null;
671
- if (n._isFooterTable) return n;
672
- if (n.stack && Array.isArray(n.stack)) {
673
- for (var i = 0; i < n.stack.length; i++) {
674
- var found = findFooterTableNode(n.stack[i]);
675
- if (found) return found;
676
- }
677
- }
678
- if (Array.isArray(n)) {
679
- for (var i = 0; i < n.length; i++) {
680
- var found = findFooterTableNode(n[i]);
681
- if (found) return found;
682
- }
683
- }
684
- return null;
685
- }
686
-
687
- // Find footer table node to get its height
688
- var footerStackItem = null;
689
- if (node.stack && node.stack.length > 0) {
690
- for (var si = node.stack.length - 1; si >= 0; si--) {
691
- var found = findFooterTableNode(node.stack[si]);
692
- if (found) {
693
- footerStackItem = node.stack[si];
694
- break;
695
- }
696
- }
697
- }
698
-
699
- var stackHeight = Math.abs((footerStackItem && footerStackItem._height) || 0);
700
-
701
- // Only process the LAST page where footer is located
702
- // Intermediate pages (remark only) should not be repositioned
703
- var pageIdx = ctx.page;
704
- if (pageIdx > preRenderState.startPage) {
705
- // Also reposition items on the START page (where summary might be)
706
- var startPage = pages[preRenderState.startPage];
707
- if (startPage && startPage.items && startPage.items.length > 0) {
708
- var startPageHeight = startPage.pageSize.height;
709
- var startPageBottom = startPageHeight - pageMargins.bottom;
710
-
711
- // Find content bottom on start page
712
- var startContentBottom = 0;
713
- for (var si = 0; si < startPage.items.length; si++) {
714
- var sItem = startPage.items[si];
715
- var sItemBottom = 0;
716
- if (sItem.item) {
717
- if (typeof sItem.item.y === 'number') {
718
- var sh = 0;
719
- // Line items have getHeight() method
720
- if (sItem.type === 'line' && typeof sItem.item.getHeight === 'function') {
721
- sh = sItem.item.getHeight();
722
- } else {
723
- sh = sItem.item.h || sItem.item.height || 0;
724
- }
725
- sItemBottom = sItem.item.y + sh;
726
- }
727
- if (typeof sItem.item.y2 === 'number' && sItem.item.y2 > sItemBottom) {
728
- sItemBottom = sItem.item.y2;
729
- }
730
- }
731
- if (sItemBottom > startContentBottom) {
732
- startContentBottom = sItemBottom;
733
- }
734
- }
735
-
736
- // Calculate gap and move items on start page
737
- var startGapHeight = startPageBottom - startContentBottom;
738
- if (startGapHeight > 0) {
739
- var startStackStartY = preRenderState.startY;
740
- for (var si = 0; si < startPage.items.length; si++) {
741
- var sItem = startPage.items[si];
742
- var sItemY = null;
743
- if (sItem.item && typeof sItem.item.y1 === 'number') {
744
- sItemY = sItem.item.y1;
745
- } else if (sItem.item && typeof sItem.item.y === 'number') {
746
- sItemY = sItem.item.y;
747
- } else if (sItem.item && sItem.item.points && Array.isArray(sItem.item.points) && sItem.item.points.length > 0) {
748
- // For polylines, use the first point's Y
749
- sItemY = sItem.item.points[0].y;
750
- }
751
-
752
- // Skip items fully above footer start
753
- if (sItemY === null || sItemY < startStackStartY) continue;
754
-
755
- // Move item down
756
- if (sItem.item && typeof sItem.item.y === 'number') {
757
- sItem.item.y += startGapHeight;
758
- }
759
- if (sItem.item && typeof sItem.item.y1 === 'number') {
760
- sItem.item.y1 += startGapHeight;
761
- }
762
- if (sItem.item && typeof sItem.item.y2 === 'number') {
763
- sItem.item.y2 += startGapHeight;
764
- }
765
- // Handle polylines (points array)
766
- if (sItem.item && sItem.item.points && Array.isArray(sItem.item.points)) {
767
- for (var spi = 0; spi < sItem.item.points.length; spi++) {
768
- if (typeof sItem.item.points[spi].y === 'number') {
769
- sItem.item.points[spi].y += startGapHeight;
770
- }
771
- }
772
- }
773
- }
774
-
775
- // MULTI-PAGE: Draw guide lines in the gap area (same as single-page)
776
- var colSpec = node._footerGapOption && node._footerGapOption.columns ? node._footerGapOption.columns : (self._footerGapOption && self._footerGapOption.columns);
777
- if (colSpec) {
778
- var rawWidths = colSpec.content && colSpec.content.vLines ? colSpec.content.vLines : [];
779
- if (rawWidths && rawWidths.length > 1) {
780
- var style = (colSpec.style || {});
781
- var lw = style.lineWidth != null ? style.lineWidth : 0.5;
782
- var lc = style.color || '#000000';
783
- var dashCfg = style.dash;
784
- var includeOuter = colSpec.includeOuter !== false;
785
- var startIndex = includeOuter ? 0 : 1;
786
- var endIndex = includeOuter ? rawWidths.length : rawWidths.length - 1;
787
- var pageX = preRenderState.x || pageMargins.left;
788
-
789
- for (var ci = startIndex; ci < endIndex; ci++) {
790
- var xGuide = pageX + rawWidths[ci] - 0.25;
791
- // Extend first and last vertical lines to content bottom after moving
792
- var isFirstOrLast = (ci === 0) || (ci === rawWidths.length - 1);
793
- var vLineY2 = isFirstOrLast ? (startContentBottom + startGapHeight) : (startStackStartY + startGapHeight);
794
- startPage.items.push({
795
- type: 'vector',
796
- item: {
797
- type: 'line',
798
- x1: xGuide,
799
- y1: startStackStartY,
800
- x2: xGuide,
801
- y2: vLineY2,
802
- lineWidth: lw,
803
- lineColor: lc,
804
- dash: dashCfg ? {
805
- length: dashCfg.length,
806
- space: dashCfg.space != null ? dashCfg.space : dashCfg.gap
807
- } : undefined,
808
- _footerGuideLine: true
809
- }
810
- });
811
- }
812
-
813
- // Remove existing horizontal line at startStackStartY (drawn by tableProcessor)
814
- // It's at wrong position now - we'll draw new one at bottom of gap
815
- for (var ri = startPage.items.length - 1; ri >= 0; ri--) {
816
- var rItem = startPage.items[ri];
817
- if (rItem.type === 'vector' && rItem.item && rItem.item.type === 'line') {
818
- // Check if it's a horizontal line at startStackStartY
819
- if (Math.abs(rItem.item.y1 - startStackStartY) < 1 &&
820
- Math.abs(rItem.item.y2 - startStackStartY) < 1) {
821
- startPage.items.splice(ri, 1);
822
- break;
823
- }
824
- }
825
- }
826
- }
827
- }
828
- }
829
- }
830
-
831
- var page = pages[pageIdx];
832
- if (page && page.items && page.items.length > 0) {
833
- var pageHeight = page.pageSize.height;
834
- var bottomMargin = pageMargins.bottom;
835
- var pageBottom = pageHeight - bottomMargin;
836
-
837
- // Find footer start Y on this page (where footer items begin)
838
- // Use footerHeight to identify footer area from the bottom of content
839
- var contentBottom = 0;
840
- for (var i = 0; i < page.items.length; i++) {
841
- var item = page.items[i];
842
- var itemBottom = 0;
843
- if (item.item) {
844
- if (typeof item.item.y === 'number') {
845
- var h = item.item.h || item.item.height || 0;
846
- itemBottom = item.item.y + h;
847
- }
848
- if (typeof item.item.y2 === 'number' && item.item.y2 > itemBottom) {
849
- itemBottom = item.item.y2;
850
- }
851
- // Handle polylines (points array)
852
- if (item.item.points && Array.isArray(item.item.points)) {
853
- for (var pi = 0; pi < item.item.points.length; pi++) {
854
- if (typeof item.item.points[pi].y === 'number' && item.item.points[pi].y > itemBottom) {
855
- itemBottom = item.item.points[pi].y;
856
- }
857
- }
858
- }
859
- }
860
- if (itemBottom > contentBottom) {
861
- contentBottom = itemBottom;
862
- }
863
- }
864
-
865
- // Check if summary is on the last page
866
- var summaryOnLastPage = (preRenderState.summaryRenderedPage === pageIdx);
867
-
868
- var stackStartY;
869
- if (summaryOnLastPage) {
870
- // Summary is on this page - move all: summary + remark + footer together
871
- // Calculate header threshold for this page
872
- var repeatableHeaderHeight = 0;
873
- for (var ri = 0; ri < self.writer.repeatables.length; ri++) {
874
- repeatableHeaderHeight += self.writer.repeatables[ri].height;
875
- }
876
- var headerThreshold = pageMargins.top + repeatableHeaderHeight;
877
-
878
- // Find minimum Y of all items below header threshold
879
- stackStartY = contentBottom;
880
- for (var i = 0; i < page.items.length; i++) {
881
- var item = page.items[i];
882
- var itemY = null;
883
- if (item.item && typeof item.item.y1 === 'number') {
884
- itemY = item.item.y1;
885
- } else if (item.item && typeof item.item.y === 'number') {
886
- itemY = item.item.y;
887
- } else if (item.item && item.item.points && Array.isArray(item.item.points) && item.item.points.length > 0) {
888
- itemY = item.item.points[0].y;
889
- }
890
- if (itemY !== null && itemY >= headerThreshold && itemY < stackStartY) {
891
- stackStartY = itemY;
892
- }
893
- }
894
-
895
- // Draw guide lines in the gap area (same as single-page)
896
- var gapHeightForLines = pageBottom - contentBottom;
897
- if (gapHeightForLines > 0) {
898
- var colSpec = node._footerGapOption && node._footerGapOption.columns ? node._footerGapOption.columns : (self._footerGapOption && self._footerGapOption.columns);
899
- if (colSpec) {
900
- var rawWidths = colSpec.content && colSpec.content.vLines ? colSpec.content.vLines : [];
901
- if (rawWidths && rawWidths.length > 1) {
902
- var style = (colSpec.style || {});
903
- var lw = style.lineWidth != null ? style.lineWidth : 0.5;
904
- var lc = style.color || '#000000';
905
- var dashCfg = style.dash;
906
- var includeOuter = colSpec.includeOuter !== false;
907
- var startIndex = includeOuter ? 0 : 1;
908
- var endIndex = includeOuter ? rawWidths.length : rawWidths.length - 1;
909
- var pageX = preRenderState.x || pageMargins.left;
910
-
911
- for (var ci = startIndex; ci < endIndex; ci++) {
912
- var xGuide = pageX + rawWidths[ci] - 0.25;
913
- page.items.push({
914
- type: 'vector',
915
- item: {
916
- type: 'line',
917
- x1: xGuide,
918
- y1: stackStartY,
919
- x2: xGuide,
920
- y2: stackStartY + gapHeightForLines,
921
- lineWidth: lw,
922
- lineColor: lc,
923
- dash: dashCfg ? {
924
- length: dashCfg.length,
925
- space: dashCfg.space != null ? dashCfg.space : dashCfg.gap
926
- } : undefined,
927
- _footerGuideLine: true
928
- }
929
- });
930
- }
931
- }
932
- }
933
- }
934
- } else {
935
- // Summary is NOT on this page - move only footer
936
- stackStartY = contentBottom - stackHeight;
937
- }
938
-
939
- // Calculate gap: how much to move footer stack down
940
- var gapHeight = pageBottom - contentBottom;
941
- if (gapHeight > 0) {
942
- // Calculate header threshold if not already calculated
943
- if (typeof headerThreshold === 'undefined') {
944
- var repeatableHeaderHeight = 0;
945
- for (var ri = 0; ri < self.writer.repeatables.length; ri++) {
946
- repeatableHeaderHeight += self.writer.repeatables[ri].height;
947
- }
948
- headerThreshold = pageMargins.top + repeatableHeaderHeight;
949
- }
950
-
951
- // Move all items that are part of footer stack (Y >= stackStartY)
952
- for (var i = 0; i < page.items.length; i++) {
953
- var item = page.items[i];
954
-
955
- // Skip guide lines (they're already positioned correctly)
956
- if (item.item && item.item._footerGuideLine) continue;
957
-
958
- var itemY = null;
959
- if (item.item && typeof item.item.y1 === 'number') {
960
- itemY = item.item.y1;
961
- } else if (item.item && typeof item.item.y === 'number') {
962
- itemY = item.item.y;
963
- } else if (item.item && item.item.points && Array.isArray(item.item.points) && item.item.points.length > 0) {
964
- itemY = item.item.points[0].y;
965
- }
966
-
967
- // Skip items above footer stack
968
- if (itemY === null || itemY < stackStartY) continue;
969
-
970
- // Skip items in header area (repeated headers)
971
- if (itemY < headerThreshold) continue;
972
-
973
- // Move footer stack item down
974
- if (item.item && typeof item.item.y === 'number') {
975
- item.item.y += gapHeight;
976
- }
977
- if (item.item && typeof item.item.y1 === 'number') {
978
- item.item.y1 += gapHeight;
979
- }
980
- if (item.item && typeof item.item.y2 === 'number') {
981
- item.item.y2 += gapHeight;
982
- }
983
- // // Handle polylines (points array)
984
- if (item.item && item.item.points && Array.isArray(item.item.points)) {
985
- for (var pi = 0; pi < item.item.points.length; pi++) {
986
- if (typeof item.item.points[pi].y === 'number') {
987
- item.item.points[pi].y += gapHeight;
988
- }
989
- }
990
- }
991
- }
992
- }
993
- }
994
- }
995
-
996
- // Also update context for current page
997
- var lastPageGapHeight = ctx.availableHeight;
998
- if (lastPageGapHeight > 0) {
999
- ctx.moveDown(lastPageGapHeight);
1000
- }
1001
- }
1002
- }
1003
- } else if (node.layers) {
1004
- self.processLayers(node);
1005
- } else if (node.columns) {
1006
- self.processColumns(node);
1007
- } else if (node.ul) {
1008
- self.processList(false, node);
1009
- } else if (node.ol) {
1010
- self.processList(true, node);
1011
- } else if (node.table) {
1012
- self.processTable(node);
1013
- } else if (node.text !== undefined) {
1014
- self.processLeaf(node);
1015
- } else if (node.toc) {
1016
- self.processToc(node);
1017
- } else if (node.image) {
1018
- self.processImage(node);
1019
- } else if (node.svg) {
1020
- self.processSVG(node);
1021
- } else if (node.canvas) {
1022
- self.processCanvas(node);
1023
- } else if (node.qr) {
1024
- self.processQr(node);
1025
- } else if (!node._span) {
1026
- throw new Error('Unrecognized document structure: ' + JSON.stringify(node, fontStringify));
1027
- }
1028
-
1029
- if ((absPosition || relPosition) && !node.absoluteRepeatable) {
1030
- self.writer.context().endDetachedBlock();
1031
- }
1032
-
1033
- if (unbreakable) {
1034
- if (node.footer) {
1035
- footerBreak = self.writer.commitUnbreakableBlock(undefined, undefined, node.footer);
1036
- } else {
1037
- self.writer.commitUnbreakableBlock();
1038
- }
1039
- }
1040
-
1041
- if (node.verticalAlign) {
1042
- var stackEntry = {
1043
- begin: verticalAlignBegin,
1044
- end: self.writer.endVerticalAlign(node.verticalAlign)
1045
- };
1046
- self.verticalAlignItemStack.push(stackEntry);
1047
- node._verticalAlignIdx = self.verticalAlignItemStack.length - 1;
1048
- }
1049
- });
1050
-
1051
- node._height = self.writer.context().getCurrentPosition().top - prevTop;
1052
-
1053
- function applyMargins(callback) {
1054
- var margin = node._margin;
1055
-
1056
- if (node.pageBreak === 'before') {
1057
- self.writer.moveToNextPage(node.pageOrientation);
1058
- }
1059
-
1060
- if (margin) {
1061
- self.writer.context().moveDown(margin[1]);
1062
- self.writer.context().addMargin(margin[0], margin[2]);
1063
- }
1064
-
1065
- callback();
1066
-
1067
- if (margin) {
1068
- self.writer.context().addMargin(-margin[0], -margin[2]);
1069
- self.writer.context().moveDown(margin[3]);
1070
- }
1071
-
1072
- if (node.pageBreak === 'after') {
1073
- self.writer.moveToNextPage(node.pageOrientation);
1074
- }
1075
- }
1076
- };
1077
-
1078
- // vertical container
1079
- LayoutBuilder.prototype.processVerticalContainer = function (node) {
1080
- var self = this;
1081
- node.stack.forEach(function (item) {
1082
- self.processNode(item);
1083
- addAll(node.positions, item.positions);
1084
-
1085
- //TODO: paragraph gap
1086
- });
1087
- };
1088
-
1089
- // layers
1090
- LayoutBuilder.prototype.processLayers = function(node) {
1091
- var self = this;
1092
- var ctxX = self.writer.context().x;
1093
- var ctxY = self.writer.context().y;
1094
- var maxX = ctxX;
1095
- var maxY = ctxY;
1096
- node.layers.forEach(function(item, i) {
1097
- self.writer.context().x = ctxX;
1098
- self.writer.context().y = ctxY;
1099
- self.processNode(item);
1100
- item._verticalAlignIdx = self.verticalAlignItemStack.length - 1;
1101
- addAll(node.positions, item.positions);
1102
- maxX = self.writer.context().x > maxX ? self.writer.context().x : maxX;
1103
- maxY = self.writer.context().y > maxY ? self.writer.context().y : maxY;
1104
- });
1105
- self.writer.context().x = maxX;
1106
- self.writer.context().y = maxY;
1107
- };
1108
-
1109
- // columns
1110
- LayoutBuilder.prototype.processColumns = function (columnNode) {
1111
- this.nestedLevel++;
1112
- var columns = columnNode.columns;
1113
- var availableWidth = this.writer.context().availableWidth;
1114
- var gaps = gapArray(columnNode._gap);
1115
-
1116
- if (gaps) {
1117
- availableWidth -= (gaps.length - 1) * columnNode._gap;
1118
- }
1119
-
1120
- ColumnCalculator.buildColumnWidths(columns, availableWidth);
1121
- var result = this.processRow({
1122
- marginX: columnNode._margin ? [columnNode._margin[0], columnNode._margin[2]] : [0, 0],
1123
- cells: columns,
1124
- widths: columns,
1125
- gaps
1126
- });
1127
- addAll(columnNode.positions, result.positions);
1128
-
1129
- this.nestedLevel--;
1130
- if (this.nestedLevel === 0) {
1131
- this.writer.context().resetMarginXTopParent();
1132
- }
1133
-
1134
- function gapArray(gap) {
1135
- if (!gap) {
1136
- return null;
1137
- }
1138
-
1139
- var gaps = [];
1140
- gaps.push(0);
1141
-
1142
- for (var i = columns.length - 1; i > 0; i--) {
1143
- gaps.push(gap);
1144
- }
1145
-
1146
- return gaps;
1147
- }
1148
- };
1149
-
1150
- /**
1151
- * Searches for a cell in the same row that starts a rowspan and is positioned immediately before the current cell.
1152
- * Alternatively, it finds a cell where the colspan initiating the rowspan extends to the cell just before the current one.
1153
- *
1154
- * @param {Array<object>} arr - An array representing cells in a row.
1155
- * @param {number} i - The index of the current cell to search backward from.
1156
- * @returns {object|null} The starting cell of the rowspan if found; otherwise, `null`.
1157
- */
1158
- LayoutBuilder.prototype._findStartingRowSpanCell = function (arr, i) {
1159
- var requiredColspan = 1;
1160
- for (var index = i - 1; index >= 0; index--) {
1161
- if (!arr[index]._span) {
1162
- if (arr[index].rowSpan > 1 && (arr[index].colSpan || 1) === requiredColspan) {
1163
- return arr[index];
1164
- } else {
1165
- return null;
1166
- }
1167
- }
1168
- requiredColspan++;
1169
- }
1170
- return null;
1171
- };
1172
-
1173
- /**
1174
- * Retrieves a page break description for a specified page from a list of page breaks.
1175
- *
1176
- * @param {Array<object>} pageBreaks - An array of page break descriptions, each containing `prevPage` properties.
1177
- * @param {number} page - The page number to find the associated page break for.
1178
- * @returns {object|undefined} The page break description object for the specified page if found; otherwise, `undefined`.
1179
- */
1180
- LayoutBuilder.prototype._getPageBreak = function (pageBreaks, page) {
1181
- return pageBreaks.find(desc => desc.prevPage === page);
1182
- };
1183
-
1184
- LayoutBuilder.prototype._getPageBreakListBySpan = function (tableNode, page, rowIndex) {
1185
- if (!tableNode || !tableNode._breaksBySpan) {
1186
- return null;
1187
- }
1188
- const breaksList = tableNode._breaksBySpan.filter(desc => desc.prevPage === page && rowIndex <= desc.rowIndexOfSpanEnd);
1189
-
1190
- var y = Number.MAX_VALUE,
1191
- prevY = Number.MIN_VALUE;
1192
-
1193
- breaksList.forEach(b => {
1194
- prevY = Math.max(b.prevY, prevY);
1195
- y = Math.min(b.y, y);
1196
- });
1197
-
1198
- return {
1199
- prevPage: page,
1200
- prevY: prevY,
1201
- y: y
1202
- };
1203
- };
1204
-
1205
- LayoutBuilder.prototype._findSameRowPageBreakByRowSpanData = function (breaksBySpan, page, rowIndex) {
1206
- if (!breaksBySpan) {
1207
- return null;
1208
- }
1209
- return breaksBySpan.find(desc => desc.prevPage === page && rowIndex === desc.rowIndexOfSpanEnd);
1210
- };
1211
-
1212
- LayoutBuilder.prototype._updatePageBreaksData = function (pageBreaks, tableNode, rowIndex) {
1213
- Object.keys(tableNode._bottomByPage).forEach(p => {
1214
- const page = Number(p);
1215
- const pageBreak = this._getPageBreak(pageBreaks, page);
1216
- if (pageBreak) {
1217
- pageBreak.prevY = Math.max(pageBreak.prevY, tableNode._bottomByPage[page]);
1218
- }
1219
- if (tableNode._breaksBySpan && tableNode._breaksBySpan.length > 0) {
1220
- const breaksBySpanList = tableNode._breaksBySpan.filter(pb => pb.prevPage === page && rowIndex <= pb.rowIndexOfSpanEnd);
1221
- if (breaksBySpanList && breaksBySpanList.length > 0) {
1222
- breaksBySpanList.forEach(b => {
1223
- b.prevY = Math.max(b.prevY, tableNode._bottomByPage[page]);
1224
- });
1225
- }
1226
- }
1227
- });
1228
- };
1229
-
1230
- /**
1231
- * Resolves the Y-coordinates for a target object by comparing two break points.
1232
- *
1233
- * @param {object} break1 - The first break point with `prevY` and `y` properties.
1234
- * @param {object} break2 - The second break point with `prevY` and `y` properties.
1235
- * @param {object} target - The target object to be updated with resolved Y-coordinates.
1236
- * @property {number} target.prevY - Updated to the maximum `prevY` value between `break1` and `break2`.
1237
- * @property {number} target.y - Updated to the minimum `y` value between `break1` and `break2`.
1238
- */
1239
- LayoutBuilder.prototype._resolveBreakY = function (break1, break2, target) {
1240
- target.prevY = Math.max(break1.prevY, break2.prevY);
1241
- target.y = Math.min(break1.y, break2.y);
1242
- };
1243
-
1244
- LayoutBuilder.prototype._storePageBreakData = function (data, startsRowSpan, pageBreaks, tableNode) {
1245
- var pageDesc;
1246
- var pageDescBySpan;
1247
-
1248
- if (!startsRowSpan) {
1249
- pageDesc = this._getPageBreak(pageBreaks, data.prevPage);
1250
- pageDescBySpan = this._getPageBreakListBySpan(tableNode, data.prevPage, data.rowIndex);
1251
- if (!pageDesc) {
1252
- pageDesc = Object.assign({}, data);
1253
- pageBreaks.push(pageDesc);
1254
- }
1255
-
1256
- if (pageDescBySpan) {
1257
- this._resolveBreakY(pageDesc, pageDescBySpan, pageDesc);
1258
- }
1259
- this._resolveBreakY(pageDesc, data, pageDesc);
1260
- } else {
1261
- var breaksBySpan = tableNode && tableNode._breaksBySpan || null;
1262
- pageDescBySpan = this._findSameRowPageBreakByRowSpanData(breaksBySpan, data.prevPage, data.rowIndex);
1263
- if (!pageDescBySpan) {
1264
- pageDescBySpan = Object.assign({}, data, {
1265
- rowIndexOfSpanEnd: data.rowIndex + data.rowSpan - 1
1266
- });
1267
- if (!tableNode._breaksBySpan) {
1268
- tableNode._breaksBySpan = [];
1269
- }
1270
- tableNode._breaksBySpan.push(pageDescBySpan);
1271
- }
1272
- pageDescBySpan.prevY = Math.max(pageDescBySpan.prevY, data.prevY);
1273
- pageDescBySpan.y = Math.min(pageDescBySpan.y, data.y);
1274
- pageDesc = this._getPageBreak(pageBreaks, data.prevPage);
1275
- if (pageDesc) {
1276
- this._resolveBreakY(pageDesc, pageDescBySpan, pageDesc);
1277
- }
1278
- }
1279
- };
1280
-
1281
- /**
1282
- * Calculates the left offset for a column based on the specified gap values.
1283
- *
1284
- * @param {number} i - The index of the column for which the offset is being calculated.
1285
- * @param {Array<number>} gaps - An array of gap values for each column.
1286
- * @returns {number} The left offset for the column. Returns `gaps[i]` if it exists, otherwise `0`.
1287
- */
1288
- LayoutBuilder.prototype._colLeftOffset = function (i, gaps) {
1289
- if (gaps && gaps.length > i) {
1290
- return gaps[i];
1291
- }
1292
- return 0;
1293
- };
1294
-
1295
- /**
1296
- * Checks if a cell or node contains an inline image.
1297
- *
1298
- * @param {object} node - The node to check for inline images.
1299
- * @returns {boolean} True if the node contains an inline image; otherwise, false.
1300
- */
1301
- LayoutBuilder.prototype._containsInlineImage = function (node) {
1302
- if (!node) {
1303
- return false;
1304
- }
1305
-
1306
- // Direct image node
1307
- if (node.image) {
1308
- return true;
1309
- }
1310
-
1311
-
1312
- // Check in table
1313
- if (node.table && isArray(node.table.body)) {
1314
- for (var r = 0; r < node.table.body.length; r++) {
1315
- if (isArray(node.table.body[r])) {
1316
- for (var c = 0; c < node.table.body[r].length; c++) {
1317
- if (this._containsInlineImage(node.table.body[r][c])) {
1318
- return true;
1319
- }
1320
- }
1321
- }
1322
- }
1323
- }
1324
-
1325
- return false;
1326
- };
1327
-
1328
-
1329
- /**
1330
- * Gets the maximum image height from cells in a row.
1331
- *
1332
- * @param {Array<object>} cells - Array of cell objects in a row.
1333
- * @returns {number} The maximum image height found in the cells.
1334
- */
1335
- LayoutBuilder.prototype._getMaxImageHeight = function (cells) {
1336
- var maxHeight = 0;
1337
-
1338
- for (var i = 0; i < cells.length; i++) {
1339
- var cellHeight = this._getImageHeightFromNode(cells[i]);
1340
- if (cellHeight > maxHeight) {
1341
- maxHeight = cellHeight;
1342
- }
1343
- }
1344
-
1345
- return maxHeight;
1346
- };
1347
-
1348
- /**
1349
- * Gets the maximum estimated height from cells in a row.
1350
- * Checks for measured heights (_height property) and content-based heights.
1351
- *
1352
- * @param {Array<object>} cells - Array of cell objects in a row.
1353
- * @returns {number} The maximum estimated height found in the cells, or 0 if cannot estimate.
1354
- */
1355
- LayoutBuilder.prototype._getMaxCellHeight = function (cells) {
1356
- var maxHeight = 0;
1357
-
1358
- for (var i = 0; i < cells.length; i++) {
1359
- var cell = cells[i];
1360
- if (!cell || cell._span) {
1361
- continue; // Skip null cells and span placeholders
1362
- }
1363
-
1364
- var cellHeight = 0;
1365
-
1366
- // Check if cell has measured height from docMeasure phase
1367
- if (cell._height) {
1368
- cellHeight = cell._height;
1369
- }
1370
- // Check for image content
1371
- else if (cell.image && cell._maxHeight) {
1372
- cellHeight = cell._maxHeight;
1373
- }
1374
- // Check for nested content with height
1375
- else {
1376
- cellHeight = this._getImageHeightFromNode(cell);
1377
- }
1378
-
1379
- if (cellHeight > maxHeight) {
1380
- maxHeight = cellHeight;
1381
- }
1382
- }
1383
-
1384
- return maxHeight;
1385
- };
1386
-
1387
- /**
1388
- * Recursively gets image height from a node.
1389
- *
1390
- * @param {object} node - The node to extract image height from.
1391
- * @returns {number} The image height if found; otherwise, 0.
1392
- */
1393
- LayoutBuilder.prototype._getImageHeightFromNode = function (node) {
1394
- if (!node) {
1395
- return 0;
1396
- }
1397
-
1398
- // Direct image node with height
1399
- if (node.image && node._height) {
1400
- return node._height;
1401
- }
1402
-
1403
- var maxHeight = 0;
1404
-
1405
- // Check in stack
1406
- if (isArray(node.stack)) {
1407
- for (var i = 0; i < node.stack.length; i++) {
1408
- var h = this._getImageHeightFromNode(node.stack[i]);
1409
- if (h > maxHeight) {
1410
- maxHeight = h;
1411
- }
1412
- }
1413
- }
1414
-
1415
- // Check in columns
1416
- if (isArray(node.columns)) {
1417
- for (var j = 0; j < node.columns.length; j++) {
1418
- var h2 = this._getImageHeightFromNode(node.columns[j]);
1419
- if (h2 > maxHeight) {
1420
- maxHeight = h2;
1421
- }
1422
- }
1423
- }
1424
-
1425
- // Check in table
1426
- if (node.table && isArray(node.table.body)) {
1427
- for (var r = 0; r < node.table.body.length; r++) {
1428
- if (isArray(node.table.body[r])) {
1429
- for (var c = 0; c < node.table.body[r].length; c++) {
1430
- var h3 = this._getImageHeightFromNode(node.table.body[r][c]);
1431
- if (h3 > maxHeight) {
1432
- maxHeight = h3;
1433
- }
1434
- }
1435
- }
1436
- }
1437
- }
1438
-
1439
- return maxHeight;
1440
- };
1441
-
1442
-
1443
- /**
1444
- * Retrieves the ending cell for a row span in case it exists in a specified table column.
1445
- *
1446
- * @param {Array<Array<object>>} tableBody - The table body, represented as a 2D array of cell objects.
1447
- * @param {number} rowIndex - The index of the starting row for the row span.
1448
- * @param {object} column - The column object containing row span information.
1449
- * @param {number} columnIndex - The index of the column within the row.
1450
- * @returns {object|null} The cell at the end of the row span if it exists; otherwise, `null`.
1451
- * @throws {Error} If the row span extends beyond the total row count.
1452
- */
1453
- LayoutBuilder.prototype._getRowSpanEndingCell = function (tableBody, rowIndex, column, columnIndex) {
1454
- if (column.rowSpan && column.rowSpan > 1) {
1455
- var endingRow = rowIndex + column.rowSpan - 1;
1456
- if (endingRow >= tableBody.length) {
1457
- throw new Error(`Row span for column ${columnIndex} (with indexes starting from 0) exceeded row count`);
1458
- }
1459
- return tableBody[endingRow][columnIndex];
1460
- }
1461
-
1462
- return null;
1463
- };
1464
-
1465
- LayoutBuilder.prototype.processRow = function ({ marginX = [0, 0], dontBreakRows = false, rowsWithoutPageBreak = 0, cells, widths, gaps, tableNode, tableBody, rowIndex, height, heightOffset = 0 }) {
1466
- var self = this;
1467
- var isUnbreakableRow = dontBreakRows || rowIndex <= rowsWithoutPageBreak - 1;
1468
- var pageBreaks = [];
1469
- var pageBreaksByRowSpan = [];
1470
- var positions = [];
1471
- var willBreakByHeight = false;
1472
- var columnAlignIndexes = {};
1473
- var hasInlineImage = false;
1474
- widths = widths || cells;
1475
-
1476
- // Check if row contains inline images
1477
- if (!isUnbreakableRow) {
1478
- for (var cellIdx = 0; cellIdx < cells.length; cellIdx++) {
1479
- if (self._containsInlineImage(cells[cellIdx])) {
1480
- hasInlineImage = true;
1481
- break;
1482
- }
1483
- }
1484
- }
1485
-
1486
- // Check if row would cause page break and force move to next page first
1487
- // This keeps the entire row together on the new page
1488
- // Apply when: forcePageBreakForAllRows is enabled OR row has inline images
1489
-
1490
- // Priority for forcePageBreakForAllRows setting:
1491
- // 1. Table-specific layout.forcePageBreakForAllRows
1492
- // 2. Tables with footerGapCollect: 'product-items' (auto-enabled)
1493
- // 3. Global footerGapOption.forcePageBreakForAllRows
1494
- var tableLayout = tableNode && tableNode._layout;
1495
- var footerGapOpt = self.writer.context()._footerGapOption;
1496
- var shouldForcePageBreak = false;
1497
-
1498
- if (tableLayout && tableLayout.forcePageBreakForAllRows !== undefined) {
1499
- // Table-specific setting takes precedence
1500
- shouldForcePageBreak = tableLayout.forcePageBreakForAllRows === true;
1501
- }
1502
-
1503
- if (!isUnbreakableRow && (shouldForcePageBreak || hasInlineImage)) {
1504
- var availableHeight = self.writer.context().availableHeight;
1505
-
1506
- // Calculate estimated height from actual cell content
1507
- var estimatedHeight = height; // Use provided height if available
1508
-
1509
- if (!estimatedHeight) {
1510
- // Try to get maximum cell height from measured content
1511
- var maxCellHeight = self._getMaxCellHeight(cells);
1512
-
1513
- if (maxCellHeight > 0) {
1514
- // Add padding for table borders and cell padding (approximate)
1515
- // Using smaller padding to avoid overly conservative page break detection
1516
- var tablePadding = 10; // Account for row padding and borders
1517
- estimatedHeight = maxCellHeight + tablePadding;
1518
- } else {
1519
- // Fallback: use minRowHeight from table layout or global config if provided
1520
- // Priority: table-specific layout > global footerGapOption > default 80
1521
- // Using higher default (80px) to handle text rows with wrapping and multiple lines
1522
- // This is conservative but prevents text rows from being split across pages
1523
- var minRowHeight = (tableLayout && tableLayout.minRowHeight) || (footerGapOpt && footerGapOpt.minRowHeight) || 80;
1524
- estimatedHeight = minRowHeight;
1525
- }
1526
- }
1527
-
1528
- // Apply heightOffset from table definition to adjust page break calculation
1529
- // This allows fine-tuning of page break detection for specific tables
1530
- // heightOffset is passed as parameter from processTable
1531
- if (heightOffset) {
1532
- estimatedHeight = (estimatedHeight || 0) + heightOffset;
1533
- }
1534
-
1535
- // Check if row won't fit on current page
1536
- // Strategy: Force break if row won't fit AND we're not too close to page boundary
1537
- // "Too close" means availableHeight is very small (< 5px) - at that point forcing
1538
- // a break would create a nearly-blank page
1539
- var minSpaceThreshold = 5; // Only skip forced break if < 5px space left
1540
-
1541
- if (estimatedHeight > availableHeight && availableHeight > minSpaceThreshold) {
1542
- var currentPage = self.writer.context().page;
1543
- var currentY = self.writer.context().y;
1544
-
1545
- // Draw vertical lines to fill the gap from current position to page break
1546
- // This ensures vertical lines extend all the way to the bottom of the page
1547
- if (tableNode && tableNode._tableProcessor && rowIndex > 0) {
1548
- tableNode._tableProcessor.drawVerticalLinesForForcedPageBreak(
1549
- rowIndex,
1550
- self.writer,
1551
- currentY,
1552
- currentY + availableHeight
1553
- );
1554
- }
1555
-
1556
- // Move to next page before processing row
1557
- self.writer.context().moveDown(availableHeight);
1558
- self.writer.moveToNextPage();
1559
-
1560
- // Track this page break so tableProcessor can draw borders correctly
1561
- pageBreaks.push({
1562
- prevPage: currentPage,
1563
- prevY: currentY + availableHeight,
1564
- y: self.writer.context().y,
1565
- page: self.writer.context().page,
1566
- forced: true // Mark as forced page break
1567
- });
1568
-
1569
- // Mark that this row should not break anymore
1570
- isUnbreakableRow = true;
1571
- dontBreakRows = true;
1572
- }
1573
- }
1574
-
1575
- // Check if row should break by height
1576
- if (!isUnbreakableRow && height > self.writer.context().availableHeight) {
1577
- willBreakByHeight = true;
1578
- }
1579
-
1580
- // Use the marginX if we are in a top level table/column (not nested)
1581
- const marginXParent = self.nestedLevel === 1 ? marginX : null;
1582
- const _bottomByPage = tableNode ? tableNode._bottomByPage : null;
1583
- this.writer.context().beginColumnGroup(marginXParent, _bottomByPage);
1584
-
1585
- for (var i = 0, l = cells.length; i < l; i++) {
1586
- var cell = cells[i];
1587
-
1588
- // Page change handler
1589
-
1590
- this.tracker.auto('pageChanged', storePageBreakClosure, function () {
1591
- var width = widths[i]._calcWidth;
1592
- var leftOffset = self._colLeftOffset(i, gaps);
1593
- // Check if exists and retrieve the cell that started the rowspan in case we are in the cell just after
1594
- var startingSpanCell = self._findStartingRowSpanCell(cells, i);
1595
-
1596
- if (cell.colSpan && cell.colSpan > 1) {
1597
- for (var j = 1; j < cell.colSpan; j++) {
1598
- width += widths[++i]._calcWidth + gaps[i];
1599
- }
1600
- }
1601
-
1602
- // if rowspan starts in this cell, we retrieve the last cell affected by the rowspan
1603
- const rowSpanEndingCell = self._getRowSpanEndingCell(tableBody, rowIndex, cell, i);
1604
- if (rowSpanEndingCell) {
1605
- // We store a reference of the ending cell in the first cell of the rowspan
1606
- cell._endingCell = rowSpanEndingCell;
1607
- cell._endingCell._startingRowSpanY = cell._startingRowSpanY;
1608
- }
1609
-
1610
- // If we are after a cell that started a rowspan
1611
- var endOfRowSpanCell = null;
1612
- if (startingSpanCell && startingSpanCell._endingCell) {
1613
- // Reference to the last cell of the rowspan
1614
- endOfRowSpanCell = startingSpanCell._endingCell;
1615
- // Store if we are in an unbreakable block when we save the context and the originalX
1616
- if (self.writer.transactionLevel > 0) {
1617
- endOfRowSpanCell._isUnbreakableContext = true;
1618
- endOfRowSpanCell._originalXOffset = self.writer.originalX;
1619
- }
1620
- }
1621
-
1622
- // We pass the endingSpanCell reference to store the context just after processing rowspan cell
1623
- self.writer.context().beginColumn(width, leftOffset, endOfRowSpanCell, heightOffset);
1624
-
1625
- if (!cell._span) {
1626
- self.processNode(cell);
1627
- self.writer.context().updateBottomByPage();
1628
- addAll(positions, cell.positions);
1629
- if (cell.verticalAlign && cell._verticalAlignIdx !== undefined) {
1630
- columnAlignIndexes[i] = cell._verticalAlignIdx;
1631
- }
1632
- } else if (cell._columnEndingContext) {
1633
- var discountY = 0;
1634
- if (dontBreakRows) {
1635
- // Calculate how many points we have to discount to Y when dontBreakRows and rowSpan are combined
1636
- const ctxBeforeRowSpanLastRow = self.writer.writer.contextStack[self.writer.writer.contextStack.length - 1];
1637
- discountY = ctxBeforeRowSpanLastRow.y - cell._startingRowSpanY;
1638
- }
1639
- var originalXOffset = 0;
1640
- // If context was saved from an unbreakable block and we are not in an unbreakable block anymore
1641
- // We have to sum the originalX (X before starting unbreakable block) to X
1642
- if (cell._isUnbreakableContext && !self.writer.transactionLevel) {
1643
- originalXOffset = cell._originalXOffset;
1644
- }
1645
- // row-span ending
1646
- // Recover the context after processing the rowspanned cell
1647
- self.writer.context().markEnding(cell, originalXOffset, discountY);
1648
- }
1649
- });
1650
- }
1651
-
1652
- // Check if last cell is part of a span
1653
- var endingSpanCell = null;
1654
- var lastColumn = cells.length > 0 ? cells[cells.length - 1] : null;
1655
- if (lastColumn) {
1656
- // Previous column cell has a rowspan
1657
- if (lastColumn._endingCell) {
1658
- endingSpanCell = lastColumn._endingCell;
1659
- // Previous column cell is part of a span
1660
- } else if (lastColumn._span === true) {
1661
- // We get the cell that started the span where we set a reference to the ending cell
1662
- const startingSpanCell = this._findStartingRowSpanCell(cells, cells.length);
1663
- if (startingSpanCell) {
1664
- // Context will be stored here (ending cell)
1665
- endingSpanCell = startingSpanCell._endingCell;
1666
- // Store if we are in an unbreakable block when we save the context and the originalX
1667
- if (this.writer.transactionLevel > 0) {
1668
- endingSpanCell._isUnbreakableContext = true;
1669
- endingSpanCell._originalXOffset = this.writer.originalX;
1670
- }
1671
- }
1672
- }
1673
- }
1674
-
1675
- // If content did not break page, check if we should break by height
1676
- if (willBreakByHeight && !isUnbreakableRow && pageBreaks.length === 0) {
1677
- this.writer.context().moveDown(this.writer.context().availableHeight);
1678
- this.writer.moveToNextPage();
1679
- }
1680
-
1681
- var bottomByPage = this.writer.context().completeColumnGroup(height, endingSpanCell);
1682
- var rowHeight = this.writer.context().height;
1683
- for (var colIndex = 0, columnsLength = cells.length; colIndex < columnsLength; colIndex++) {
1684
- var columnNode = cells[colIndex];
1685
- if (columnNode._span) {
1686
- continue;
1687
- }
1688
- if (columnNode.verticalAlign && columnAlignIndexes[colIndex] !== undefined) {
1689
- var alignEntry = self.verticalAlignItemStack[columnAlignIndexes[colIndex]];
1690
- if (alignEntry && alignEntry.begin && alignEntry.begin.item) {
1691
- alignEntry.begin.item.viewHeight = rowHeight;
1692
- alignEntry.begin.item.nodeHeight = columnNode._height;
1693
- }
1694
- }
1695
- if (columnNode.layers) {
1696
- columnNode.layers.forEach(function (layer) {
1697
- if (layer.verticalAlign && layer._verticalAlignIdx !== undefined) {
1698
- var layerEntry = self.verticalAlignItemStack[layer._verticalAlignIdx];
1699
- if (layerEntry && layerEntry.begin && layerEntry.begin.item) {
1700
- layerEntry.begin.item.viewHeight = rowHeight;
1701
- layerEntry.begin.item.nodeHeight = layer._height;
1702
- }
1703
- }
1704
- });
1705
- }
1706
- }
1707
-
1708
- if (tableNode) {
1709
- tableNode._bottomByPage = bottomByPage;
1710
- // If there are page breaks in this row, update data with prevY of last cell
1711
- this._updatePageBreaksData(pageBreaks, tableNode, rowIndex);
1712
- }
1713
-
1714
- return {
1715
- pageBreaksBySpan: pageBreaksByRowSpan,
1716
- pageBreaks: pageBreaks,
1717
- positions: positions
1718
- };
1719
-
1720
- function storePageBreakClosure(data) {
1721
- const startsRowSpan = cell.rowSpan && cell.rowSpan > 1;
1722
- if (startsRowSpan) {
1723
- data.rowSpan = cell.rowSpan;
1724
- }
1725
- data.rowIndex = rowIndex;
1726
- self._storePageBreakData(data, startsRowSpan, pageBreaks, tableNode);
1727
- }
1728
-
1729
- };
1730
-
1731
- // lists
1732
- LayoutBuilder.prototype.processList = function (orderedList, node) {
1733
- var self = this,
1734
- items = orderedList ? node.ol : node.ul,
1735
- gapSize = node._gapSize;
1736
-
1737
- this.writer.context().addMargin(gapSize.width);
1738
-
1739
- var nextMarker;
1740
- this.tracker.auto('lineAdded', addMarkerToFirstLeaf, function () {
1741
- items.forEach(function (item) {
1742
- nextMarker = item.listMarker;
1743
- self.processNode(item);
1744
- addAll(node.positions, item.positions);
1745
- });
1746
- });
1747
-
1748
- this.writer.context().addMargin(-gapSize.width);
1749
-
1750
- function addMarkerToFirstLeaf(line) {
1751
- // I'm not very happy with the way list processing is implemented
1752
- // (both code and algorithm should be rethinked)
1753
- if (nextMarker) {
1754
- var marker = nextMarker;
1755
- nextMarker = null;
1756
-
1757
- if (marker.canvas) {
1758
- var vector = marker.canvas[0];
1759
-
1760
- offsetVector(vector, -marker._minWidth, 0);
1761
- self.writer.addVector(vector);
1762
- } else if (marker._inlines) {
1763
- var markerLine = new Line(self.pageSize.width);
1764
- markerLine.addInline(marker._inlines[0]);
1765
- markerLine.x = -marker._minWidth;
1766
- markerLine.y = line.getAscenderHeight() - markerLine.getAscenderHeight();
1767
- self.writer.addLine(markerLine, true);
1768
- }
1769
- }
1770
- }
1771
- };
1772
-
1773
- // tables
1774
- LayoutBuilder.prototype.processTable = function (tableNode) {
1775
- this.nestedLevel++;
1776
- var processor = new TableProcessor(tableNode);
1777
-
1778
- // Store processor reference for forced page break vertical line drawing
1779
- tableNode._tableProcessor = processor;
1780
-
1781
- processor.beginTable(this.writer);
1782
-
1783
- var rowHeights = tableNode.table.heights;
1784
- for (var i = 0, l = tableNode.table.body.length; i < l; i++) {
1785
- // if dontBreakRows and row starts a rowspan
1786
- // we store the 'y' of the beginning of each rowSpan
1787
- if (processor.dontBreakRows) {
1788
- tableNode.table.body[i].forEach(cell => {
1789
- if (cell.rowSpan && cell.rowSpan > 1) {
1790
- cell._startingRowSpanY = this.writer.context().y;
1791
- }
1792
- });
1793
- }
1794
-
1795
- processor.beginRow(i, this.writer);
1796
-
1797
- var height;
1798
- if (isFunction(rowHeights)) {
1799
- height = rowHeights(i);
1800
- } else if (isArray(rowHeights)) {
1801
- height = rowHeights[i];
1802
- } else {
1803
- height = rowHeights;
1804
- }
1805
-
1806
- if (height === 'auto') {
1807
- height = undefined;
1808
- }
1809
-
1810
- var heightOffset = tableNode.heightOffset != undefined ? tableNode.heightOffset : 0;
1811
-
1812
- var pageBeforeProcessing = this.writer.context().page;
1813
-
1814
- var result = this.processRow({
1815
- marginX: tableNode._margin ? [tableNode._margin[0], tableNode._margin[2]] : [0, 0],
1816
- dontBreakRows: processor.dontBreakRows,
1817
- rowsWithoutPageBreak: processor.rowsWithoutPageBreak,
1818
- cells: tableNode.table.body[i],
1819
- widths: tableNode.table.widths,
1820
- gaps: tableNode._offsets.offsets,
1821
- tableBody: tableNode.table.body,
1822
- tableNode,
1823
- rowIndex: i,
1824
- height,
1825
- heightOffset
1826
- });
1827
- addAll(tableNode.positions, result.positions);
1828
-
1829
- if (!result.pageBreaks || result.pageBreaks.length === 0) {
1830
- var breaksBySpan = tableNode && tableNode._breaksBySpan || null;
1831
- var breakBySpanData = this._findSameRowPageBreakByRowSpanData(breaksBySpan, pageBeforeProcessing, i);
1832
- if (breakBySpanData) {
1833
- var finalBreakBySpanData = this._getPageBreakListBySpan(tableNode, breakBySpanData.prevPage, i);
1834
- result.pageBreaks.push(finalBreakBySpanData);
1835
- }
1836
- }
1837
-
1838
- // Get next row cells for look-ahead page break detection
1839
- var nextRowCells = (i + 1 < tableNode.table.body.length) ? tableNode.table.body[i + 1] : null;
1840
-
1841
- processor.endRow(i, this.writer, result.pageBreaks, nextRowCells, this);
1842
- }
1843
-
1844
- processor.endTable(this.writer);
1845
- this.nestedLevel--;
1846
- if (this.nestedLevel === 0) {
1847
- this.writer.context().resetMarginXTopParent();
1848
- }
1849
- };
1850
-
1851
- // leafs (texts)
1852
- LayoutBuilder.prototype.processLeaf = function (node) {
1853
- var line = this.buildNextLine(node);
1854
- if (line && (node.tocItem || node.id)) {
1855
- line._node = node;
1856
- }
1857
- var currentHeight = (line) ? line.getHeight() : 0;
1858
- var maxHeight = node.maxHeight || -1;
1859
-
1860
- if (line) {
1861
- var nodeId = getNodeId(node);
1862
- if (nodeId) {
1863
- line.id = nodeId;
1864
- }
1865
- }
1866
-
1867
- if (node._tocItemRef) {
1868
- line._pageNodeRef = node._tocItemRef;
1869
- }
1870
-
1871
- if (node._pageRef) {
1872
- line._pageNodeRef = node._pageRef._nodeRef;
1873
- }
1874
-
1875
- if (line && line.inlines && isArray(line.inlines)) {
1876
- for (var i = 0, l = line.inlines.length; i < l; i++) {
1877
- if (line.inlines[i]._tocItemRef) {
1878
- line.inlines[i]._pageNodeRef = line.inlines[i]._tocItemRef;
1879
- }
1880
-
1881
- if (line.inlines[i]._pageRef) {
1882
- line.inlines[i]._pageNodeRef = line.inlines[i]._pageRef._nodeRef;
1883
- }
1884
- }
1885
- }
1886
-
1887
- while (line && (maxHeight === -1 || currentHeight < maxHeight)) {
1888
- var positions = this.writer.addLine(line);
1889
- node.positions.push(positions);
1890
- line = this.buildNextLine(node);
1891
- if (line) {
1892
- currentHeight += line.getHeight();
1893
- }
1894
- }
1895
- };
1896
-
1897
- LayoutBuilder.prototype.processToc = function (node) {
1898
- if (node.toc.title) {
1899
- this.processNode(node.toc.title);
1900
- }
1901
- if (node.toc._table) {
1902
- this.processNode(node.toc._table);
1903
- }
1904
- };
1905
-
1906
- LayoutBuilder.prototype.buildNextLine = function (textNode) {
1907
-
1908
- function cloneInline(inline) {
1909
- var newInline = inline.constructor();
1910
- for (var key in inline) {
1911
- newInline[key] = inline[key];
1912
- }
1913
- return newInline;
1914
- }
1915
-
1916
- if (!textNode._inlines || textNode._inlines.length === 0) {
1917
- return null;
1918
- }
1919
-
1920
- var line = new Line(this.writer.context().availableWidth);
1921
- var textTools = new TextTools(null);
1922
-
1923
- while (textNode._inlines && textNode._inlines.length > 0 && line.hasEnoughSpaceForInline(textNode._inlines[0])) {
1924
- var inline = textNode._inlines.shift();
1925
-
1926
- if (!inline.noWrap && inline.text.length > 1 && inline.width > line.maxWidth) {
1927
- var widthPerChar = inline.width / inline.text.length;
1928
- var maxChars = Math.floor(line.maxWidth / widthPerChar);
1929
- if (maxChars < 1) {
1930
- maxChars = 1;
1931
- }
1932
- if (maxChars < inline.text.length) {
1933
- var newInline = cloneInline(inline);
1934
-
1935
- newInline.text = inline.text.substr(maxChars);
1936
- inline.text = inline.text.substr(0, maxChars);
1937
-
1938
- newInline.width = textTools.widthOfString(newInline.text, newInline.font, newInline.fontSize, newInline.characterSpacing);
1939
- inline.width = textTools.widthOfString(inline.text, inline.font, inline.fontSize, inline.characterSpacing);
1940
-
1941
- textNode._inlines.unshift(newInline);
1942
- }
1943
- }
1944
-
1945
- line.addInline(inline);
1946
- }
1947
-
1948
- line.lastLineInParagraph = textNode._inlines.length === 0;
1949
-
1950
- return line;
1951
- };
1952
-
1953
- // images
1954
- LayoutBuilder.prototype.processImage = function (node) {
1955
- var position = this.writer.addImage(node);
1956
- node.positions.push(position);
1957
- };
1958
-
1959
- LayoutBuilder.prototype.processSVG = function (node) {
1960
- var position = this.writer.addSVG(node);
1961
- node.positions.push(position);
1962
- };
1963
-
1964
- LayoutBuilder.prototype.processCanvas = function (node) {
1965
- var height = node._minHeight;
1966
-
1967
- if (node.absolutePosition === undefined && this.writer.context().availableHeight < height) {
1968
- // TODO: support for canvas larger than a page
1969
- // TODO: support for other overflow methods
1970
-
1971
- this.writer.moveToNextPage();
1972
- }
1973
-
1974
- this.writer.alignCanvas(node);
1975
-
1976
- node.canvas.forEach(function (vector) {
1977
- var position = this.writer.addVector(vector);
1978
- node.positions.push(position);
1979
- }, this);
1980
-
1981
- this.writer.context().moveDown(height);
1982
- };
1983
-
1984
- LayoutBuilder.prototype.processQr = function (node) {
1985
- var position = this.writer.addQr(node);
1986
- node.positions.push(position);
1987
- };
1988
-
1989
- function processNode_test(node) {
1990
- decorateNode(node);
1991
-
1992
- var prevTop = testWriter.context().getCurrentPosition().top;
1993
-
1994
- applyMargins(function () {
1995
- var unbreakable = node.unbreakable;
1996
- if (unbreakable) {
1997
- testWriter.beginUnbreakableBlock();
1998
- }
1999
-
2000
- var absPosition = node.absolutePosition;
2001
- if (absPosition) {
2002
- testWriter.context().beginDetachedBlock();
2003
- testWriter.context().moveTo(absPosition.x || 0, absPosition.y || 0);
2004
- }
2005
-
2006
- var relPosition = node.relativePosition;
2007
- if (relPosition) {
2008
- testWriter.context().beginDetachedBlock();
2009
- if (typeof testWriter.context().moveToRelative === 'function') {
2010
- testWriter.context().moveToRelative(relPosition.x || 0, relPosition.y || 0);
2011
- } else if (currentLayoutBuilder && currentLayoutBuilder.writer) {
2012
- testWriter.context().moveTo(
2013
- (relPosition.x || 0) + currentLayoutBuilder.writer.context().x,
2014
- (relPosition.y || 0) + currentLayoutBuilder.writer.context().y
2015
- );
2016
- }
2017
- }
2018
-
2019
- var verticalAlignBegin;
2020
- if (node.verticalAlign) {
2021
- verticalAlignBegin = testWriter.beginVerticalAlign(node.verticalAlign);
2022
- }
2023
-
2024
- if (node.stack) {
2025
- processVerticalContainer_test(node);
2026
- } else if (node.table) {
2027
- processTable_test(node);
2028
- } else if (node.text !== undefined) {
2029
- processLeaf_test(node);
2030
- }
2031
-
2032
- if (absPosition || relPosition) {
2033
- testWriter.context().endDetachedBlock();
2034
- }
2035
-
2036
- if (unbreakable) {
2037
- testResult = testWriter.commitUnbreakableBlock_test();
2038
- }
2039
-
2040
- if (node.verticalAlign) {
2041
- testVerticalAlignStack.push({ begin: verticalAlignBegin, end: testWriter.endVerticalAlign(node.verticalAlign) });
2042
- }
2043
- });
2044
-
2045
- node._height = testWriter.context().getCurrentPosition().top - prevTop;
2046
-
2047
- function applyMargins(callback) {
2048
- var margin = node._margin;
2049
-
2050
- if (node.pageBreak === 'before') {
2051
- testWriter.moveToNextPage(node.pageOrientation);
2052
- }
2053
-
2054
- if (margin) {
2055
- testWriter.context().moveDown(margin[1]);
2056
- testWriter.context().addMargin(margin[0], margin[2]);
2057
- }
2058
-
2059
- callback();
2060
-
2061
- if (margin) {
2062
- testWriter.context().addMargin(-margin[0], -margin[2]);
2063
- testWriter.context().moveDown(margin[3]);
2064
- }
2065
-
2066
- if (node.pageBreak === 'after') {
2067
- testWriter.moveToNextPage(node.pageOrientation);
2068
- }
2069
- }
2070
- }
2071
-
2072
- function processVerticalContainer_test(node) {
2073
- node.stack.forEach(function (item) {
2074
- processNode_test(item);
2075
- addAll(node.positions, item.positions);
2076
- });
2077
- }
2078
-
2079
- function processTable_test(tableNode) {
2080
- var processor = new TableProcessor(tableNode);
2081
- processor.beginTable(testWriter);
2082
-
2083
- for (var i = 0, l = tableNode.table.body.length; i < l; i++) {
2084
- processor.beginRow(i, testWriter);
2085
- var result = processRow_test(tableNode.table.body[i], tableNode.table.widths, tableNode._offsets ? tableNode._offsets.offsets : null, tableNode.table.body, i);
2086
- addAll(tableNode.positions, result.positions);
2087
- processor.endRow(i, testWriter, result.pageBreaks);
2088
- }
2089
-
2090
- processor.endTable(testWriter);
2091
- }
2092
-
2093
- function processRow_test(columns, widths, gaps, tableBody, tableRow) {
2094
- var pageBreaks = [];
2095
- var positions = [];
2096
-
2097
- testTracker.auto('pageChanged', storePageBreakData, function () {
2098
- widths = widths || columns;
2099
-
2100
- testWriter.context().beginColumnGroup();
2101
-
2102
- var verticalAlignCols = {};
2103
-
2104
- for (var i = 0, l = columns.length; i < l; i++) {
2105
- var column = columns[i];
2106
- var width = widths[i]._calcWidth || widths[i];
2107
- var leftOffset = colLeftOffset(i);
2108
- var colIndex = i;
2109
- if (column.colSpan && column.colSpan > 1) {
2110
- for (var j = 1; j < column.colSpan; j++) {
2111
- width += (widths[++i]._calcWidth || widths[i]) + (gaps ? gaps[i] : 0);
2112
- }
2113
- }
2114
-
2115
- testWriter.context().beginColumn(width, leftOffset, getEndingCell(column, i));
2116
-
2117
- if (!column._span) {
2118
- processNode_test(column);
2119
- verticalAlignCols[colIndex] = testVerticalAlignStack.length - 1;
2120
- addAll(positions, column.positions);
2121
- } else if (column._columnEndingContext) {
2122
- testWriter.context().markEnding(column);
2123
- }
2124
- }
2125
-
2126
- testWriter.context().completeColumnGroup();
2127
-
2128
- var rowHeight = testWriter.context().height;
2129
- for (var c = 0, clen = columns.length; c < clen; c++) {
2130
- var col = columns[c];
2131
- if (col._span) {
2132
- continue;
2133
- }
2134
- if (col.verticalAlign && verticalAlignCols[c] !== undefined) {
2135
- var alignItem = testVerticalAlignStack[verticalAlignCols[c]].begin.item;
2136
- alignItem.viewHeight = rowHeight;
2137
- alignItem.nodeHeight = col._height;
2138
- }
2139
- }
2140
- });
2141
-
2142
- return { pageBreaks: pageBreaks, positions: positions };
2143
-
2144
- function storePageBreakData(data) {
2145
- var pageDesc;
2146
- for (var idx = 0, len = pageBreaks.length; idx < len; idx++) {
2147
- var desc = pageBreaks[idx];
2148
- if (desc.prevPage === data.prevPage) {
2149
- pageDesc = desc;
2150
- break;
2151
- }
2152
- }
2153
-
2154
- if (!pageDesc) {
2155
- pageDesc = data;
2156
- pageBreaks.push(pageDesc);
2157
- }
2158
- pageDesc.prevY = Math.max(pageDesc.prevY, data.prevY);
2159
- pageDesc.y = Math.min(pageDesc.y, data.y);
2160
- }
2161
-
2162
- function colLeftOffset(i) {
2163
- if (gaps && gaps.length > i) {
2164
- return gaps[i];
2165
- }
2166
- return 0;
2167
- }
2168
-
2169
- function getEndingCell(column, columnIndex) {
2170
- if (column.rowSpan && column.rowSpan > 1) {
2171
- var endingRow = tableRow + column.rowSpan - 1;
2172
- if (endingRow >= tableBody.length) {
2173
- throw new Error('Row span for column ' + columnIndex + ' (with indexes starting from 0) exceeded row count');
2174
- }
2175
- return tableBody[endingRow][columnIndex];
2176
- }
2177
- return null;
2178
- }
2179
- }
2180
-
2181
- function processLeaf_test(node) {
2182
- var line = buildNextLine_test(node);
2183
- var currentHeight = line ? line.getHeight() : 0;
2184
- var maxHeight = node.maxHeight || -1;
2185
-
2186
- while (line && (maxHeight === -1 || currentHeight < maxHeight)) {
2187
- var positions = testWriter.addLine(line);
2188
- node.positions.push(positions);
2189
- line = buildNextLine_test(node);
2190
- if (line) {
2191
- currentHeight += line.getHeight();
2192
- }
2193
- }
2194
- }
2195
-
2196
- function buildNextLine_test(textNode) {
2197
- function cloneInline(inline) {
2198
- var newInline = inline.constructor();
2199
- for (var key in inline) {
2200
- newInline[key] = inline[key];
2201
- }
2202
- return newInline;
2203
- }
2204
-
2205
- if (!textNode._inlines || textNode._inlines.length === 0) {
2206
- return null;
2207
- }
2208
-
2209
- var line = new Line(testWriter.context().availableWidth);
2210
- var textTools = new TextTools(null);
2211
-
2212
- while (textNode._inlines && textNode._inlines.length > 0 && line.hasEnoughSpaceForInline(textNode._inlines[0])) {
2213
- var inline = textNode._inlines.shift();
2214
-
2215
- if (!inline.noWrap && inline.text.length > 1 && inline.width > line.maxWidth) {
2216
- var widthPerChar = inline.width / inline.text.length;
2217
- var maxChars = Math.floor(line.maxWidth / widthPerChar);
2218
- if (maxChars < 1) {
2219
- maxChars = 1;
2220
- }
2221
- if (maxChars < inline.text.length) {
2222
- var newInline = cloneInline(inline);
2223
-
2224
- newInline.text = inline.text.substr(maxChars);
2225
- inline.text = inline.text.substr(0, maxChars);
2226
-
2227
- newInline.width = textTools.widthOfString(newInline.text, newInline.font, newInline.fontSize, newInline.characterSpacing);
2228
- inline.width = textTools.widthOfString(inline.text, inline.font, inline.fontSize, inline.characterSpacing);
2229
-
2230
- textNode._inlines.unshift(newInline);
2231
- }
2232
- }
2233
-
2234
- line.addInline(inline);
2235
- }
2236
-
2237
- line.lastLineInParagraph = textNode._inlines.length === 0;
2238
-
2239
- return line;
2240
- }
2241
-
2242
- module.exports = LayoutBuilder;
1
+ 'use strict';
2
+
3
+ var cloneDeep = require('lodash/cloneDeep');
4
+ var TraversalTracker = require('./traversalTracker');
5
+ var DocPreprocessor = require('./docPreprocessor');
6
+ var DocMeasure = require('./docMeasure');
7
+ var DocumentContext = require('./documentContext');
8
+ var PageElementWriter = require('./pageElementWriter');
9
+ var ColumnCalculator = require('./columnCalculator');
10
+ var TableProcessor = require('./tableProcessor');
11
+ var Line = require('./line');
12
+ var isString = require('./helpers').isString;
13
+ var isArray = require('./helpers').isArray;
14
+ var isUndefined = require('./helpers').isUndefined;
15
+ var isNull = require('./helpers').isNull;
16
+ var pack = require('./helpers').pack;
17
+ var offsetVector = require('./helpers').offsetVector;
18
+ var fontStringify = require('./helpers').fontStringify;
19
+ var getNodeId = require('./helpers').getNodeId;
20
+ var isFunction = require('./helpers').isFunction;
21
+ var TextTools = require('./textTools');
22
+ var StyleContextStack = require('./styleContextStack');
23
+ var isNumber = require('./helpers').isNumber;
24
+
25
+ var footerBreak = false;
26
+ var testTracker;
27
+ var testWriter;
28
+ var testVerticalAlignStack = [];
29
+ var testResult = false;
30
+ var currentLayoutBuilder;
31
+
32
+ function addAll(target, otherArray) {
33
+ if (!isArray(target) || !isArray(otherArray) || otherArray.length === 0) {
34
+ return;
35
+ }
36
+
37
+ otherArray.forEach(function (item) {
38
+ target.push(item);
39
+ });
40
+ }
41
+
42
+ /**
43
+ * Creates an instance of LayoutBuilder - layout engine which turns document-definition-object
44
+ * into a set of pages, lines, inlines and vectors ready to be rendered into a PDF
45
+ *
46
+ * @param {Object} pageSize - an object defining page width and height
47
+ * @param {Object} pageMargins - an object defining top, left, right and bottom margins
48
+ */
49
+ function LayoutBuilder(pageSize, pageMargins, imageMeasure, svgMeasure) {
50
+ this.pageSize = pageSize;
51
+ this.pageMargins = pageMargins;
52
+ this.tracker = new TraversalTracker();
53
+ this.imageMeasure = imageMeasure;
54
+ this.svgMeasure = svgMeasure;
55
+ this.tableLayouts = {};
56
+ this.nestedLevel = 0;
57
+ this.verticalAlignItemStack = [];
58
+ this.heightHeaderAndFooter = {};
59
+
60
+ this._footerColumnGuides = null;
61
+ this._footerGapOption = null;
62
+ }
63
+
64
+ LayoutBuilder.prototype.registerTableLayouts = function (tableLayouts) {
65
+ this.tableLayouts = pack(this.tableLayouts, tableLayouts);
66
+ };
67
+
68
+ /**
69
+ * Executes layout engine on document-definition-object and creates an array of pages
70
+ * containing positioned Blocks, Lines and inlines
71
+ *
72
+ * @param {Object} docStructure document-definition-object
73
+ * @param {Object} fontProvider font provider
74
+ * @param {Object} styleDictionary dictionary with style definitions
75
+ * @param {Object} defaultStyle default style definition
76
+ * @return {Array} an array of pages
77
+ */
78
+ LayoutBuilder.prototype.layoutDocument = function (docStructure, fontProvider, styleDictionary, defaultStyle, background, header, footer, images, watermark, pageBreakBeforeFct) {
79
+
80
+ function addPageBreaksIfNecessary(linearNodeList, pages) {
81
+
82
+ if (!isFunction(pageBreakBeforeFct)) {
83
+ return false;
84
+ }
85
+
86
+ linearNodeList = linearNodeList.filter(function (node) {
87
+ return node.positions.length > 0;
88
+ });
89
+
90
+ linearNodeList.forEach(function (node) {
91
+ var nodeInfo = {};
92
+ [
93
+ 'id', 'text', 'ul', 'ol', 'table', 'image', 'qr', 'canvas', 'svg', 'columns', 'layers',
94
+ 'headlineLevel', 'style', 'pageBreak', 'pageOrientation',
95
+ 'width', 'height'
96
+ ].forEach(function (key) {
97
+ if (node[key] !== undefined) {
98
+ nodeInfo[key] = node[key];
99
+ }
100
+ });
101
+ nodeInfo.startPosition = node.positions[0];
102
+ nodeInfo.pageNumbers = Array.from(new Set(node.positions.map(function (node) { return node.pageNumber; })));
103
+ nodeInfo.pages = pages.length;
104
+ nodeInfo.stack = isArray(node.stack);
105
+ nodeInfo.layers = isArray(node.layers);
106
+
107
+ node.nodeInfo = nodeInfo;
108
+ });
109
+
110
+ for (var index = 0; index < linearNodeList.length; index++) {
111
+ var node = linearNodeList[index];
112
+ if (node.pageBreak !== 'before' && !node.pageBreakCalculated) {
113
+ node.pageBreakCalculated = true;
114
+ var pageNumber = node.nodeInfo.pageNumbers[0];
115
+ var followingNodesOnPage = [];
116
+ var nodesOnNextPage = [];
117
+ var previousNodesOnPage = [];
118
+ if (pageBreakBeforeFct.length > 1) {
119
+ for (var ii = index + 1, l = linearNodeList.length; ii < l; ii++) {
120
+ if (linearNodeList[ii].nodeInfo.pageNumbers.indexOf(pageNumber) > -1) {
121
+ followingNodesOnPage.push(linearNodeList[ii].nodeInfo);
122
+ }
123
+ if (pageBreakBeforeFct.length > 2 && linearNodeList[ii].nodeInfo.pageNumbers.indexOf(pageNumber + 1) > -1) {
124
+ nodesOnNextPage.push(linearNodeList[ii].nodeInfo);
125
+ }
126
+ }
127
+ }
128
+ if (pageBreakBeforeFct.length > 3) {
129
+ for (var jj = 0; jj < index; jj++) {
130
+ if (linearNodeList[jj].nodeInfo.pageNumbers.indexOf(pageNumber) > -1) {
131
+ previousNodesOnPage.push(linearNodeList[jj].nodeInfo);
132
+ }
133
+ }
134
+ }
135
+ if (pageBreakBeforeFct(node.nodeInfo, followingNodesOnPage, nodesOnNextPage, previousNodesOnPage)) {
136
+ node.pageBreak = 'before';
137
+ return true;
138
+ }
139
+ }
140
+ }
141
+
142
+ return false;
143
+ }
144
+
145
+ this.docPreprocessor = new DocPreprocessor();
146
+ this.docMeasure = new DocMeasure(fontProvider, styleDictionary, defaultStyle, this.imageMeasure, this.svgMeasure, this.tableLayouts, images);
147
+
148
+
149
+ function resetXYs(result) {
150
+ result.linearNodeList.forEach(function (node) {
151
+ node.resetXY();
152
+ });
153
+ }
154
+
155
+ var result = this.tryLayoutDocument(docStructure, fontProvider, styleDictionary, defaultStyle, background, header, footer, images, watermark);
156
+ while (addPageBreaksIfNecessary(result.linearNodeList, result.pages)) {
157
+ resetXYs(result);
158
+ result = this.tryLayoutDocument(docStructure, fontProvider, styleDictionary, defaultStyle, background, header, footer, images, watermark);
159
+ }
160
+
161
+ return result.pages;
162
+ };
163
+
164
+ LayoutBuilder.prototype.tryLayoutDocument = function (docStructure, fontProvider, styleDictionary, defaultStyle, background, header, footer, images, watermark) {
165
+ footerBreak = false;
166
+
167
+ this.verticalAlignItemStack = this.verticalAlignItemStack || [];
168
+ this.linearNodeList = [];
169
+ this.writer = new PageElementWriter(
170
+ new DocumentContext(this.pageSize, this.pageMargins, this._footerGapOption), this.tracker);
171
+
172
+ this.heightHeaderAndFooter = this.addHeadersAndFooters(header, footer) || {};
173
+ if (!isUndefined(this.heightHeaderAndFooter.header)) {
174
+ this.pageMargins.top = this.heightHeaderAndFooter.header + 1;
175
+ }
176
+
177
+ if (isArray(docStructure) && docStructure[2] && isArray(docStructure[2]) && docStructure[2][0] && docStructure[2][0].remark) {
178
+ var tableRemark = docStructure[2][0].remark;
179
+ var remarkLabel = docStructure[2][0];
180
+ var remarkDetail = docStructure[2][1] && docStructure[2][1].text;
181
+
182
+ docStructure[2].splice(0, 1);
183
+ if (docStructure[2].length > 0) {
184
+ docStructure[2].splice(0, 1);
185
+ }
186
+
187
+ var labelRow = [];
188
+ var detailRow = [];
189
+
190
+ labelRow.push(remarkLabel);
191
+ detailRow.push({ remarktest: true, text: remarkDetail });
192
+
193
+ tableRemark.table.body.push(labelRow);
194
+ tableRemark.table.body.push(detailRow);
195
+
196
+ tableRemark.table.headerRows = 1;
197
+
198
+ docStructure[2].push(tableRemark);
199
+ }
200
+
201
+ this.linearNodeList = [];
202
+ docStructure = this.docPreprocessor.preprocessDocument(docStructure);
203
+ docStructure = this.docMeasure.measureDocument(docStructure);
204
+
205
+ this.verticalAlignItemStack = [];
206
+ this.writer = new PageElementWriter(
207
+ new DocumentContext(this.pageSize, this.pageMargins, this._footerGapOption), this.tracker);
208
+
209
+ var _this = this;
210
+ this.writer.context().tracker.startTracking('pageAdded', function () {
211
+ _this.addBackground(background);
212
+ });
213
+
214
+ this.addBackground(background);
215
+ this.processNode(docStructure);
216
+ this.addHeadersAndFooters(header, footer,
217
+ (this.heightHeaderAndFooter.header || 0) + 1,
218
+ (this.heightHeaderAndFooter.footer || 0) + 1);
219
+ if (watermark != null) {
220
+ this.addWatermark(watermark, fontProvider, defaultStyle);
221
+ }
222
+
223
+ return { pages: this.writer.context().pages, linearNodeList: this.linearNodeList };
224
+ };
225
+
226
+ LayoutBuilder.prototype.applyFooterGapOption = function(opt) {
227
+ if (opt === true) {
228
+ opt = { enabled: true };
229
+ }
230
+
231
+ if (!opt) return;
232
+
233
+ if (typeof opt !== 'object') {
234
+ this._footerGapOption = { enabled: true, forcePageBreakForAllRows: false };
235
+ return;
236
+ }
237
+
238
+ this._footerGapOption = {
239
+ enabled: opt.enabled !== false,
240
+ minRowHeight: typeof opt.minRowHeight === 'number' ? opt.minRowHeight : undefined, // Optional fallback - system auto-calculates from cell content if not provided
241
+ forcePageBreakForAllRows: opt.forcePageBreakForAllRows === true, // Force page break for all rows (not just inline images)
242
+ columns: opt.columns ? {
243
+ widths: Array.isArray(opt.columns.widths) ? opt.columns.widths.slice() : undefined,
244
+ widthLength: opt.columns.widths.length || 0,
245
+ stops: Array.isArray(opt.columns.stops) ? opt.columns.stops.slice() : undefined,
246
+ style: opt.columns.style ? Object.assign({}, opt.columns.style) : {},
247
+ includeOuter: opt.columns.includeOuter !== false
248
+ } : null
249
+ };
250
+ };
251
+
252
+ LayoutBuilder.prototype.addBackground = function (background) {
253
+ var backgroundGetter = isFunction(background) ? background : function () {
254
+ return background;
255
+ };
256
+
257
+ var context = this.writer.context();
258
+ var pageSize = context.getCurrentPage().pageSize;
259
+
260
+ var pageBackground = backgroundGetter(context.page + 1, pageSize);
261
+
262
+ if (pageBackground) {
263
+ this.writer.beginUnbreakableBlock(pageSize.width, pageSize.height);
264
+ pageBackground = this.docPreprocessor.preprocessDocument(pageBackground);
265
+ this.processNode(this.docMeasure.measureDocument(pageBackground));
266
+ this.writer.commitUnbreakableBlock(0, 0);
267
+ context.backgroundLength[context.page] += pageBackground.positions.length;
268
+ }
269
+ };
270
+
271
+ LayoutBuilder.prototype.addStaticRepeatable = function (headerOrFooter, sizeFunction) {
272
+ return this.addDynamicRepeatable(function () {
273
+ return JSON.parse(JSON.stringify(headerOrFooter)); // copy to new object
274
+ }, sizeFunction);
275
+ };
276
+
277
+ LayoutBuilder.prototype.addDynamicRepeatable = function (nodeGetter, sizeFunction) {
278
+ var pages = this.writer.context().pages;
279
+ var measuredHeight;
280
+
281
+ for (var pageIndex = 0, l = pages.length; pageIndex < l; pageIndex++) {
282
+ this.writer.context().page = pageIndex;
283
+
284
+ var node = nodeGetter(pageIndex + 1, l, this.writer.context().pages[pageIndex].pageSize);
285
+
286
+ if (node) {
287
+ var sizes = sizeFunction(this.writer.context().getCurrentPage().pageSize, this.pageMargins);
288
+ this.writer.beginUnbreakableBlock(sizes.width, sizes.height);
289
+ node = this.docPreprocessor.preprocessDocument(node);
290
+ this.processNode(this.docMeasure.measureDocument(node));
291
+ this.writer.commitUnbreakableBlock(sizes.x, sizes.y);
292
+ if (!isUndefined(node._height)) {
293
+ measuredHeight = node._height;
294
+ }
295
+ }
296
+ }
297
+
298
+ return measuredHeight;
299
+ };
300
+
301
+ LayoutBuilder.prototype.addHeadersAndFooters = function (header, footer, headerHeight, footerHeight) {
302
+ var measured = { header: undefined, footer: undefined };
303
+
304
+ var headerSizeFct = function (pageSize) {
305
+ var effectiveHeight = headerHeight;
306
+ if (isUndefined(effectiveHeight)) {
307
+ effectiveHeight = pageSize.height;
308
+ }
309
+ return {
310
+ x: 0,
311
+ y: 0,
312
+ width: pageSize.width,
313
+ height: effectiveHeight
314
+ };
315
+ };
316
+
317
+ var footerSizeFct = function (pageSize) {
318
+ var effectiveHeight = footerHeight;
319
+ if (isUndefined(effectiveHeight)) {
320
+ effectiveHeight = pageSize.height;
321
+ }
322
+ return {
323
+ x: 0,
324
+ y: pageSize.height - effectiveHeight,
325
+ width: pageSize.width,
326
+ height: effectiveHeight
327
+ };
328
+ };
329
+
330
+ if (this._footerGapOption && !this.writer.context()._footerGapOption) {
331
+ this.writer.context()._footerGapOption = this._footerGapOption;
332
+ }
333
+
334
+ if (isFunction(header)) {
335
+ measured.header = this.addDynamicRepeatable(header, headerSizeFct);
336
+ } else if (header) {
337
+ measured.header = this.addStaticRepeatable(header, headerSizeFct);
338
+ }
339
+
340
+ if (isFunction(footer)) {
341
+ measured.footer = this.addDynamicRepeatable(footer, footerSizeFct);
342
+ } else if (footer) {
343
+ measured.footer = this.addStaticRepeatable(footer, footerSizeFct);
344
+ }
345
+
346
+ return measured;
347
+ };
348
+
349
+ LayoutBuilder.prototype.addWatermark = function (watermark, fontProvider, defaultStyle) {
350
+ if (isString(watermark)) {
351
+ watermark = { 'text': watermark };
352
+ }
353
+
354
+ if (!watermark.text) { // empty watermark text
355
+ return;
356
+ }
357
+
358
+ var pages = this.writer.context().pages;
359
+ for (var i = 0, l = pages.length; i < l; i++) {
360
+ pages[i].watermark = getWatermarkObject({ ...watermark }, pages[i].pageSize, fontProvider, defaultStyle);
361
+ }
362
+
363
+ function getWatermarkObject(watermark, pageSize, fontProvider, defaultStyle) {
364
+ watermark.font = watermark.font || defaultStyle.font || 'Roboto';
365
+ watermark.fontSize = watermark.fontSize || 'auto';
366
+ watermark.color = watermark.color || 'black';
367
+ watermark.opacity = isNumber(watermark.opacity) ? watermark.opacity : 0.6;
368
+ watermark.bold = watermark.bold || false;
369
+ watermark.italics = watermark.italics || false;
370
+ watermark.angle = !isUndefined(watermark.angle) && !isNull(watermark.angle) ? watermark.angle : null;
371
+
372
+ if (watermark.angle === null) {
373
+ watermark.angle = Math.atan2(pageSize.height, pageSize.width) * -180 / Math.PI;
374
+ }
375
+
376
+ if (watermark.fontSize === 'auto') {
377
+ watermark.fontSize = getWatermarkFontSize(pageSize, watermark, fontProvider);
378
+ }
379
+
380
+ var watermarkObject = {
381
+ text: watermark.text,
382
+ font: fontProvider.provideFont(watermark.font, watermark.bold, watermark.italics),
383
+ fontSize: watermark.fontSize,
384
+ color: watermark.color,
385
+ opacity: watermark.opacity,
386
+ angle: watermark.angle
387
+ };
388
+
389
+ watermarkObject._size = getWatermarkSize(watermark, fontProvider);
390
+
391
+ return watermarkObject;
392
+ }
393
+
394
+ function getWatermarkSize(watermark, fontProvider) {
395
+ var textTools = new TextTools(fontProvider);
396
+ var styleContextStack = new StyleContextStack(null, { font: watermark.font, bold: watermark.bold, italics: watermark.italics });
397
+
398
+ styleContextStack.push({
399
+ fontSize: watermark.fontSize
400
+ });
401
+
402
+ var size = textTools.sizeOfString(watermark.text, styleContextStack);
403
+ var rotatedSize = textTools.sizeOfRotatedText(watermark.text, watermark.angle, styleContextStack);
404
+
405
+ return { size: size, rotatedSize: rotatedSize };
406
+ }
407
+
408
+ function getWatermarkFontSize(pageSize, watermark, fontProvider) {
409
+ var textTools = new TextTools(fontProvider);
410
+ var styleContextStack = new StyleContextStack(null, { font: watermark.font, bold: watermark.bold, italics: watermark.italics });
411
+ var rotatedSize;
412
+
413
+ /**
414
+ * Binary search the best font size.
415
+ * Initial bounds [0, 1000]
416
+ * Break when range < 1
417
+ */
418
+ var a = 0;
419
+ var b = 1000;
420
+ var c = (a + b) / 2;
421
+ while (Math.abs(a - b) > 1) {
422
+ styleContextStack.push({
423
+ fontSize: c
424
+ });
425
+ rotatedSize = textTools.sizeOfRotatedText(watermark.text, watermark.angle, styleContextStack);
426
+ if (rotatedSize.width > pageSize.width) {
427
+ b = c;
428
+ c = (a + b) / 2;
429
+ } else if (rotatedSize.width < pageSize.width) {
430
+ if (rotatedSize.height > pageSize.height) {
431
+ b = c;
432
+ c = (a + b) / 2;
433
+ } else {
434
+ a = c;
435
+ c = (a + b) / 2;
436
+ }
437
+ }
438
+ styleContextStack.pop();
439
+ }
440
+ /*
441
+ End binary search
442
+ */
443
+ return c;
444
+ }
445
+ };
446
+
447
+ function decorateNode(node) {
448
+ var x = node.x, y = node.y;
449
+ node.positions = [];
450
+
451
+ if (isArray(node.canvas)) {
452
+ node.canvas.forEach(function (vector) {
453
+ var x = vector.x, y = vector.y, x1 = vector.x1, y1 = vector.y1, x2 = vector.x2, y2 = vector.y2;
454
+ vector.resetXY = function () {
455
+ vector.x = x;
456
+ vector.y = y;
457
+ vector.x1 = x1;
458
+ vector.y1 = y1;
459
+ vector.x2 = x2;
460
+ vector.y2 = y2;
461
+ };
462
+ });
463
+ }
464
+
465
+ node.resetXY = function () {
466
+ node.x = x;
467
+ node.y = y;
468
+ if (isArray(node.canvas)) {
469
+ node.canvas.forEach(function (vector) {
470
+ vector.resetXY();
471
+ });
472
+ }
473
+ };
474
+ }
475
+
476
+ LayoutBuilder.prototype.processNode = function (node) {
477
+ var self = this;
478
+
479
+ if (footerBreak && (node.footerBreak || node.footer)) {
480
+ return;
481
+ }
482
+
483
+ if (node && node.unbreakable && node.summary && node.table && node.table.body &&
484
+ node.table.body[0] && node.table.body[0][0] && node.table.body[0][0].summaryBreak) {
485
+ testTracker = new TraversalTracker();
486
+ testWriter = new PageElementWriter(self.writer.context(), testTracker);
487
+ testVerticalAlignStack = self.verticalAlignItemStack.slice();
488
+ currentLayoutBuilder = self;
489
+ testResult = false;
490
+ var nodeForTest = cloneDeep(node);
491
+ if (nodeForTest.table.body[0]) {
492
+ nodeForTest.table.body[0].splice(0, 1);
493
+ }
494
+ processNode_test(nodeForTest);
495
+ currentLayoutBuilder = null;
496
+ if (testResult && node.table.body[0]) {
497
+ node.table.body[0].splice(0, 1);
498
+ }
499
+ }
500
+
501
+ this.linearNodeList.push(node);
502
+ decorateNode(node);
503
+
504
+ var prevTop = self.writer.context().getCurrentPosition().top;
505
+
506
+ applyMargins(function () {
507
+ var unbreakable = node.unbreakable;
508
+ if (unbreakable) {
509
+ self.writer.beginUnbreakableBlock();
510
+ }
511
+
512
+ var absPosition = node.absolutePosition;
513
+ if (absPosition) {
514
+ self.writer.context().beginDetachedBlock();
515
+ self.writer.context().moveTo(absPosition.x || 0, absPosition.y || 0);
516
+ }
517
+
518
+ var relPosition = node.relativePosition;
519
+ if (relPosition) {
520
+ self.writer.context().beginDetachedBlock();
521
+ self.writer.context().moveToRelative(relPosition.x || 0, relPosition.y || 0);
522
+ }
523
+
524
+ var verticalAlignBegin;
525
+ if (node.verticalAlign) {
526
+ verticalAlignBegin = self.writer.beginVerticalAlign(node.verticalAlign);
527
+ }
528
+
529
+ if (node.stack) {
530
+ // Handle _footerGapOption for breakable stacks
531
+ var footerGapEnabled = !unbreakable && node.footer && node._footerGapOption && node._footerGapOption.enabled;
532
+ var preRenderState = null;
533
+
534
+ if (footerGapEnabled) {
535
+ var ctx = self.writer.context();
536
+ var currentPage = ctx.getCurrentPage();
537
+ preRenderState = {
538
+ startY: ctx.y,
539
+ startPage: ctx.page,
540
+ availableHeight: ctx.availableHeight,
541
+ itemCount: currentPage ? currentPage.items.length : 0,
542
+ x: ctx.x,
543
+ summaryRenderedPage: null
544
+ };
545
+ }
546
+
547
+ // Process the stack
548
+ self.processVerticalContainer(node);
549
+
550
+ // Track which page summary was rendered on (summary is first item, unbreakable)
551
+ if (preRenderState && node.stack && node.stack[0]) {
552
+ var summaryNode = node.stack[0];
553
+ if (summaryNode.summary || summaryNode.unbreakable) {
554
+ // Summary is unbreakable, check if it was pushed to a new page
555
+ // by comparing its height with available space at startPage
556
+ var summaryHeight = Math.abs(summaryNode._height || 0);
557
+ if (summaryHeight <= preRenderState.availableHeight) {
558
+ // Summary fit on startPage
559
+ preRenderState.summaryRenderedPage = preRenderState.startPage;
560
+ } else {
561
+ // Summary was pushed to next page
562
+ preRenderState.summaryRenderedPage = preRenderState.startPage + 1;
563
+ }
564
+ }
565
+ }
566
+
567
+ // Post-render repositioning
568
+ if (footerGapEnabled && preRenderState) {
569
+ var ctx = self.writer.context();
570
+
571
+ // Only reposition if on same page (single-page content)
572
+ if (ctx.page === preRenderState.startPage) {
573
+ var renderedHeight = ctx.y - preRenderState.startY;
574
+ var gapHeight = preRenderState.availableHeight - renderedHeight;
575
+
576
+ if (gapHeight > 0) {
577
+ var currentPage = ctx.getCurrentPage();
578
+
579
+ // SINGLE-PAGE: Draw guide lines in the gap area
580
+ var gapTopY = preRenderState.startY;
581
+ var colSpec = node._footerGapOption.columns || self._footerGapOption.columns || null;
582
+ if (colSpec) {
583
+ var rawWidths = colSpec.content.vLines || [];
584
+ if (rawWidths && rawWidths.length > 1) {
585
+ var style = (colSpec.style || {});
586
+ var lw = style.lineWidth != null ? style.lineWidth : 0.5;
587
+ var lc = style.color || '#000000';
588
+ var dashCfg = style.dash;
589
+ var includeOuter = colSpec.includeOuter !== false;
590
+ var startIndex = includeOuter ? 0 : 1;
591
+ var endIndex = includeOuter ? rawWidths.length : rawWidths.length - 1;
592
+
593
+ for (var ci = startIndex; ci < endIndex; ci++) {
594
+ var xGuide = ctx.x + rawWidths[ci] - 0.25;
595
+ currentPage.items.push({
596
+ type: 'vector',
597
+ item: {
598
+ type: 'line',
599
+ x1: xGuide,
600
+ y1: gapTopY,
601
+ x2: xGuide,
602
+ y2: gapTopY + gapHeight,
603
+ lineWidth: lw,
604
+ lineColor: lc,
605
+ dash: dashCfg ? {
606
+ length: dashCfg.length,
607
+ space: dashCfg.space != null ? dashCfg.space : dashCfg.gap
608
+ } : undefined,
609
+ _footerGuideLine: true
610
+ }
611
+ });
612
+ }
613
+ }
614
+ }
615
+
616
+ // Reposition only items that belong to footer stack content
617
+ // Iterate ALL items (backgrounds are inserted at lower indices, not appended)
618
+ // Filter by Y position to exclude non-footer items
619
+ for (var i = 0; i < currentPage.items.length; i++) {
620
+ var item = currentPage.items[i];
621
+
622
+ // Skip the guide lines we just added (they're already positioned correctly)
623
+ if (item.item && item.item._footerGuideLine) {
624
+ continue;
625
+ }
626
+
627
+ // Get the item's starting Y position
628
+ var itemStartY = null;
629
+ if (item.item && typeof item.item.y1 === 'number') {
630
+ itemStartY = item.item.y1;
631
+ } else if (item.item && typeof item.item.y === 'number') {
632
+ itemStartY = item.item.y;
633
+ }
634
+
635
+ // Only reposition items that START at or after footer stack's Y position
636
+ // This excludes outer table border lines that extend from earlier rows
637
+ if (itemStartY !== null && itemStartY < preRenderState.startY) {
638
+ continue;
639
+ }
640
+
641
+ // Reposition this item
642
+ if (item.item && typeof item.item.y === 'number') {
643
+ item.item.y += gapHeight;
644
+ }
645
+ if (item.item && typeof item.item.y1 === 'number') {
646
+ item.item.y1 += gapHeight;
647
+ }
648
+ if (item.item && typeof item.item.y2 === 'number') {
649
+ item.item.y2 += gapHeight;
650
+ }
651
+ // Handle polylines (points array)
652
+ if (item.item && item.item.points && Array.isArray(item.item.points)) {
653
+ for (var pi = 0; pi < item.item.points.length; pi++) {
654
+ if (typeof item.item.points[pi].y === 'number') {
655
+ item.item.points[pi].y += gapHeight;
656
+ }
657
+ }
658
+ }
659
+ }
660
+ ctx.moveDown(gapHeight);
661
+ }
662
+ } else {
663
+ // MULTI-PAGE: Process ALL pages from startPage+1 to current page
664
+ // Only move FOOTER items to bottom, keep remark at top
665
+ var pages = ctx.pages;
666
+ var pageMargins = ctx.pageMargins;
667
+
668
+ // Helper function to recursively find node with _isFooterTable
669
+ function findFooterTableNode(n) {
670
+ if (!n) return null;
671
+ if (n._isFooterTable) return n;
672
+ if (n.stack && Array.isArray(n.stack)) {
673
+ for (var i = 0; i < n.stack.length; i++) {
674
+ var found = findFooterTableNode(n.stack[i]);
675
+ if (found) return found;
676
+ }
677
+ }
678
+ if (Array.isArray(n)) {
679
+ for (var i = 0; i < n.length; i++) {
680
+ var found = findFooterTableNode(n[i]);
681
+ if (found) return found;
682
+ }
683
+ }
684
+ return null;
685
+ }
686
+
687
+ // Find footer table node to get its height
688
+ var footerStackItem = null;
689
+ if (node.stack && node.stack.length > 0) {
690
+ for (var si = node.stack.length - 1; si >= 0; si--) {
691
+ var found = findFooterTableNode(node.stack[si]);
692
+ if (found) {
693
+ footerStackItem = node.stack[si];
694
+ break;
695
+ }
696
+ }
697
+ }
698
+
699
+ var stackHeight = Math.abs((footerStackItem && footerStackItem._height) || 0);
700
+
701
+ // Only process the LAST page where footer is located
702
+ // Intermediate pages (remark only) should not be repositioned
703
+ var pageIdx = ctx.page;
704
+ if (pageIdx > preRenderState.startPage) {
705
+ // Also reposition items on the START page (where summary might be)
706
+ var startPage = pages[preRenderState.startPage];
707
+ if (startPage && startPage.items && startPage.items.length > 0) {
708
+ var startPageHeight = startPage.pageSize.height;
709
+ var startPageBottom = startPageHeight - pageMargins.bottom;
710
+
711
+ // Find content bottom on start page
712
+ var startContentBottom = 0;
713
+ for (var si = 0; si < startPage.items.length; si++) {
714
+ var sItem = startPage.items[si];
715
+ var sItemBottom = 0;
716
+ if (sItem.item) {
717
+ if (typeof sItem.item.y === 'number') {
718
+ var sh = 0;
719
+ // Line items have getHeight() method
720
+ if (sItem.type === 'line' && typeof sItem.item.getHeight === 'function') {
721
+ sh = sItem.item.getHeight();
722
+ } else {
723
+ sh = sItem.item.h || sItem.item.height || 0;
724
+ }
725
+ sItemBottom = sItem.item.y + sh;
726
+ }
727
+ if (typeof sItem.item.y2 === 'number' && sItem.item.y2 > sItemBottom) {
728
+ sItemBottom = sItem.item.y2;
729
+ }
730
+ }
731
+ if (sItemBottom > startContentBottom) {
732
+ startContentBottom = sItemBottom;
733
+ }
734
+ }
735
+
736
+ // Calculate gap and move items on start page
737
+ var startGapHeight = startPageBottom - startContentBottom;
738
+ if (startGapHeight > 0) {
739
+ var startStackStartY = preRenderState.startY;
740
+ for (var si = 0; si < startPage.items.length; si++) {
741
+ var sItem = startPage.items[si];
742
+ var sItemY = null;
743
+ if (sItem.item && typeof sItem.item.y1 === 'number') {
744
+ sItemY = sItem.item.y1;
745
+ } else if (sItem.item && typeof sItem.item.y === 'number') {
746
+ sItemY = sItem.item.y;
747
+ } else if (sItem.item && sItem.item.points && Array.isArray(sItem.item.points) && sItem.item.points.length > 0) {
748
+ // For polylines, use the first point's Y
749
+ sItemY = sItem.item.points[0].y;
750
+ }
751
+
752
+ // Skip items fully above footer start
753
+ if (sItemY === null || sItemY < startStackStartY) continue;
754
+
755
+ // Move item down
756
+ if (sItem.item && typeof sItem.item.y === 'number') {
757
+ sItem.item.y += startGapHeight;
758
+ }
759
+ if (sItem.item && typeof sItem.item.y1 === 'number') {
760
+ sItem.item.y1 += startGapHeight;
761
+ }
762
+ if (sItem.item && typeof sItem.item.y2 === 'number') {
763
+ sItem.item.y2 += startGapHeight;
764
+ }
765
+ // Handle polylines (points array)
766
+ if (sItem.item && sItem.item.points && Array.isArray(sItem.item.points)) {
767
+ for (var spi = 0; spi < sItem.item.points.length; spi++) {
768
+ if (typeof sItem.item.points[spi].y === 'number') {
769
+ sItem.item.points[spi].y += startGapHeight;
770
+ }
771
+ }
772
+ }
773
+ }
774
+
775
+ // MULTI-PAGE: Draw guide lines in the gap area (same as single-page)
776
+ var colSpec = node._footerGapOption && node._footerGapOption.columns ? node._footerGapOption.columns : (self._footerGapOption && self._footerGapOption.columns);
777
+ if (colSpec) {
778
+ var rawWidths = colSpec.content && colSpec.content.vLines ? colSpec.content.vLines : [];
779
+ if (rawWidths && rawWidths.length > 1) {
780
+ var style = (colSpec.style || {});
781
+ var lw = style.lineWidth != null ? style.lineWidth : 0.5;
782
+ var lc = style.color || '#000000';
783
+ var dashCfg = style.dash;
784
+ var includeOuter = colSpec.includeOuter !== false;
785
+ var startIndex = includeOuter ? 0 : 1;
786
+ var endIndex = includeOuter ? rawWidths.length : rawWidths.length - 1;
787
+ var pageX = preRenderState.x || pageMargins.left;
788
+
789
+ for (var ci = startIndex; ci < endIndex; ci++) {
790
+ var xGuide = pageX + rawWidths[ci] - 0.25;
791
+ // Extend first and last vertical lines to content bottom after moving
792
+ var isFirstOrLast = (ci === 0) || (ci === rawWidths.length - 1);
793
+ var vLineY2 = isFirstOrLast ? (startContentBottom + startGapHeight) : (startStackStartY + startGapHeight);
794
+ startPage.items.push({
795
+ type: 'vector',
796
+ item: {
797
+ type: 'line',
798
+ x1: xGuide,
799
+ y1: startStackStartY,
800
+ x2: xGuide,
801
+ y2: vLineY2,
802
+ lineWidth: lw,
803
+ lineColor: lc,
804
+ dash: dashCfg ? {
805
+ length: dashCfg.length,
806
+ space: dashCfg.space != null ? dashCfg.space : dashCfg.gap
807
+ } : undefined,
808
+ _footerGuideLine: true
809
+ }
810
+ });
811
+ }
812
+
813
+ // Remove existing horizontal line at startStackStartY (drawn by tableProcessor)
814
+ // It's at wrong position now - we'll draw new one at bottom of gap
815
+ for (var ri = startPage.items.length - 1; ri >= 0; ri--) {
816
+ var rItem = startPage.items[ri];
817
+ if (rItem.type === 'vector' && rItem.item && rItem.item.type === 'line') {
818
+ // Check if it's a horizontal line at startStackStartY
819
+ if (Math.abs(rItem.item.y1 - startStackStartY) < 1 &&
820
+ Math.abs(rItem.item.y2 - startStackStartY) < 1) {
821
+ startPage.items.splice(ri, 1);
822
+ break;
823
+ }
824
+ }
825
+ }
826
+ }
827
+ }
828
+ }
829
+ }
830
+
831
+ var page = pages[pageIdx];
832
+ if (page && page.items && page.items.length > 0) {
833
+ var pageHeight = page.pageSize.height;
834
+ var bottomMargin = pageMargins.bottom;
835
+ var pageBottom = pageHeight - bottomMargin;
836
+
837
+ // Find footer start Y on this page (where footer items begin)
838
+ // Use footerHeight to identify footer area from the bottom of content
839
+ var contentBottom = 0;
840
+ for (var i = 0; i < page.items.length; i++) {
841
+ var item = page.items[i];
842
+ var itemBottom = 0;
843
+ if (item.item) {
844
+ if (typeof item.item.y === 'number') {
845
+ var h = item.item.h || item.item.height || 0;
846
+ itemBottom = item.item.y + h;
847
+ }
848
+ if (typeof item.item.y2 === 'number' && item.item.y2 > itemBottom) {
849
+ itemBottom = item.item.y2;
850
+ }
851
+ // Handle polylines (points array)
852
+ if (item.item.points && Array.isArray(item.item.points)) {
853
+ for (var pi = 0; pi < item.item.points.length; pi++) {
854
+ if (typeof item.item.points[pi].y === 'number' && item.item.points[pi].y > itemBottom) {
855
+ itemBottom = item.item.points[pi].y;
856
+ }
857
+ }
858
+ }
859
+ }
860
+ if (itemBottom > contentBottom) {
861
+ contentBottom = itemBottom;
862
+ }
863
+ }
864
+
865
+ // Check if summary is on the last page
866
+ var summaryOnLastPage = (preRenderState.summaryRenderedPage === pageIdx);
867
+
868
+ var stackStartY;
869
+ if (summaryOnLastPage) {
870
+ // Summary is on this page - move all: summary + remark + footer together
871
+ // Calculate header threshold for this page
872
+ var repeatableHeaderHeight = 0;
873
+ for (var ri = 0; ri < self.writer.repeatables.length; ri++) {
874
+ repeatableHeaderHeight += self.writer.repeatables[ri].height;
875
+ }
876
+ var headerThreshold = pageMargins.top + repeatableHeaderHeight;
877
+
878
+ // Find minimum Y of all items below header threshold
879
+ stackStartY = contentBottom;
880
+ for (var i = 0; i < page.items.length; i++) {
881
+ var item = page.items[i];
882
+ var itemY = null;
883
+ if (item.item && typeof item.item.y1 === 'number') {
884
+ itemY = item.item.y1;
885
+ } else if (item.item && typeof item.item.y === 'number') {
886
+ itemY = item.item.y;
887
+ } else if (item.item && item.item.points && Array.isArray(item.item.points) && item.item.points.length > 0) {
888
+ itemY = item.item.points[0].y;
889
+ }
890
+ if (itemY !== null && itemY >= headerThreshold && itemY < stackStartY) {
891
+ stackStartY = itemY;
892
+ }
893
+ }
894
+
895
+ // Draw guide lines in the gap area (same as single-page)
896
+ var gapHeightForLines = pageBottom - contentBottom;
897
+ if (gapHeightForLines > 0) {
898
+ var colSpec = node._footerGapOption && node._footerGapOption.columns ? node._footerGapOption.columns : (self._footerGapOption && self._footerGapOption.columns);
899
+ if (colSpec) {
900
+ var rawWidths = colSpec.content && colSpec.content.vLines ? colSpec.content.vLines : [];
901
+ if (rawWidths && rawWidths.length > 1) {
902
+ var style = (colSpec.style || {});
903
+ var lw = style.lineWidth != null ? style.lineWidth : 0.5;
904
+ var lc = style.color || '#000000';
905
+ var dashCfg = style.dash;
906
+ var includeOuter = colSpec.includeOuter !== false;
907
+ var startIndex = includeOuter ? 0 : 1;
908
+ var endIndex = includeOuter ? rawWidths.length : rawWidths.length - 1;
909
+ var pageX = preRenderState.x || pageMargins.left;
910
+
911
+ for (var ci = startIndex; ci < endIndex; ci++) {
912
+ var xGuide = pageX + rawWidths[ci] - 0.25;
913
+ page.items.push({
914
+ type: 'vector',
915
+ item: {
916
+ type: 'line',
917
+ x1: xGuide,
918
+ y1: stackStartY,
919
+ x2: xGuide,
920
+ y2: stackStartY + gapHeightForLines,
921
+ lineWidth: lw,
922
+ lineColor: lc,
923
+ dash: dashCfg ? {
924
+ length: dashCfg.length,
925
+ space: dashCfg.space != null ? dashCfg.space : dashCfg.gap
926
+ } : undefined,
927
+ _footerGuideLine: true
928
+ }
929
+ });
930
+ }
931
+ }
932
+ }
933
+ }
934
+ } else {
935
+ // Summary is NOT on this page - move only footer
936
+ stackStartY = contentBottom - stackHeight;
937
+ }
938
+
939
+ // Calculate gap: how much to move footer stack down
940
+ var gapHeight = pageBottom - contentBottom;
941
+ if (gapHeight > 0) {
942
+ // Calculate header threshold if not already calculated
943
+ if (typeof headerThreshold === 'undefined') {
944
+ var repeatableHeaderHeight = 0;
945
+ for (var ri = 0; ri < self.writer.repeatables.length; ri++) {
946
+ repeatableHeaderHeight += self.writer.repeatables[ri].height;
947
+ }
948
+ headerThreshold = pageMargins.top + repeatableHeaderHeight;
949
+ }
950
+
951
+ // Move all items that are part of footer stack (Y >= stackStartY)
952
+ for (var i = 0; i < page.items.length; i++) {
953
+ var item = page.items[i];
954
+
955
+ // Skip guide lines (they're already positioned correctly)
956
+ if (item.item && item.item._footerGuideLine) continue;
957
+
958
+ var itemY = null;
959
+ if (item.item && typeof item.item.y1 === 'number') {
960
+ itemY = item.item.y1;
961
+ } else if (item.item && typeof item.item.y === 'number') {
962
+ itemY = item.item.y;
963
+ } else if (item.item && item.item.points && Array.isArray(item.item.points) && item.item.points.length > 0) {
964
+ itemY = item.item.points[0].y;
965
+ }
966
+
967
+ // Skip items above footer stack
968
+ if (itemY === null || itemY < stackStartY) continue;
969
+
970
+ // Skip items in header area (repeated headers)
971
+ if (itemY < headerThreshold) continue;
972
+
973
+ // Move footer stack item down
974
+ if (item.item && typeof item.item.y === 'number') {
975
+ item.item.y += gapHeight;
976
+ }
977
+ if (item.item && typeof item.item.y1 === 'number') {
978
+ item.item.y1 += gapHeight;
979
+ }
980
+ if (item.item && typeof item.item.y2 === 'number') {
981
+ item.item.y2 += gapHeight;
982
+ }
983
+ // // Handle polylines (points array)
984
+ if (item.item && item.item.points && Array.isArray(item.item.points)) {
985
+ for (var pi = 0; pi < item.item.points.length; pi++) {
986
+ if (typeof item.item.points[pi].y === 'number') {
987
+ item.item.points[pi].y += gapHeight;
988
+ }
989
+ }
990
+ }
991
+ }
992
+ }
993
+ }
994
+ }
995
+
996
+ // Also update context for current page
997
+ var lastPageGapHeight = ctx.availableHeight;
998
+ if (lastPageGapHeight > 0) {
999
+ ctx.moveDown(lastPageGapHeight);
1000
+ }
1001
+ }
1002
+ }
1003
+ } else if (node.layers) {
1004
+ self.processLayers(node);
1005
+ } else if (node.columns) {
1006
+ self.processColumns(node);
1007
+ } else if (node.ul) {
1008
+ self.processList(false, node);
1009
+ } else if (node.ol) {
1010
+ self.processList(true, node);
1011
+ } else if (node.table) {
1012
+ self.processTable(node);
1013
+ } else if (node.text !== undefined) {
1014
+ self.processLeaf(node);
1015
+ } else if (node.toc) {
1016
+ self.processToc(node);
1017
+ } else if (node.image) {
1018
+ self.processImage(node);
1019
+ } else if (node.svg) {
1020
+ self.processSVG(node);
1021
+ } else if (node.canvas) {
1022
+ self.processCanvas(node);
1023
+ } else if (node.qr) {
1024
+ self.processQr(node);
1025
+ } else if (!node._span) {
1026
+ throw new Error('Unrecognized document structure: ' + JSON.stringify(node, fontStringify));
1027
+ }
1028
+
1029
+ if ((absPosition || relPosition) && !node.absoluteRepeatable) {
1030
+ self.writer.context().endDetachedBlock();
1031
+ }
1032
+
1033
+ if (unbreakable) {
1034
+ if (node.footer) {
1035
+ footerBreak = self.writer.commitUnbreakableBlock(undefined, undefined, node.footer);
1036
+ } else {
1037
+ self.writer.commitUnbreakableBlock();
1038
+ }
1039
+ }
1040
+
1041
+ if (node.verticalAlign) {
1042
+ var stackEntry = {
1043
+ begin: verticalAlignBegin,
1044
+ end: self.writer.endVerticalAlign(node.verticalAlign)
1045
+ };
1046
+ self.verticalAlignItemStack.push(stackEntry);
1047
+ node._verticalAlignIdx = self.verticalAlignItemStack.length - 1;
1048
+ }
1049
+ });
1050
+
1051
+ node._height = self.writer.context().getCurrentPosition().top - prevTop;
1052
+
1053
+ function applyMargins(callback) {
1054
+ var margin = node._margin;
1055
+
1056
+ if (node.pageBreak === 'before') {
1057
+ self.writer.moveToNextPage(node.pageOrientation);
1058
+ }
1059
+
1060
+ if (margin) {
1061
+ self.writer.context().moveDown(margin[1]);
1062
+ self.writer.context().addMargin(margin[0], margin[2]);
1063
+ }
1064
+
1065
+ callback();
1066
+
1067
+ if (margin) {
1068
+ self.writer.context().addMargin(-margin[0], -margin[2]);
1069
+ self.writer.context().moveDown(margin[3]);
1070
+ }
1071
+
1072
+ if (node.pageBreak === 'after') {
1073
+ self.writer.moveToNextPage(node.pageOrientation);
1074
+ }
1075
+ }
1076
+ };
1077
+
1078
+ // vertical container
1079
+ LayoutBuilder.prototype.processVerticalContainer = function (node) {
1080
+ var self = this;
1081
+ node.stack.forEach(function (item) {
1082
+ self.processNode(item);
1083
+ addAll(node.positions, item.positions);
1084
+
1085
+ //TODO: paragraph gap
1086
+ });
1087
+ };
1088
+
1089
+ // layers
1090
+ LayoutBuilder.prototype.processLayers = function(node) {
1091
+ var self = this;
1092
+ var ctxX = self.writer.context().x;
1093
+ var ctxY = self.writer.context().y;
1094
+ var maxX = ctxX;
1095
+ var maxY = ctxY;
1096
+ node.layers.forEach(function(item, i) {
1097
+ self.writer.context().x = ctxX;
1098
+ self.writer.context().y = ctxY;
1099
+ self.processNode(item);
1100
+ item._verticalAlignIdx = self.verticalAlignItemStack.length - 1;
1101
+ addAll(node.positions, item.positions);
1102
+ maxX = self.writer.context().x > maxX ? self.writer.context().x : maxX;
1103
+ maxY = self.writer.context().y > maxY ? self.writer.context().y : maxY;
1104
+ });
1105
+ self.writer.context().x = maxX;
1106
+ self.writer.context().y = maxY;
1107
+ };
1108
+
1109
+ // columns
1110
+ LayoutBuilder.prototype.processColumns = function (columnNode) {
1111
+ this.nestedLevel++;
1112
+ var columns = columnNode.columns;
1113
+ var availableWidth = this.writer.context().availableWidth;
1114
+ var gaps = gapArray(columnNode._gap);
1115
+
1116
+ if (gaps) {
1117
+ availableWidth -= (gaps.length - 1) * columnNode._gap;
1118
+ }
1119
+
1120
+ ColumnCalculator.buildColumnWidths(columns, availableWidth);
1121
+ var result = this.processRow({
1122
+ marginX: columnNode._margin ? [columnNode._margin[0], columnNode._margin[2]] : [0, 0],
1123
+ cells: columns,
1124
+ widths: columns,
1125
+ gaps
1126
+ });
1127
+ addAll(columnNode.positions, result.positions);
1128
+
1129
+ this.nestedLevel--;
1130
+ if (this.nestedLevel === 0) {
1131
+ this.writer.context().resetMarginXTopParent();
1132
+ }
1133
+
1134
+ function gapArray(gap) {
1135
+ if (!gap) {
1136
+ return null;
1137
+ }
1138
+
1139
+ var gaps = [];
1140
+ gaps.push(0);
1141
+
1142
+ for (var i = columns.length - 1; i > 0; i--) {
1143
+ gaps.push(gap);
1144
+ }
1145
+
1146
+ return gaps;
1147
+ }
1148
+ };
1149
+
1150
+ /**
1151
+ * Searches for a cell in the same row that starts a rowspan and is positioned immediately before the current cell.
1152
+ * Alternatively, it finds a cell where the colspan initiating the rowspan extends to the cell just before the current one.
1153
+ *
1154
+ * @param {Array<object>} arr - An array representing cells in a row.
1155
+ * @param {number} i - The index of the current cell to search backward from.
1156
+ * @returns {object|null} The starting cell of the rowspan if found; otherwise, `null`.
1157
+ */
1158
+ LayoutBuilder.prototype._findStartingRowSpanCell = function (arr, i) {
1159
+ var requiredColspan = 1;
1160
+ for (var index = i - 1; index >= 0; index--) {
1161
+ if (!arr[index]._span) {
1162
+ if (arr[index].rowSpan > 1 && (arr[index].colSpan || 1) === requiredColspan) {
1163
+ return arr[index];
1164
+ } else {
1165
+ return null;
1166
+ }
1167
+ }
1168
+ requiredColspan++;
1169
+ }
1170
+ return null;
1171
+ };
1172
+
1173
+ /**
1174
+ * Retrieves a page break description for a specified page from a list of page breaks.
1175
+ *
1176
+ * @param {Array<object>} pageBreaks - An array of page break descriptions, each containing `prevPage` properties.
1177
+ * @param {number} page - The page number to find the associated page break for.
1178
+ * @returns {object|undefined} The page break description object for the specified page if found; otherwise, `undefined`.
1179
+ */
1180
+ LayoutBuilder.prototype._getPageBreak = function (pageBreaks, page) {
1181
+ return pageBreaks.find(desc => desc.prevPage === page);
1182
+ };
1183
+
1184
+ LayoutBuilder.prototype._getPageBreakListBySpan = function (tableNode, page, rowIndex) {
1185
+ if (!tableNode || !tableNode._breaksBySpan) {
1186
+ return null;
1187
+ }
1188
+ const breaksList = tableNode._breaksBySpan.filter(desc => desc.prevPage === page && rowIndex <= desc.rowIndexOfSpanEnd);
1189
+
1190
+ var y = Number.MAX_VALUE,
1191
+ prevY = Number.MIN_VALUE;
1192
+
1193
+ breaksList.forEach(b => {
1194
+ prevY = Math.max(b.prevY, prevY);
1195
+ y = Math.min(b.y, y);
1196
+ });
1197
+
1198
+ return {
1199
+ prevPage: page,
1200
+ prevY: prevY,
1201
+ y: y
1202
+ };
1203
+ };
1204
+
1205
+ LayoutBuilder.prototype._findSameRowPageBreakByRowSpanData = function (breaksBySpan, page, rowIndex) {
1206
+ if (!breaksBySpan) {
1207
+ return null;
1208
+ }
1209
+ return breaksBySpan.find(desc => desc.prevPage === page && rowIndex === desc.rowIndexOfSpanEnd);
1210
+ };
1211
+
1212
+ LayoutBuilder.prototype._updatePageBreaksData = function (pageBreaks, tableNode, rowIndex) {
1213
+ Object.keys(tableNode._bottomByPage).forEach(p => {
1214
+ const page = Number(p);
1215
+ const pageBreak = this._getPageBreak(pageBreaks, page);
1216
+ if (pageBreak) {
1217
+ pageBreak.prevY = Math.max(pageBreak.prevY, tableNode._bottomByPage[page]);
1218
+ }
1219
+ if (tableNode._breaksBySpan && tableNode._breaksBySpan.length > 0) {
1220
+ const breaksBySpanList = tableNode._breaksBySpan.filter(pb => pb.prevPage === page && rowIndex <= pb.rowIndexOfSpanEnd);
1221
+ if (breaksBySpanList && breaksBySpanList.length > 0) {
1222
+ breaksBySpanList.forEach(b => {
1223
+ b.prevY = Math.max(b.prevY, tableNode._bottomByPage[page]);
1224
+ });
1225
+ }
1226
+ }
1227
+ });
1228
+ };
1229
+
1230
+ /**
1231
+ * Resolves the Y-coordinates for a target object by comparing two break points.
1232
+ *
1233
+ * @param {object} break1 - The first break point with `prevY` and `y` properties.
1234
+ * @param {object} break2 - The second break point with `prevY` and `y` properties.
1235
+ * @param {object} target - The target object to be updated with resolved Y-coordinates.
1236
+ * @property {number} target.prevY - Updated to the maximum `prevY` value between `break1` and `break2`.
1237
+ * @property {number} target.y - Updated to the minimum `y` value between `break1` and `break2`.
1238
+ */
1239
+ LayoutBuilder.prototype._resolveBreakY = function (break1, break2, target) {
1240
+ target.prevY = Math.max(break1.prevY, break2.prevY);
1241
+ target.y = Math.min(break1.y, break2.y);
1242
+ };
1243
+
1244
+ LayoutBuilder.prototype._storePageBreakData = function (data, startsRowSpan, pageBreaks, tableNode) {
1245
+ var pageDesc;
1246
+ var pageDescBySpan;
1247
+
1248
+ if (!startsRowSpan) {
1249
+ pageDesc = this._getPageBreak(pageBreaks, data.prevPage);
1250
+ pageDescBySpan = this._getPageBreakListBySpan(tableNode, data.prevPage, data.rowIndex);
1251
+ if (!pageDesc) {
1252
+ pageDesc = Object.assign({}, data);
1253
+ pageBreaks.push(pageDesc);
1254
+ }
1255
+
1256
+ if (pageDescBySpan) {
1257
+ this._resolveBreakY(pageDesc, pageDescBySpan, pageDesc);
1258
+ }
1259
+ this._resolveBreakY(pageDesc, data, pageDesc);
1260
+ } else {
1261
+ var breaksBySpan = tableNode && tableNode._breaksBySpan || null;
1262
+ pageDescBySpan = this._findSameRowPageBreakByRowSpanData(breaksBySpan, data.prevPage, data.rowIndex);
1263
+ if (!pageDescBySpan) {
1264
+ pageDescBySpan = Object.assign({}, data, {
1265
+ rowIndexOfSpanEnd: data.rowIndex + data.rowSpan - 1
1266
+ });
1267
+ if (!tableNode._breaksBySpan) {
1268
+ tableNode._breaksBySpan = [];
1269
+ }
1270
+ tableNode._breaksBySpan.push(pageDescBySpan);
1271
+ }
1272
+ pageDescBySpan.prevY = Math.max(pageDescBySpan.prevY, data.prevY);
1273
+ pageDescBySpan.y = Math.min(pageDescBySpan.y, data.y);
1274
+ pageDesc = this._getPageBreak(pageBreaks, data.prevPage);
1275
+ if (pageDesc) {
1276
+ this._resolveBreakY(pageDesc, pageDescBySpan, pageDesc);
1277
+ }
1278
+ }
1279
+ };
1280
+
1281
+ /**
1282
+ * Calculates the left offset for a column based on the specified gap values.
1283
+ *
1284
+ * @param {number} i - The index of the column for which the offset is being calculated.
1285
+ * @param {Array<number>} gaps - An array of gap values for each column.
1286
+ * @returns {number} The left offset for the column. Returns `gaps[i]` if it exists, otherwise `0`.
1287
+ */
1288
+ LayoutBuilder.prototype._colLeftOffset = function (i, gaps) {
1289
+ if (gaps && gaps.length > i) {
1290
+ return gaps[i];
1291
+ }
1292
+ return 0;
1293
+ };
1294
+
1295
+ /**
1296
+ * Checks if a cell or node contains an inline image.
1297
+ *
1298
+ * @param {object} node - The node to check for inline images.
1299
+ * @returns {boolean} True if the node contains an inline image; otherwise, false.
1300
+ */
1301
+ LayoutBuilder.prototype._containsInlineImage = function (node) {
1302
+ if (!node) {
1303
+ return false;
1304
+ }
1305
+
1306
+ // Direct image node
1307
+ if (node.image) {
1308
+ return true;
1309
+ }
1310
+
1311
+
1312
+ // Check in table
1313
+ if (node.table && isArray(node.table.body)) {
1314
+ for (var r = 0; r < node.table.body.length; r++) {
1315
+ if (isArray(node.table.body[r])) {
1316
+ for (var c = 0; c < node.table.body[r].length; c++) {
1317
+ if (this._containsInlineImage(node.table.body[r][c])) {
1318
+ return true;
1319
+ }
1320
+ }
1321
+ }
1322
+ }
1323
+ }
1324
+
1325
+ return false;
1326
+ };
1327
+
1328
+
1329
+ /**
1330
+ * Gets the maximum image height from cells in a row.
1331
+ *
1332
+ * @param {Array<object>} cells - Array of cell objects in a row.
1333
+ * @returns {number} The maximum image height found in the cells.
1334
+ */
1335
+ LayoutBuilder.prototype._getMaxImageHeight = function (cells) {
1336
+ var maxHeight = 0;
1337
+
1338
+ for (var i = 0; i < cells.length; i++) {
1339
+ var cellHeight = this._getImageHeightFromNode(cells[i]);
1340
+ if (cellHeight > maxHeight) {
1341
+ maxHeight = cellHeight;
1342
+ }
1343
+ }
1344
+
1345
+ return maxHeight;
1346
+ };
1347
+
1348
+ /**
1349
+ * Gets the maximum estimated height from cells in a row.
1350
+ * Checks for measured heights (_height property) and content-based heights.
1351
+ *
1352
+ * @param {Array<object>} cells - Array of cell objects in a row.
1353
+ * @returns {number} The maximum estimated height found in the cells, or 0 if cannot estimate.
1354
+ */
1355
+ LayoutBuilder.prototype._getMaxCellHeight = function (cells) {
1356
+ var maxHeight = 0;
1357
+
1358
+ for (var i = 0; i < cells.length; i++) {
1359
+ var cell = cells[i];
1360
+ if (!cell || cell._span) {
1361
+ continue; // Skip null cells and span placeholders
1362
+ }
1363
+
1364
+ var cellHeight = 0;
1365
+
1366
+ // Check if cell has measured height from docMeasure phase
1367
+ if (cell._height) {
1368
+ cellHeight = cell._height;
1369
+ }
1370
+ // Check for image content
1371
+ else if (cell.image && cell._maxHeight) {
1372
+ cellHeight = cell._maxHeight;
1373
+ }
1374
+ // Check for nested content with height
1375
+ else {
1376
+ cellHeight = this._getImageHeightFromNode(cell);
1377
+ }
1378
+
1379
+ if (cellHeight > maxHeight) {
1380
+ maxHeight = cellHeight;
1381
+ }
1382
+ }
1383
+
1384
+ return maxHeight;
1385
+ };
1386
+
1387
+ /**
1388
+ * Recursively gets image height from a node.
1389
+ *
1390
+ * @param {object} node - The node to extract image height from.
1391
+ * @returns {number} The image height if found; otherwise, 0.
1392
+ */
1393
+ LayoutBuilder.prototype._getImageHeightFromNode = function (node) {
1394
+ if (!node) {
1395
+ return 0;
1396
+ }
1397
+
1398
+ // Direct image node with height
1399
+ if (node.image && node._height) {
1400
+ return node._height;
1401
+ }
1402
+
1403
+ var maxHeight = 0;
1404
+
1405
+ // Check in stack
1406
+ if (isArray(node.stack)) {
1407
+ for (var i = 0; i < node.stack.length; i++) {
1408
+ var h = this._getImageHeightFromNode(node.stack[i]);
1409
+ if (h > maxHeight) {
1410
+ maxHeight = h;
1411
+ }
1412
+ }
1413
+ }
1414
+
1415
+ // Check in columns
1416
+ if (isArray(node.columns)) {
1417
+ for (var j = 0; j < node.columns.length; j++) {
1418
+ var h2 = this._getImageHeightFromNode(node.columns[j]);
1419
+ if (h2 > maxHeight) {
1420
+ maxHeight = h2;
1421
+ }
1422
+ }
1423
+ }
1424
+
1425
+ // Check in table
1426
+ if (node.table && isArray(node.table.body)) {
1427
+ for (var r = 0; r < node.table.body.length; r++) {
1428
+ if (isArray(node.table.body[r])) {
1429
+ for (var c = 0; c < node.table.body[r].length; c++) {
1430
+ var h3 = this._getImageHeightFromNode(node.table.body[r][c]);
1431
+ if (h3 > maxHeight) {
1432
+ maxHeight = h3;
1433
+ }
1434
+ }
1435
+ }
1436
+ }
1437
+ }
1438
+
1439
+ return maxHeight;
1440
+ };
1441
+
1442
+
1443
+ /**
1444
+ * Retrieves the ending cell for a row span in case it exists in a specified table column.
1445
+ *
1446
+ * @param {Array<Array<object>>} tableBody - The table body, represented as a 2D array of cell objects.
1447
+ * @param {number} rowIndex - The index of the starting row for the row span.
1448
+ * @param {object} column - The column object containing row span information.
1449
+ * @param {number} columnIndex - The index of the column within the row.
1450
+ * @returns {object|null} The cell at the end of the row span if it exists; otherwise, `null`.
1451
+ * @throws {Error} If the row span extends beyond the total row count.
1452
+ */
1453
+ LayoutBuilder.prototype._getRowSpanEndingCell = function (tableBody, rowIndex, column, columnIndex) {
1454
+ if (column.rowSpan && column.rowSpan > 1) {
1455
+ var endingRow = rowIndex + column.rowSpan - 1;
1456
+ if (endingRow >= tableBody.length) {
1457
+ throw new Error(`Row span for column ${columnIndex} (with indexes starting from 0) exceeded row count`);
1458
+ }
1459
+ return tableBody[endingRow][columnIndex];
1460
+ }
1461
+
1462
+ return null;
1463
+ };
1464
+
1465
+ LayoutBuilder.prototype.processRow = function ({ marginX = [0, 0], dontBreakRows = false, rowsWithoutPageBreak = 0, cells, widths, gaps, tableNode, tableBody, rowIndex, height, heightOffset = 0 }) {
1466
+ var self = this;
1467
+ var isUnbreakableRow = dontBreakRows || rowIndex <= rowsWithoutPageBreak - 1;
1468
+ var pageBreaks = [];
1469
+ var pageBreaksByRowSpan = [];
1470
+ var positions = [];
1471
+ var willBreakByHeight = false;
1472
+ var columnAlignIndexes = {};
1473
+ var hasInlineImage = false;
1474
+ widths = widths || cells;
1475
+
1476
+ // Check if row contains inline images
1477
+ if (!isUnbreakableRow) {
1478
+ for (var cellIdx = 0; cellIdx < cells.length; cellIdx++) {
1479
+ if (self._containsInlineImage(cells[cellIdx])) {
1480
+ hasInlineImage = true;
1481
+ break;
1482
+ }
1483
+ }
1484
+ }
1485
+
1486
+ // Check if row would cause page break and force move to next page first
1487
+ // This keeps the entire row together on the new page
1488
+ // Apply when: forcePageBreakForAllRows is enabled OR row has inline images
1489
+
1490
+ // Priority for forcePageBreakForAllRows setting:
1491
+ // 1. Table-specific layout.forcePageBreakForAllRows
1492
+ // 2. Tables with footerGapCollect: 'product-items' (auto-enabled)
1493
+ // 3. Global footerGapOption.forcePageBreakForAllRows
1494
+ var tableLayout = tableNode && tableNode._layout;
1495
+ var footerGapOpt = self.writer.context()._footerGapOption;
1496
+ var shouldForcePageBreak = false;
1497
+
1498
+ if (tableLayout && tableLayout.forcePageBreakForAllRows !== undefined) {
1499
+ // Table-specific setting takes precedence
1500
+ shouldForcePageBreak = tableLayout.forcePageBreakForAllRows === true;
1501
+ }
1502
+
1503
+ if (!isUnbreakableRow && (shouldForcePageBreak || hasInlineImage)) {
1504
+ var availableHeight = self.writer.context().availableHeight;
1505
+
1506
+ // Calculate estimated height from actual cell content
1507
+ var estimatedHeight = height; // Use provided height if available
1508
+
1509
+ if (!estimatedHeight) {
1510
+ // Try to get maximum cell height from measured content
1511
+ var maxCellHeight = self._getMaxCellHeight(cells);
1512
+
1513
+ if (maxCellHeight > 0) {
1514
+ // Add padding for table borders and cell padding (approximate)
1515
+ // Using smaller padding to avoid overly conservative page break detection
1516
+ var tablePadding = 10; // Account for row padding and borders
1517
+ estimatedHeight = maxCellHeight + tablePadding;
1518
+ } else {
1519
+ // Fallback: use minRowHeight from table layout or global config if provided
1520
+ // Priority: table-specific layout > global footerGapOption > default 80
1521
+ // Using higher default (80px) to handle text rows with wrapping and multiple lines
1522
+ // This is conservative but prevents text rows from being split across pages
1523
+ var minRowHeight = (tableLayout && tableLayout.minRowHeight) || (footerGapOpt && footerGapOpt.minRowHeight) || 80;
1524
+ estimatedHeight = minRowHeight;
1525
+ }
1526
+ }
1527
+
1528
+ // Apply heightOffset from table definition to adjust page break calculation
1529
+ // This allows fine-tuning of page break detection for specific tables
1530
+ // heightOffset is passed as parameter from processTable
1531
+ if (heightOffset) {
1532
+ estimatedHeight = (estimatedHeight || 0) + heightOffset;
1533
+ }
1534
+
1535
+ // Check if row won't fit on current page
1536
+ // Strategy: Force break if row won't fit AND we're not too close to page boundary
1537
+ // "Too close" means availableHeight is very small (< 5px) - at that point forcing
1538
+ // a break would create a nearly-blank page
1539
+ var minSpaceThreshold = 5; // Only skip forced break if < 5px space left
1540
+
1541
+ if (estimatedHeight > availableHeight && availableHeight > minSpaceThreshold) {
1542
+ var currentPage = self.writer.context().page;
1543
+ var currentY = self.writer.context().y;
1544
+
1545
+ // Draw vertical lines to fill the gap from current position to page break
1546
+ // This ensures vertical lines extend all the way to the bottom of the page
1547
+ if (tableNode && tableNode._tableProcessor && rowIndex > 0) {
1548
+ tableNode._tableProcessor.drawVerticalLinesForForcedPageBreak(
1549
+ rowIndex,
1550
+ self.writer,
1551
+ currentY,
1552
+ currentY + availableHeight
1553
+ );
1554
+ }
1555
+
1556
+ // Move to next page before processing row
1557
+ self.writer.context().moveDown(availableHeight);
1558
+ self.writer.moveToNextPage();
1559
+
1560
+ // Track this page break so tableProcessor can draw borders correctly
1561
+ pageBreaks.push({
1562
+ prevPage: currentPage,
1563
+ prevY: currentY + availableHeight,
1564
+ y: self.writer.context().y,
1565
+ page: self.writer.context().page,
1566
+ forced: true // Mark as forced page break
1567
+ });
1568
+
1569
+ // Mark that this row should not break anymore
1570
+ isUnbreakableRow = true;
1571
+ dontBreakRows = true;
1572
+ }
1573
+ }
1574
+
1575
+ // Check if row should break by height
1576
+ if (!isUnbreakableRow && height > self.writer.context().availableHeight) {
1577
+ willBreakByHeight = true;
1578
+ }
1579
+
1580
+ // Use the marginX if we are in a top level table/column (not nested)
1581
+ const marginXParent = self.nestedLevel === 1 ? marginX : null;
1582
+ const _bottomByPage = tableNode ? tableNode._bottomByPage : null;
1583
+ this.writer.context().beginColumnGroup(marginXParent, _bottomByPage);
1584
+
1585
+ for (var i = 0, l = cells.length; i < l; i++) {
1586
+ var cell = cells[i];
1587
+
1588
+ // Page change handler
1589
+
1590
+ this.tracker.auto('pageChanged', storePageBreakClosure, function () {
1591
+ var width = widths[i]._calcWidth;
1592
+ var leftOffset = self._colLeftOffset(i, gaps);
1593
+ // Check if exists and retrieve the cell that started the rowspan in case we are in the cell just after
1594
+ var startingSpanCell = self._findStartingRowSpanCell(cells, i);
1595
+
1596
+ if (cell.colSpan && cell.colSpan > 1) {
1597
+ for (var j = 1; j < cell.colSpan; j++) {
1598
+ width += widths[++i]._calcWidth + gaps[i];
1599
+ }
1600
+ }
1601
+
1602
+ // if rowspan starts in this cell, we retrieve the last cell affected by the rowspan
1603
+ const rowSpanEndingCell = self._getRowSpanEndingCell(tableBody, rowIndex, cell, i);
1604
+ if (rowSpanEndingCell) {
1605
+ // We store a reference of the ending cell in the first cell of the rowspan
1606
+ cell._endingCell = rowSpanEndingCell;
1607
+ cell._endingCell._startingRowSpanY = cell._startingRowSpanY;
1608
+ }
1609
+
1610
+ // If we are after a cell that started a rowspan
1611
+ var endOfRowSpanCell = null;
1612
+ if (startingSpanCell && startingSpanCell._endingCell) {
1613
+ // Reference to the last cell of the rowspan
1614
+ endOfRowSpanCell = startingSpanCell._endingCell;
1615
+ // Store if we are in an unbreakable block when we save the context and the originalX
1616
+ if (self.writer.transactionLevel > 0) {
1617
+ endOfRowSpanCell._isUnbreakableContext = true;
1618
+ endOfRowSpanCell._originalXOffset = self.writer.originalX;
1619
+ }
1620
+ }
1621
+
1622
+ // We pass the endingSpanCell reference to store the context just after processing rowspan cell
1623
+ self.writer.context().beginColumn(width, leftOffset, endOfRowSpanCell, heightOffset);
1624
+
1625
+ if (!cell._span) {
1626
+ self.processNode(cell);
1627
+ self.writer.context().updateBottomByPage();
1628
+ addAll(positions, cell.positions);
1629
+ if (cell.verticalAlign && cell._verticalAlignIdx !== undefined) {
1630
+ columnAlignIndexes[i] = cell._verticalAlignIdx;
1631
+ }
1632
+ } else if (cell._columnEndingContext) {
1633
+ var discountY = 0;
1634
+ if (dontBreakRows) {
1635
+ // Calculate how many points we have to discount to Y when dontBreakRows and rowSpan are combined
1636
+ const ctxBeforeRowSpanLastRow = self.writer.writer.contextStack[self.writer.writer.contextStack.length - 1];
1637
+ discountY = ctxBeforeRowSpanLastRow.y - cell._startingRowSpanY;
1638
+ }
1639
+ var originalXOffset = 0;
1640
+ // If context was saved from an unbreakable block and we are not in an unbreakable block anymore
1641
+ // We have to sum the originalX (X before starting unbreakable block) to X
1642
+ if (cell._isUnbreakableContext && !self.writer.transactionLevel) {
1643
+ originalXOffset = cell._originalXOffset;
1644
+ }
1645
+ // row-span ending
1646
+ // Recover the context after processing the rowspanned cell
1647
+ self.writer.context().markEnding(cell, originalXOffset, discountY);
1648
+ }
1649
+ });
1650
+ }
1651
+
1652
+ // Check if last cell is part of a span
1653
+ var endingSpanCell = null;
1654
+ var lastColumn = cells.length > 0 ? cells[cells.length - 1] : null;
1655
+ if (lastColumn) {
1656
+ // Previous column cell has a rowspan
1657
+ if (lastColumn._endingCell) {
1658
+ endingSpanCell = lastColumn._endingCell;
1659
+ // Previous column cell is part of a span
1660
+ } else if (lastColumn._span === true) {
1661
+ // We get the cell that started the span where we set a reference to the ending cell
1662
+ const startingSpanCell = this._findStartingRowSpanCell(cells, cells.length);
1663
+ if (startingSpanCell) {
1664
+ // Context will be stored here (ending cell)
1665
+ endingSpanCell = startingSpanCell._endingCell;
1666
+ // Store if we are in an unbreakable block when we save the context and the originalX
1667
+ if (this.writer.transactionLevel > 0) {
1668
+ endingSpanCell._isUnbreakableContext = true;
1669
+ endingSpanCell._originalXOffset = this.writer.originalX;
1670
+ }
1671
+ }
1672
+ }
1673
+ }
1674
+
1675
+ // If content did not break page, check if we should break by height
1676
+ if (willBreakByHeight && !isUnbreakableRow && pageBreaks.length === 0) {
1677
+ this.writer.context().moveDown(this.writer.context().availableHeight);
1678
+ this.writer.moveToNextPage();
1679
+ }
1680
+
1681
+ var bottomByPage = this.writer.context().completeColumnGroup(height, endingSpanCell);
1682
+ var rowHeight = this.writer.context().height;
1683
+ for (var colIndex = 0, columnsLength = cells.length; colIndex < columnsLength; colIndex++) {
1684
+ var columnNode = cells[colIndex];
1685
+ if (columnNode._span) {
1686
+ continue;
1687
+ }
1688
+ if (columnNode.verticalAlign && columnAlignIndexes[colIndex] !== undefined) {
1689
+ var alignEntry = self.verticalAlignItemStack[columnAlignIndexes[colIndex]];
1690
+ if (alignEntry && alignEntry.begin && alignEntry.begin.item) {
1691
+ alignEntry.begin.item.viewHeight = rowHeight;
1692
+ alignEntry.begin.item.nodeHeight = columnNode._height;
1693
+ }
1694
+ }
1695
+ if (columnNode.layers) {
1696
+ columnNode.layers.forEach(function (layer) {
1697
+ if (layer.verticalAlign && layer._verticalAlignIdx !== undefined) {
1698
+ var layerEntry = self.verticalAlignItemStack[layer._verticalAlignIdx];
1699
+ if (layerEntry && layerEntry.begin && layerEntry.begin.item) {
1700
+ layerEntry.begin.item.viewHeight = rowHeight;
1701
+ layerEntry.begin.item.nodeHeight = layer._height;
1702
+ }
1703
+ }
1704
+ });
1705
+ }
1706
+ }
1707
+
1708
+ if (tableNode) {
1709
+ tableNode._bottomByPage = bottomByPage;
1710
+ // If there are page breaks in this row, update data with prevY of last cell
1711
+ this._updatePageBreaksData(pageBreaks, tableNode, rowIndex);
1712
+ }
1713
+
1714
+ return {
1715
+ pageBreaksBySpan: pageBreaksByRowSpan,
1716
+ pageBreaks: pageBreaks,
1717
+ positions: positions
1718
+ };
1719
+
1720
+ function storePageBreakClosure(data) {
1721
+ const startsRowSpan = cell.rowSpan && cell.rowSpan > 1;
1722
+ if (startsRowSpan) {
1723
+ data.rowSpan = cell.rowSpan;
1724
+ }
1725
+ data.rowIndex = rowIndex;
1726
+ self._storePageBreakData(data, startsRowSpan, pageBreaks, tableNode);
1727
+ }
1728
+
1729
+ };
1730
+
1731
+ // lists
1732
+ LayoutBuilder.prototype.processList = function (orderedList, node) {
1733
+ var self = this,
1734
+ items = orderedList ? node.ol : node.ul,
1735
+ gapSize = node._gapSize;
1736
+
1737
+ this.writer.context().addMargin(gapSize.width);
1738
+
1739
+ var nextMarker;
1740
+ this.tracker.auto('lineAdded', addMarkerToFirstLeaf, function () {
1741
+ items.forEach(function (item) {
1742
+ nextMarker = item.listMarker;
1743
+ self.processNode(item);
1744
+ addAll(node.positions, item.positions);
1745
+ });
1746
+ });
1747
+
1748
+ this.writer.context().addMargin(-gapSize.width);
1749
+
1750
+ function addMarkerToFirstLeaf(line) {
1751
+ // I'm not very happy with the way list processing is implemented
1752
+ // (both code and algorithm should be rethinked)
1753
+ if (nextMarker) {
1754
+ var marker = nextMarker;
1755
+ nextMarker = null;
1756
+
1757
+ if (marker.canvas) {
1758
+ var vector = marker.canvas[0];
1759
+
1760
+ offsetVector(vector, -marker._minWidth, 0);
1761
+ self.writer.addVector(vector);
1762
+ } else if (marker._inlines) {
1763
+ var markerLine = new Line(self.pageSize.width);
1764
+ markerLine.addInline(marker._inlines[0]);
1765
+ markerLine.x = -marker._minWidth;
1766
+ markerLine.y = line.getAscenderHeight() - markerLine.getAscenderHeight();
1767
+ self.writer.addLine(markerLine, true);
1768
+ }
1769
+ }
1770
+ }
1771
+ };
1772
+
1773
+ // tables
1774
+ LayoutBuilder.prototype.processTable = function (tableNode) {
1775
+ this.nestedLevel++;
1776
+ var processor = new TableProcessor(tableNode);
1777
+
1778
+ // Store processor reference for forced page break vertical line drawing
1779
+ tableNode._tableProcessor = processor;
1780
+
1781
+ processor.beginTable(this.writer);
1782
+
1783
+ var rowHeights = tableNode.table.heights;
1784
+ for (var i = 0, l = tableNode.table.body.length; i < l; i++) {
1785
+ // if dontBreakRows and row starts a rowspan
1786
+ // we store the 'y' of the beginning of each rowSpan
1787
+ if (processor.dontBreakRows) {
1788
+ tableNode.table.body[i].forEach(cell => {
1789
+ if (cell.rowSpan && cell.rowSpan > 1) {
1790
+ cell._startingRowSpanY = this.writer.context().y;
1791
+ }
1792
+ });
1793
+ }
1794
+
1795
+ processor.beginRow(i, this.writer);
1796
+
1797
+ var height;
1798
+ if (isFunction(rowHeights)) {
1799
+ height = rowHeights(i);
1800
+ } else if (isArray(rowHeights)) {
1801
+ height = rowHeights[i];
1802
+ } else {
1803
+ height = rowHeights;
1804
+ }
1805
+
1806
+ if (height === 'auto') {
1807
+ height = undefined;
1808
+ }
1809
+
1810
+ var heightOffset = tableNode.heightOffset != undefined ? tableNode.heightOffset : 0;
1811
+
1812
+ var pageBeforeProcessing = this.writer.context().page;
1813
+
1814
+ var result = this.processRow({
1815
+ marginX: tableNode._margin ? [tableNode._margin[0], tableNode._margin[2]] : [0, 0],
1816
+ dontBreakRows: processor.dontBreakRows,
1817
+ rowsWithoutPageBreak: processor.rowsWithoutPageBreak,
1818
+ cells: tableNode.table.body[i],
1819
+ widths: tableNode.table.widths,
1820
+ gaps: tableNode._offsets.offsets,
1821
+ tableBody: tableNode.table.body,
1822
+ tableNode,
1823
+ rowIndex: i,
1824
+ height,
1825
+ heightOffset
1826
+ });
1827
+ addAll(tableNode.positions, result.positions);
1828
+
1829
+ if (!result.pageBreaks || result.pageBreaks.length === 0) {
1830
+ var breaksBySpan = tableNode && tableNode._breaksBySpan || null;
1831
+ var breakBySpanData = this._findSameRowPageBreakByRowSpanData(breaksBySpan, pageBeforeProcessing, i);
1832
+ if (breakBySpanData) {
1833
+ var finalBreakBySpanData = this._getPageBreakListBySpan(tableNode, breakBySpanData.prevPage, i);
1834
+ result.pageBreaks.push(finalBreakBySpanData);
1835
+ }
1836
+ }
1837
+
1838
+ // Get next row cells for look-ahead page break detection
1839
+ var nextRowCells = (i + 1 < tableNode.table.body.length) ? tableNode.table.body[i + 1] : null;
1840
+
1841
+ processor.endRow(i, this.writer, result.pageBreaks, nextRowCells, this);
1842
+ }
1843
+
1844
+ processor.endTable(this.writer);
1845
+ this.nestedLevel--;
1846
+ if (this.nestedLevel === 0) {
1847
+ this.writer.context().resetMarginXTopParent();
1848
+ }
1849
+ };
1850
+
1851
+ // leafs (texts)
1852
+ LayoutBuilder.prototype.processLeaf = function (node) {
1853
+ var line = this.buildNextLine(node);
1854
+ if (line && (node.tocItem || node.id)) {
1855
+ line._node = node;
1856
+ }
1857
+ var currentHeight = (line) ? line.getHeight() : 0;
1858
+ var maxHeight = node.maxHeight || -1;
1859
+
1860
+ if (line) {
1861
+ var nodeId = getNodeId(node);
1862
+ if (nodeId) {
1863
+ line.id = nodeId;
1864
+ }
1865
+ }
1866
+
1867
+ if (node._tocItemRef) {
1868
+ line._pageNodeRef = node._tocItemRef;
1869
+ }
1870
+
1871
+ if (node._pageRef) {
1872
+ line._pageNodeRef = node._pageRef._nodeRef;
1873
+ }
1874
+
1875
+ if (line && line.inlines && isArray(line.inlines)) {
1876
+ for (var i = 0, l = line.inlines.length; i < l; i++) {
1877
+ if (line.inlines[i]._tocItemRef) {
1878
+ line.inlines[i]._pageNodeRef = line.inlines[i]._tocItemRef;
1879
+ }
1880
+
1881
+ if (line.inlines[i]._pageRef) {
1882
+ line.inlines[i]._pageNodeRef = line.inlines[i]._pageRef._nodeRef;
1883
+ }
1884
+ }
1885
+ }
1886
+
1887
+ while (line && (maxHeight === -1 || currentHeight < maxHeight)) {
1888
+ var positions = this.writer.addLine(line);
1889
+ node.positions.push(positions);
1890
+ line = this.buildNextLine(node);
1891
+ if (line) {
1892
+ currentHeight += line.getHeight();
1893
+ }
1894
+ }
1895
+ };
1896
+
1897
+ LayoutBuilder.prototype.processToc = function (node) {
1898
+ if (node.toc.title) {
1899
+ this.processNode(node.toc.title);
1900
+ }
1901
+ if (node.toc._table) {
1902
+ this.processNode(node.toc._table);
1903
+ }
1904
+ };
1905
+
1906
+ LayoutBuilder.prototype.buildNextLine = function (textNode) {
1907
+
1908
+ function cloneInline(inline) {
1909
+ var newInline = inline.constructor();
1910
+ for (var key in inline) {
1911
+ newInline[key] = inline[key];
1912
+ }
1913
+ return newInline;
1914
+ }
1915
+
1916
+ if (!textNode._inlines || textNode._inlines.length === 0) {
1917
+ return null;
1918
+ }
1919
+
1920
+ var line = new Line(this.writer.context().availableWidth);
1921
+ var textTools = new TextTools(null);
1922
+
1923
+ while (textNode._inlines && textNode._inlines.length > 0 && line.hasEnoughSpaceForInline(textNode._inlines[0])) {
1924
+ var inline = textNode._inlines.shift();
1925
+
1926
+ if (!inline.noWrap && inline.text.length > 1 && inline.width > line.maxWidth) {
1927
+ var widthPerChar = inline.width / inline.text.length;
1928
+ var maxChars = Math.floor(line.maxWidth / widthPerChar);
1929
+ if (maxChars < 1) {
1930
+ maxChars = 1;
1931
+ }
1932
+ if (maxChars < inline.text.length) {
1933
+ var newInline = cloneInline(inline);
1934
+
1935
+ newInline.text = inline.text.substr(maxChars);
1936
+ inline.text = inline.text.substr(0, maxChars);
1937
+
1938
+ newInline.width = textTools.widthOfString(newInline.text, newInline.font, newInline.fontSize, newInline.characterSpacing);
1939
+ inline.width = textTools.widthOfString(inline.text, inline.font, inline.fontSize, inline.characterSpacing);
1940
+
1941
+ textNode._inlines.unshift(newInline);
1942
+ }
1943
+ }
1944
+
1945
+ line.addInline(inline);
1946
+ }
1947
+
1948
+ line.lastLineInParagraph = textNode._inlines.length === 0;
1949
+
1950
+ return line;
1951
+ };
1952
+
1953
+ // images
1954
+ LayoutBuilder.prototype.processImage = function (node) {
1955
+ var position = this.writer.addImage(node);
1956
+ node.positions.push(position);
1957
+ };
1958
+
1959
+ LayoutBuilder.prototype.processSVG = function (node) {
1960
+ var position = this.writer.addSVG(node);
1961
+ node.positions.push(position);
1962
+ };
1963
+
1964
+ LayoutBuilder.prototype.processCanvas = function (node) {
1965
+ var height = node._minHeight;
1966
+
1967
+ if (node.absolutePosition === undefined && this.writer.context().availableHeight < height) {
1968
+ // TODO: support for canvas larger than a page
1969
+ // TODO: support for other overflow methods
1970
+
1971
+ this.writer.moveToNextPage();
1972
+ }
1973
+
1974
+ this.writer.alignCanvas(node);
1975
+
1976
+ node.canvas.forEach(function (vector) {
1977
+ var position = this.writer.addVector(vector);
1978
+ node.positions.push(position);
1979
+ }, this);
1980
+
1981
+ this.writer.context().moveDown(height);
1982
+ };
1983
+
1984
+ LayoutBuilder.prototype.processQr = function (node) {
1985
+ var position = this.writer.addQr(node);
1986
+ node.positions.push(position);
1987
+ };
1988
+
1989
+ function processNode_test(node) {
1990
+ decorateNode(node);
1991
+
1992
+ var prevTop = testWriter.context().getCurrentPosition().top;
1993
+
1994
+ applyMargins(function () {
1995
+ var unbreakable = node.unbreakable;
1996
+ if (unbreakable) {
1997
+ testWriter.beginUnbreakableBlock();
1998
+ }
1999
+
2000
+ var absPosition = node.absolutePosition;
2001
+ if (absPosition) {
2002
+ testWriter.context().beginDetachedBlock();
2003
+ testWriter.context().moveTo(absPosition.x || 0, absPosition.y || 0);
2004
+ }
2005
+
2006
+ var relPosition = node.relativePosition;
2007
+ if (relPosition) {
2008
+ testWriter.context().beginDetachedBlock();
2009
+ if (typeof testWriter.context().moveToRelative === 'function') {
2010
+ testWriter.context().moveToRelative(relPosition.x || 0, relPosition.y || 0);
2011
+ } else if (currentLayoutBuilder && currentLayoutBuilder.writer) {
2012
+ testWriter.context().moveTo(
2013
+ (relPosition.x || 0) + currentLayoutBuilder.writer.context().x,
2014
+ (relPosition.y || 0) + currentLayoutBuilder.writer.context().y
2015
+ );
2016
+ }
2017
+ }
2018
+
2019
+ var verticalAlignBegin;
2020
+ if (node.verticalAlign) {
2021
+ verticalAlignBegin = testWriter.beginVerticalAlign(node.verticalAlign);
2022
+ }
2023
+
2024
+ if (node.stack) {
2025
+ processVerticalContainer_test(node);
2026
+ } else if (node.table) {
2027
+ processTable_test(node);
2028
+ } else if (node.text !== undefined) {
2029
+ processLeaf_test(node);
2030
+ }
2031
+
2032
+ if (absPosition || relPosition) {
2033
+ testWriter.context().endDetachedBlock();
2034
+ }
2035
+
2036
+ if (unbreakable) {
2037
+ testResult = testWriter.commitUnbreakableBlock_test();
2038
+ }
2039
+
2040
+ if (node.verticalAlign) {
2041
+ testVerticalAlignStack.push({ begin: verticalAlignBegin, end: testWriter.endVerticalAlign(node.verticalAlign) });
2042
+ }
2043
+ });
2044
+
2045
+ node._height = testWriter.context().getCurrentPosition().top - prevTop;
2046
+
2047
+ function applyMargins(callback) {
2048
+ var margin = node._margin;
2049
+
2050
+ if (node.pageBreak === 'before') {
2051
+ testWriter.moveToNextPage(node.pageOrientation);
2052
+ }
2053
+
2054
+ if (margin) {
2055
+ testWriter.context().moveDown(margin[1]);
2056
+ testWriter.context().addMargin(margin[0], margin[2]);
2057
+ }
2058
+
2059
+ callback();
2060
+
2061
+ if (margin) {
2062
+ testWriter.context().addMargin(-margin[0], -margin[2]);
2063
+ testWriter.context().moveDown(margin[3]);
2064
+ }
2065
+
2066
+ if (node.pageBreak === 'after') {
2067
+ testWriter.moveToNextPage(node.pageOrientation);
2068
+ }
2069
+ }
2070
+ }
2071
+
2072
+ function processVerticalContainer_test(node) {
2073
+ node.stack.forEach(function (item) {
2074
+ processNode_test(item);
2075
+ addAll(node.positions, item.positions);
2076
+ });
2077
+ }
2078
+
2079
+ function processTable_test(tableNode) {
2080
+ var processor = new TableProcessor(tableNode);
2081
+ processor.beginTable(testWriter);
2082
+
2083
+ for (var i = 0, l = tableNode.table.body.length; i < l; i++) {
2084
+ processor.beginRow(i, testWriter);
2085
+ var result = processRow_test(tableNode.table.body[i], tableNode.table.widths, tableNode._offsets ? tableNode._offsets.offsets : null, tableNode.table.body, i);
2086
+ addAll(tableNode.positions, result.positions);
2087
+ processor.endRow(i, testWriter, result.pageBreaks);
2088
+ }
2089
+
2090
+ processor.endTable(testWriter);
2091
+ }
2092
+
2093
+ function processRow_test(columns, widths, gaps, tableBody, tableRow) {
2094
+ var pageBreaks = [];
2095
+ var positions = [];
2096
+
2097
+ testTracker.auto('pageChanged', storePageBreakData, function () {
2098
+ widths = widths || columns;
2099
+
2100
+ testWriter.context().beginColumnGroup();
2101
+
2102
+ var verticalAlignCols = {};
2103
+
2104
+ for (var i = 0, l = columns.length; i < l; i++) {
2105
+ var column = columns[i];
2106
+ var width = widths[i]._calcWidth || widths[i];
2107
+ var leftOffset = colLeftOffset(i);
2108
+ var colIndex = i;
2109
+ if (column.colSpan && column.colSpan > 1) {
2110
+ for (var j = 1; j < column.colSpan; j++) {
2111
+ width += (widths[++i]._calcWidth || widths[i]) + (gaps ? gaps[i] : 0);
2112
+ }
2113
+ }
2114
+
2115
+ testWriter.context().beginColumn(width, leftOffset, getEndingCell(column, i));
2116
+
2117
+ if (!column._span) {
2118
+ processNode_test(column);
2119
+ verticalAlignCols[colIndex] = testVerticalAlignStack.length - 1;
2120
+ addAll(positions, column.positions);
2121
+ } else if (column._columnEndingContext) {
2122
+ testWriter.context().markEnding(column);
2123
+ }
2124
+ }
2125
+
2126
+ testWriter.context().completeColumnGroup();
2127
+
2128
+ var rowHeight = testWriter.context().height;
2129
+ for (var c = 0, clen = columns.length; c < clen; c++) {
2130
+ var col = columns[c];
2131
+ if (col._span) {
2132
+ continue;
2133
+ }
2134
+ if (col.verticalAlign && verticalAlignCols[c] !== undefined) {
2135
+ var alignItem = testVerticalAlignStack[verticalAlignCols[c]].begin.item;
2136
+ alignItem.viewHeight = rowHeight;
2137
+ alignItem.nodeHeight = col._height;
2138
+ }
2139
+ }
2140
+ });
2141
+
2142
+ return { pageBreaks: pageBreaks, positions: positions };
2143
+
2144
+ function storePageBreakData(data) {
2145
+ var pageDesc;
2146
+ for (var idx = 0, len = pageBreaks.length; idx < len; idx++) {
2147
+ var desc = pageBreaks[idx];
2148
+ if (desc.prevPage === data.prevPage) {
2149
+ pageDesc = desc;
2150
+ break;
2151
+ }
2152
+ }
2153
+
2154
+ if (!pageDesc) {
2155
+ pageDesc = data;
2156
+ pageBreaks.push(pageDesc);
2157
+ }
2158
+ pageDesc.prevY = Math.max(pageDesc.prevY, data.prevY);
2159
+ pageDesc.y = Math.min(pageDesc.y, data.y);
2160
+ }
2161
+
2162
+ function colLeftOffset(i) {
2163
+ if (gaps && gaps.length > i) {
2164
+ return gaps[i];
2165
+ }
2166
+ return 0;
2167
+ }
2168
+
2169
+ function getEndingCell(column, columnIndex) {
2170
+ if (column.rowSpan && column.rowSpan > 1) {
2171
+ var endingRow = tableRow + column.rowSpan - 1;
2172
+ if (endingRow >= tableBody.length) {
2173
+ throw new Error('Row span for column ' + columnIndex + ' (with indexes starting from 0) exceeded row count');
2174
+ }
2175
+ return tableBody[endingRow][columnIndex];
2176
+ }
2177
+ return null;
2178
+ }
2179
+ }
2180
+
2181
+ function processLeaf_test(node) {
2182
+ var line = buildNextLine_test(node);
2183
+ var currentHeight = line ? line.getHeight() : 0;
2184
+ var maxHeight = node.maxHeight || -1;
2185
+
2186
+ while (line && (maxHeight === -1 || currentHeight < maxHeight)) {
2187
+ var positions = testWriter.addLine(line);
2188
+ node.positions.push(positions);
2189
+ line = buildNextLine_test(node);
2190
+ if (line) {
2191
+ currentHeight += line.getHeight();
2192
+ }
2193
+ }
2194
+ }
2195
+
2196
+ function buildNextLine_test(textNode) {
2197
+ function cloneInline(inline) {
2198
+ var newInline = inline.constructor();
2199
+ for (var key in inline) {
2200
+ newInline[key] = inline[key];
2201
+ }
2202
+ return newInline;
2203
+ }
2204
+
2205
+ if (!textNode._inlines || textNode._inlines.length === 0) {
2206
+ return null;
2207
+ }
2208
+
2209
+ var line = new Line(testWriter.context().availableWidth);
2210
+ var textTools = new TextTools(null);
2211
+
2212
+ while (textNode._inlines && textNode._inlines.length > 0 && line.hasEnoughSpaceForInline(textNode._inlines[0])) {
2213
+ var inline = textNode._inlines.shift();
2214
+
2215
+ if (!inline.noWrap && inline.text.length > 1 && inline.width > line.maxWidth) {
2216
+ var widthPerChar = inline.width / inline.text.length;
2217
+ var maxChars = Math.floor(line.maxWidth / widthPerChar);
2218
+ if (maxChars < 1) {
2219
+ maxChars = 1;
2220
+ }
2221
+ if (maxChars < inline.text.length) {
2222
+ var newInline = cloneInline(inline);
2223
+
2224
+ newInline.text = inline.text.substr(maxChars);
2225
+ inline.text = inline.text.substr(0, maxChars);
2226
+
2227
+ newInline.width = textTools.widthOfString(newInline.text, newInline.font, newInline.fontSize, newInline.characterSpacing);
2228
+ inline.width = textTools.widthOfString(inline.text, inline.font, inline.fontSize, inline.characterSpacing);
2229
+
2230
+ textNode._inlines.unshift(newInline);
2231
+ }
2232
+ }
2233
+
2234
+ line.addInline(inline);
2235
+ }
2236
+
2237
+ line.lastLineInParagraph = textNode._inlines.length === 0;
2238
+
2239
+ return line;
2240
+ }
2241
+
2242
+ module.exports = LayoutBuilder;