pdfmake 0.3.0-beta.8 → 0.3.0

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