pdfmake-acroforms 0.3.4

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