@wirabyte/w-pdfmaker 0.0.0-stage → 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (142) hide show
  1. package/CHANGELOG.md +53 -0
  2. package/LICENSE +22 -0
  3. package/NOTICE.md +39 -0
  4. package/README.md +106 -2
  5. package/build/fonts/Roboto/Roboto-Italic.ttf +0 -0
  6. package/build/fonts/Roboto/Roboto-Medium.ttf +0 -0
  7. package/build/fonts/Roboto/Roboto-MediumItalic.ttf +0 -0
  8. package/build/fonts/Roboto/Roboto-Regular.ttf +0 -0
  9. package/build/fonts/Roboto.js +27 -0
  10. package/build/pdfmake.js +103161 -0
  11. package/build/pdfmake.js.map +1 -0
  12. package/build/pdfmake.min.js +3 -0
  13. package/build/pdfmake.min.js.map +1 -0
  14. package/build/standard-fonts/Courier.js +9 -0
  15. package/build/standard-fonts/Helvetica.js +9 -0
  16. package/build/standard-fonts/Symbol.js +9 -0
  17. package/build/standard-fonts/Times.js +9 -0
  18. package/build/standard-fonts/ZapfDingbats.js +9 -0
  19. package/build/vfs_fonts.js +6 -0
  20. package/build-vfs.js +44 -0
  21. package/fonts/Roboto/Roboto-Italic.ttf +0 -0
  22. package/fonts/Roboto/Roboto-Medium.ttf +0 -0
  23. package/fonts/Roboto/Roboto-MediumItalic.ttf +0 -0
  24. package/fonts/Roboto/Roboto-Regular.ttf +0 -0
  25. package/fonts/Roboto.js +8 -0
  26. package/fonts/THSarabunIT9/LICENSE.txt +7 -0
  27. package/fonts/THSarabunIT9/THSarabunIT9-Bold.ttf +0 -0
  28. package/fonts/THSarabunIT9/THSarabunIT9-BoldItalic.ttf +0 -0
  29. package/fonts/THSarabunIT9/THSarabunIT9-Italic.ttf +0 -0
  30. package/fonts/THSarabunIT9/THSarabunIT9.ttf +0 -0
  31. package/fonts/THSarabunNew/COPYING.GPLv2 +339 -0
  32. package/fonts/THSarabunNew/LICENSE.txt +13 -0
  33. package/fonts/THSarabunNew/THSarabunNew-Bold.ttf +0 -0
  34. package/fonts/THSarabunNew/THSarabunNew-BoldItalic.ttf +0 -0
  35. package/fonts/THSarabunNew/THSarabunNew-Italic.ttf +0 -0
  36. package/fonts/THSarabunNew/THSarabunNew.ttf +0 -0
  37. package/index.d.ts +167 -0
  38. package/interfaces.d.ts +2779 -0
  39. package/js/DocMeasure.js +695 -0
  40. package/js/DocPreprocessor.js +263 -0
  41. package/js/DocumentContext.js +563 -0
  42. package/js/ElementWriter.js +488 -0
  43. package/js/LayoutBuilder.js +1525 -0
  44. package/js/Line.js +105 -0
  45. package/js/OutputDocument.js +73 -0
  46. package/js/OutputDocumentServer.js +34 -0
  47. package/js/PDFDocument.js +322 -0
  48. package/js/PageElementWriter.js +302 -0
  49. package/js/PageSize.js +74 -0
  50. package/js/Printer.js +275 -0
  51. package/js/Renderer.js +439 -0
  52. package/js/SVGMeasure.js +94 -0
  53. package/js/StyleContextStack.js +191 -0
  54. package/js/TableProcessor.js +658 -0
  55. package/js/TextBreaker.js +164 -0
  56. package/js/TextDecorator.js +164 -0
  57. package/js/TextInlines.js +212 -0
  58. package/js/URLResolver.js +122 -0
  59. package/js/base.js +125 -0
  60. package/js/browser-extensions/OutputDocumentBrowser.js +82 -0
  61. package/js/browser-extensions/fonts/Roboto.js +38 -0
  62. package/js/browser-extensions/fonts/thai.js +28 -0
  63. package/js/browser-extensions/index.js +88 -0
  64. package/js/browser-extensions/pageUrls.js +79 -0
  65. package/js/browser-extensions/pdfMake.js +3 -0
  66. package/js/browser-extensions/standard-fonts/Courier.js +20 -0
  67. package/js/browser-extensions/standard-fonts/Helvetica.js +20 -0
  68. package/js/browser-extensions/standard-fonts/Symbol.js +17 -0
  69. package/js/browser-extensions/standard-fonts/Times.js +20 -0
  70. package/js/browser-extensions/standard-fonts/ZapfDingbats.js +17 -0
  71. package/js/browser-extensions/virtual-fs-cjs.js +3 -0
  72. package/js/columnCalculator.js +159 -0
  73. package/js/helpers/node.js +122 -0
  74. package/js/helpers/tools.js +46 -0
  75. package/js/helpers/variableType.js +59 -0
  76. package/js/imageFallback.js +23 -0
  77. package/js/index.js +45 -0
  78. package/js/mergeStamp.js +194 -0
  79. package/js/pageNumbering.js +48 -0
  80. package/js/qrEnc.js +721 -0
  81. package/js/standardPageSizes.js +56 -0
  82. package/js/tableLayouts.js +98 -0
  83. package/js/thai.js +201 -0
  84. package/js/virtual-fs.js +82 -0
  85. package/package.json +93 -4
  86. package/skills/w-pdfmaker/SKILL.md +171 -0
  87. package/skills/w-pdfmaker/references/browser.md +36 -0
  88. package/skills/w-pdfmaker/references/document-definition.md +241 -0
  89. package/skills/w-pdfmaker/references/images.md +90 -0
  90. package/skills/w-pdfmaker/references/merge-stamp.md +94 -0
  91. package/skills/w-pdfmaker/references/thai.md +67 -0
  92. package/src/DocMeasure.js +780 -0
  93. package/src/DocPreprocessor.js +293 -0
  94. package/src/DocumentContext.js +605 -0
  95. package/src/ElementWriter.js +550 -0
  96. package/src/LayoutBuilder.js +1689 -0
  97. package/src/Line.js +114 -0
  98. package/src/OutputDocument.js +75 -0
  99. package/src/OutputDocumentServer.js +38 -0
  100. package/src/PDFDocument.js +352 -0
  101. package/src/PageElementWriter.js +343 -0
  102. package/src/PageSize.js +53 -0
  103. package/src/Printer.js +289 -0
  104. package/src/Renderer.js +468 -0
  105. package/src/SVGMeasure.js +109 -0
  106. package/src/StyleContextStack.js +208 -0
  107. package/src/TableProcessor.js +719 -0
  108. package/src/TextBreaker.js +166 -0
  109. package/src/TextDecorator.js +191 -0
  110. package/src/TextInlines.js +229 -0
  111. package/src/URLResolver.js +122 -0
  112. package/src/base.js +143 -0
  113. package/src/browser-extensions/OutputDocumentBrowser.js +80 -0
  114. package/src/browser-extensions/fonts/Roboto.js +27 -0
  115. package/src/browser-extensions/fonts/thai.js +23 -0
  116. package/src/browser-extensions/index.js +91 -0
  117. package/src/browser-extensions/pageUrls.js +67 -0
  118. package/src/browser-extensions/pdfMake.js +1 -0
  119. package/src/browser-extensions/standard-fonts/Courier.js +25 -0
  120. package/src/browser-extensions/standard-fonts/Helvetica.js +25 -0
  121. package/src/browser-extensions/standard-fonts/Symbol.js +17 -0
  122. package/src/browser-extensions/standard-fonts/Times.js +25 -0
  123. package/src/browser-extensions/standard-fonts/ZapfDingbats.js +17 -0
  124. package/src/browser-extensions/virtual-fs-cjs.js +1 -0
  125. package/src/columnCalculator.js +160 -0
  126. package/src/helpers/node.js +134 -0
  127. package/src/helpers/tools.js +44 -0
  128. package/src/helpers/variableType.js +50 -0
  129. package/src/imageFallback.js +18 -0
  130. package/src/index.js +45 -0
  131. package/src/mergeStamp.js +132 -0
  132. package/src/pageNumbering.js +45 -0
  133. package/src/qrEnc.js +796 -0
  134. package/src/standardPageSizes.js +52 -0
  135. package/src/tableLayouts.js +100 -0
  136. package/src/thai.js +170 -0
  137. package/src/virtual-fs.js +92 -0
  138. package/standard-fonts/Courier.js +8 -0
  139. package/standard-fonts/Helvetica.js +8 -0
  140. package/standard-fonts/Symbol.js +5 -0
  141. package/standard-fonts/Times.js +8 -0
  142. package/standard-fonts/ZapfDingbats.js +5 -0
@@ -0,0 +1,166 @@
1
+ import { isObject } from './helpers/variableType';
2
+ import StyleContextStack from './StyleContextStack';
3
+ import { lineBreaks } from './thai';
4
+
5
+ /**
6
+ * @param {string} text
7
+ * @param {boolean} noWrap
8
+ * @param {boolean} breakAll
9
+ * @returns {Array}
10
+ */
11
+ const splitWords = (text, noWrap, breakAll = false) => {
12
+ let words = [];
13
+ if (text === undefined || text === null) {
14
+ text = '';
15
+ } else {
16
+ text = String(text);
17
+ }
18
+
19
+ if (noWrap) {
20
+ words.push({ text: text });
21
+ return words;
22
+ }
23
+ if (breakAll) {
24
+ return Array.from(text.replace(/\r\n/g, '\n')).map(c => {
25
+ if(c.match(/^\n$|^\r$/)) { // new line
26
+ return { text: '', lineEnd: true };
27
+ }
28
+ return { text: c };
29
+ });
30
+ }
31
+
32
+ if (text.length === 0) {
33
+ words.push({ text: '' });
34
+ return words;
35
+ }
36
+
37
+ let last = 0;
38
+
39
+ for (let bk of lineBreaks(text)) {
40
+ let word = text.slice(last, bk.position);
41
+
42
+ if (bk.required || word.match(/\r?\n$|\r$/)) { // new line
43
+ word = word.replace(/\r?\n$|\r$/, '');
44
+ words.push({ text: word, lineEnd: true });
45
+ } else {
46
+ words.push({ text: word });
47
+ }
48
+
49
+ last = bk.position;
50
+ }
51
+
52
+ return words;
53
+ };
54
+
55
+ /**
56
+ * @param {Array} words
57
+ * @param {boolean} noWrap
58
+ * @returns {?string}
59
+ */
60
+ const getFirstWord = (words, noWrap) => {
61
+ let word = words[0];
62
+ if (word === undefined) {
63
+ return null;
64
+ }
65
+
66
+ if (noWrap) { // text was not wrapped, we need only first word
67
+ let tmpWords = splitWords(word.text, false);
68
+ if (tmpWords[0] === undefined) {
69
+ return null;
70
+ }
71
+ word = tmpWords[0];
72
+ }
73
+
74
+ return word.text;
75
+ };
76
+
77
+ /**
78
+ * @param {Array} words
79
+ * @param {boolean} noWrap
80
+ * @returns {?string}
81
+ */
82
+ const getLastWord = (words, noWrap) => {
83
+ let word = words[words.length - 1];
84
+ if (word === undefined) {
85
+ return null;
86
+ }
87
+
88
+ if (word.lineEnd) {
89
+ return null;
90
+ }
91
+
92
+ if (noWrap) { // text was not wrapped, we need only last word
93
+ let tmpWords = splitWords(word.text, false);
94
+ if (tmpWords[tmpWords.length - 1] === undefined) {
95
+ return null;
96
+ }
97
+ word = tmpWords[tmpWords.length - 1];
98
+ }
99
+
100
+ return word.text;
101
+ };
102
+
103
+ class TextBreaker {
104
+ /**
105
+ * @param {string|Array} texts
106
+ * @param {StyleContextStack} styleContextStack
107
+ * @returns {Array}
108
+ */
109
+ getBreaks(texts, styleContextStack) {
110
+ let results = [];
111
+
112
+ if (!Array.isArray(texts)) {
113
+ texts = [texts];
114
+ }
115
+
116
+ let lastWord = null;
117
+ for (let i = 0, l = texts.length; i < l; i++) {
118
+ let item = texts[i];
119
+ let style = null;
120
+ let words;
121
+ let breakAll = StyleContextStack.getStyleProperty(item || {}, styleContextStack, 'wordBreak', 'normal') === 'break-all';
122
+ let noWrap = StyleContextStack.getStyleProperty(item || {}, styleContextStack, 'noWrap', false);
123
+ if (isObject(item)) {
124
+ if (item._textRef && item._textRef._textNodeRef.text) {
125
+ item.text = item._textRef._textNodeRef.text;
126
+ }
127
+ words = splitWords(item.text, noWrap, breakAll);
128
+ style = StyleContextStack.copyStyle(item);
129
+ } else {
130
+ words = splitWords(item, noWrap, breakAll);
131
+ }
132
+
133
+ if (lastWord && words.length) {
134
+ let firstWord = getFirstWord(words, noWrap);
135
+
136
+ let wrapWords = splitWords(lastWord + firstWord, false);
137
+ if (wrapWords.length === 1) {
138
+ results[results.length - 1].noNewLine = true;
139
+ }
140
+ }
141
+
142
+ for (let i2 = 0, l2 = words.length; i2 < l2; i2++) {
143
+ let result = {
144
+ text: words[i2].text
145
+ };
146
+
147
+ if (words[i2].lineEnd) {
148
+ result.lineEnd = true;
149
+ }
150
+
151
+ StyleContextStack.copyStyle(style, result);
152
+
153
+ results.push(result);
154
+ }
155
+
156
+ lastWord = null;
157
+ if (i + 1 < l) {
158
+ lastWord = getLastWord(words, noWrap);
159
+ }
160
+ }
161
+
162
+ return results;
163
+ }
164
+ }
165
+
166
+ export default TextBreaker;
@@ -0,0 +1,191 @@
1
+ import { isNumber } from './helpers/variableType';
2
+
3
+ const groupDecorations = (line, pdfDocument) => {
4
+ let groups = [];
5
+ let currentGroup = null;
6
+ for (let i = 0, l = line.inlines.length; i < l; i++) {
7
+ let inline = line.inlines[i];
8
+ let decoration = inline.decoration;
9
+ if (!decoration) {
10
+ currentGroup = null;
11
+ continue;
12
+ }
13
+ if (!Array.isArray(decoration)) {
14
+ decoration = [decoration];
15
+ }
16
+ let color = pdfDocument.resolveColor(pdfDocument.resolveColor(inline.decorationColor, inline.color), 'black');
17
+ let style = inline.decorationStyle || 'solid';
18
+ let thickness = isNumber(inline.decorationThickness) ? inline.decorationThickness : null;
19
+ for (let ii = 0, ll = decoration.length; ii < ll; ii++) {
20
+ let decorationItem = decoration[ii];
21
+ if (!currentGroup || decorationItem !== currentGroup.decoration ||
22
+ style !== currentGroup.decorationStyle || color !== currentGroup.decorationColor ||
23
+ thickness !== currentGroup.decorationThickness) {
24
+
25
+ currentGroup = {
26
+ line: line,
27
+ decoration: decorationItem,
28
+ decorationColor: color,
29
+ decorationStyle: style,
30
+ decorationThickness: thickness,
31
+ inlines: [inline]
32
+ };
33
+ groups.push(currentGroup);
34
+ } else {
35
+ currentGroup.inlines.push(inline);
36
+ }
37
+ }
38
+ }
39
+
40
+ return groups;
41
+ };
42
+
43
+ class TextDecorator {
44
+
45
+ constructor(pdfDocument) {
46
+ this.pdfDocument = pdfDocument;
47
+ }
48
+
49
+ drawBackground(line, x, y) {
50
+ let height = line.getHeight();
51
+ for (let i = 0, l = line.inlines.length; i < l; i++) {
52
+ let inline = line.inlines[i];
53
+
54
+ let color = this.pdfDocument.resolveColor(inline.background, undefined);
55
+ if (!color) {
56
+ continue;
57
+ }
58
+
59
+ let patternColor = this.pdfDocument.providePattern(inline.background);
60
+ if (patternColor !== null) {
61
+ color = patternColor;
62
+ }
63
+
64
+ let justifyShift = (inline.justifyShift || 0);
65
+ let rectX = x + inline.x - justifyShift;
66
+ let rectWidth = inline.width + justifyShift;
67
+
68
+ let lineStart = x + Math.min(0, line.inlines[0].leadingIndent || 0);
69
+ if (line.leadingCut > 0 && rectX < lineStart) {
70
+ // Clip the background of trimmed whitespace at the line start,
71
+ // keeping any negative leading indent used by the visible text.
72
+ rectWidth = rectX + rectWidth - lineStart;
73
+ rectX = lineStart;
74
+ if (rectWidth <= 0) {
75
+ continue;
76
+ }
77
+ }
78
+
79
+ this.pdfDocument.fillColor(color)
80
+ .rect(rectX, y, rectWidth, height)
81
+ .fill();
82
+ }
83
+ }
84
+
85
+ drawDecorations(line, x, y) {
86
+ let groups = groupDecorations(line, this.pdfDocument);
87
+ for (let i = 0, l = groups.length; i < l; i++) {
88
+ this._drawDecoration(groups[i], x, y);
89
+ }
90
+ }
91
+
92
+ _drawDecoration(group, x, y) {
93
+ const maxInline = () => {
94
+ let max = 0;
95
+ for (let i = 0, l = group.inlines.length; i < l; i++) {
96
+ let inline = group.inlines[i];
97
+ max = inline.fontSize > group.inlines[max].fontSize ? i : max;
98
+ }
99
+ return group.inlines[max];
100
+ };
101
+
102
+ const width = () => {
103
+ let sum = 0;
104
+ for (let i = 0, l = group.inlines.length; i < l; i++) {
105
+ let justifyShift = (group.inlines[i].justifyShift || 0);
106
+ sum += group.inlines[i].width + justifyShift;
107
+ }
108
+ return sum;
109
+ };
110
+
111
+ let firstInline = group.inlines[0];
112
+ let biggerInline = maxInline();
113
+ let totalWidth = width();
114
+ let lineAscent = group.line.getAscenderHeight();
115
+ let ascent = biggerInline.font.ascender / 1000 * biggerInline.fontSize;
116
+ let height = biggerInline.height;
117
+ let descent = height - ascent;
118
+
119
+ let lw = isNumber(group.decorationThickness)
120
+ ? group.decorationThickness
121
+ : 0.5 + Math.floor(Math.max(biggerInline.fontSize - 8, 0) / 2) * 0.12;
122
+
123
+ switch (group.decoration) {
124
+ case 'underline':
125
+ y += lineAscent + descent * 0.45;
126
+ break;
127
+ case 'overline':
128
+ y += lineAscent - (ascent * 0.85);
129
+ break;
130
+ case 'lineThrough':
131
+ y += lineAscent - (ascent * 0.25);
132
+ break;
133
+ default:
134
+ throw new Error(`Unknown decoration : ${group.decoration}`);
135
+ }
136
+
137
+ if (group.inlines[0].sup) {
138
+ y -= group.inlines[0].fontSize * 0.75;
139
+ }
140
+ if (group.inlines[0].sub) {
141
+ y += group.inlines[0].fontSize * 0.35;
142
+ }
143
+
144
+ this.pdfDocument.save();
145
+
146
+ if (group.decorationStyle === 'double') {
147
+ let gap = Math.max(0.5, lw, biggerInline.fontSize * 0.15);
148
+ this.pdfDocument.fillColor(group.decorationColor)
149
+ .rect(x + firstInline.x, y - lw / 2, totalWidth, lw / 2).fill()
150
+ .rect(x + firstInline.x, y + gap - lw / 2, totalWidth, lw / 2).fill();
151
+ } else if (group.decorationStyle === 'dashed') {
152
+ let nbDashes = Math.ceil(totalWidth / (3.96 + 2.84));
153
+ let rdx = x + firstInline.x;
154
+ this.pdfDocument.rect(rdx, y, totalWidth, lw).clip();
155
+ this.pdfDocument.fillColor(group.decorationColor);
156
+ for (let i = 0; i < nbDashes; i++) {
157
+ this.pdfDocument.rect(rdx, y - lw / 2, 3.96, lw).fill();
158
+ rdx += 3.96 + 2.84;
159
+ }
160
+ } else if (group.decorationStyle === 'dotted') {
161
+ let nbDots = Math.ceil(totalWidth / (lw * 3));
162
+ let rx = x + firstInline.x;
163
+ this.pdfDocument.rect(rx, y, totalWidth, lw).clip();
164
+ this.pdfDocument.fillColor(group.decorationColor);
165
+ for (let i = 0; i < nbDots; i++) {
166
+ this.pdfDocument.rect(rx, y - lw / 2, lw, lw).fill();
167
+ rx += (lw * 3);
168
+ }
169
+ } else if (group.decorationStyle === 'wavy') {
170
+ let sh = 0.7, sv = 1;
171
+ let nbWaves = Math.ceil(totalWidth / (sh * 2)) + 1;
172
+ let rwx = x + firstInline.x - 1;
173
+ this.pdfDocument.rect(x + firstInline.x, y - sv, totalWidth, 2 * sv).clip();
174
+ this.pdfDocument.lineWidth(lw / 3);
175
+ this.pdfDocument.moveTo(rwx, y);
176
+ for (let i = 0; i < nbWaves; i++) {
177
+ this.pdfDocument.bezierCurveTo(rwx + sh, y - sv, rwx + sh * 2, y - sv, rwx + sh * 3, y)
178
+ .bezierCurveTo(rwx + sh * 4, y + sv, rwx + sh * 5, y + sv, rwx + sh * 6, y);
179
+ rwx += sh * 6;
180
+ }
181
+ this.pdfDocument.stroke(group.decorationColor);
182
+ } else {
183
+ this.pdfDocument.fillColor(group.decorationColor)
184
+ .rect(x + firstInline.x, y - lw / 2, totalWidth, lw)
185
+ .fill();
186
+ }
187
+ this.pdfDocument.restore();
188
+ }
189
+ }
190
+
191
+ export default TextDecorator;
@@ -0,0 +1,229 @@
1
+ import TextBreaker from './TextBreaker';
2
+ import StyleContextStack from './StyleContextStack';
3
+
4
+ const LEADING = /^(\s)+/g;
5
+ const TRAILING = /(\s)+$/g;
6
+
7
+ /**
8
+ * @param {Array} array
9
+ * @returns {Array}
10
+ */
11
+ const flattenTextArray = array => {
12
+ function flatten(array) {
13
+ return array.reduce((prev, cur) => {
14
+ let current = Array.isArray(cur.text) ? flatten(cur.text) : cur;
15
+ let more = [].concat(current).some(Array.isArray);
16
+ return prev.concat(more ? flatten(current) : current);
17
+ }, []);
18
+ }
19
+
20
+ if (!Array.isArray(array)) {
21
+ array = [array];
22
+ }
23
+
24
+ // TODO: Styling in nested text (issue: https://github.com/bpampuch/pdfmake/issues/1174)
25
+
26
+ array = flatten(array);
27
+
28
+ return array;
29
+ };
30
+
31
+
32
+ /**
33
+ * Text measurement utility
34
+ */
35
+ class TextInlines {
36
+
37
+ /**
38
+ * @param {object} pdfDocument object is instance of PDFDocument
39
+ */
40
+ constructor(pdfDocument) {
41
+ this.pdfDocument = pdfDocument;
42
+ }
43
+
44
+ /**
45
+ * Converts an array of strings (or inline-definition-objects) into a collection
46
+ * of inlines and calculated minWidth/maxWidth and their min/max widths
47
+ *
48
+ * @param {Array|object} textArray an array of inline-definition-objects (or strings)
49
+ * @param {StyleContextStack} styleContextStack current style stack
50
+ * @returns {object} collection of inlines, minWidth, maxWidth
51
+ */
52
+ buildInlines(textArray, styleContextStack) {
53
+ const getTrimmedWidth = item => {
54
+ return Math.max(0, item.width - item.leadingCut - item.trailingCut);
55
+ };
56
+
57
+ let minWidth = 0;
58
+ let maxWidth = 0;
59
+ let currentLineWidth;
60
+
61
+ let flattenedTextArray = flattenTextArray(textArray);
62
+
63
+ const textBreaker = new TextBreaker();
64
+ let brokenText = textBreaker.getBreaks(flattenedTextArray, styleContextStack);
65
+
66
+ let measuredText = this.measure(brokenText, styleContextStack);
67
+
68
+ measuredText.forEach(inline => {
69
+ minWidth = Math.max(minWidth, getTrimmedWidth(inline));
70
+
71
+ if (!currentLineWidth) {
72
+ currentLineWidth = { width: 0, leadingCut: inline.leadingCut, trailingCut: 0 };
73
+ }
74
+
75
+ currentLineWidth.width += inline.width;
76
+ currentLineWidth.trailingCut = inline.trailingCut;
77
+
78
+ maxWidth = Math.max(maxWidth, getTrimmedWidth(currentLineWidth));
79
+
80
+ if (inline.lineEnd) {
81
+ currentLineWidth = null;
82
+ }
83
+ });
84
+
85
+ if (StyleContextStack.getStyleProperty({}, styleContextStack, 'noWrap', false)) {
86
+ minWidth = maxWidth;
87
+ }
88
+
89
+ return {
90
+ items: measuredText,
91
+ minWidth: minWidth,
92
+ maxWidth: maxWidth
93
+ };
94
+ }
95
+
96
+ measure(array, styleContextStack) {
97
+ if (array.length) {
98
+ let leadingIndent = StyleContextStack.getStyleProperty(array[0], styleContextStack, 'leadingIndent', 0);
99
+ if (leadingIndent) {
100
+ array[0].leadingCut = -leadingIndent;
101
+ array[0].leadingIndent = leadingIndent;
102
+ }
103
+ }
104
+
105
+ array.forEach(item => {
106
+ let font = StyleContextStack.getStyleProperty(item, styleContextStack, 'font', 'Roboto');
107
+ let bold = StyleContextStack.getStyleProperty(item, styleContextStack, 'bold', false);
108
+ let italics = StyleContextStack.getStyleProperty(item, styleContextStack, 'italics', false);
109
+
110
+ item.font = this.pdfDocument.provideFont(font, bold, italics);
111
+
112
+ item.alignment = StyleContextStack.getStyleProperty(item, styleContextStack, 'alignment', 'left');
113
+ item.fontSize = StyleContextStack.getStyleProperty(item, styleContextStack, 'fontSize', 12);
114
+ item.fontFeatures = StyleContextStack.getStyleProperty(item, styleContextStack, 'fontFeatures', null);
115
+ item.characterSpacing = StyleContextStack.getStyleProperty(item, styleContextStack, 'characterSpacing', 0);
116
+ item.color = StyleContextStack.getStyleProperty(item, styleContextStack, 'color', 'black');
117
+ item.decoration = StyleContextStack.getStyleProperty(item, styleContextStack, 'decoration', null);
118
+ item.decorationColor = StyleContextStack.getStyleProperty(item, styleContextStack, 'decorationColor', null);
119
+ item.decorationStyle = StyleContextStack.getStyleProperty(item, styleContextStack, 'decorationStyle', null);
120
+ item.decorationThickness = StyleContextStack.getStyleProperty(item, styleContextStack, 'decorationThickness', null);
121
+ item.background = StyleContextStack.getStyleProperty(item, styleContextStack, 'background', null);
122
+ item.link = StyleContextStack.getStyleProperty(item, styleContextStack, 'link', null);
123
+ item.linkToPage = StyleContextStack.getStyleProperty(item, styleContextStack, 'linkToPage', null);
124
+ item.linkToDestination = StyleContextStack.getStyleProperty(item, styleContextStack, 'linkToDestination', null);
125
+ item.noWrap = StyleContextStack.getStyleProperty(item, styleContextStack, 'noWrap', null);
126
+ item.opacity = StyleContextStack.getStyleProperty(item, styleContextStack, 'opacity', 1);
127
+ item.sup = StyleContextStack.getStyleProperty(item, styleContextStack, 'sup', false);
128
+ item.sub = StyleContextStack.getStyleProperty(item, styleContextStack, 'sub', false);
129
+
130
+ if (item.sup || item.sub) {
131
+ // font size reduction taken from here: https://en.wikipedia.org/wiki/Subscript_and_superscript#Desktop_publishing
132
+ item.fontSize *= 0.58;
133
+ }
134
+
135
+ let lineHeight = StyleContextStack.getStyleProperty(item, styleContextStack, 'lineHeight', 1);
136
+
137
+ item.width = this.widthOfText(item.text, item);
138
+ item.height = item.font.lineHeight(item.fontSize) * lineHeight;
139
+
140
+ if (!item.leadingCut) {
141
+ item.leadingCut = 0;
142
+ }
143
+
144
+ let preserveLeadingSpaces = StyleContextStack.getStyleProperty(item, styleContextStack, 'preserveLeadingSpaces', false);
145
+ if (!preserveLeadingSpaces) {
146
+ let leadingSpaces = item.text.match(LEADING);
147
+ if (leadingSpaces) {
148
+ item.leadingCut += this.widthOfText(leadingSpaces[0], item);
149
+ }
150
+ }
151
+
152
+ item.trailingCut = 0;
153
+
154
+ let preserveTrailingSpaces = StyleContextStack.getStyleProperty(item, styleContextStack, 'preserveTrailingSpaces', false);
155
+ if (!preserveTrailingSpaces) {
156
+ let trailingSpaces = item.text.match(TRAILING);
157
+ if (trailingSpaces) {
158
+ item.trailingCut = this.widthOfText(trailingSpaces[0], item);
159
+ }
160
+ }
161
+ }, this);
162
+
163
+ return array;
164
+ }
165
+
166
+ /**
167
+ * Width of text
168
+ *
169
+ * @param {string} text
170
+ * @param {object} inline
171
+ * @returns {number}
172
+ */
173
+ widthOfText(text, inline) {
174
+ let width = inline.font.widthOfString(text, inline.fontSize, inline.fontFeatures);
175
+ if (inline.characterSpacing) {
176
+ // Include spacing after the last character to keep adjacent inlines spaced.
177
+ width += inline.characterSpacing * Array.from(text).length;
178
+ }
179
+ return width;
180
+ }
181
+
182
+ /**
183
+ * Returns size of the specified string (without breaking it) using the current style
184
+ *
185
+ * @param {string} text text to be measured
186
+ * @param {object} styleContextStack current style stack
187
+ * @returns {object} size of the specified string
188
+ */
189
+ sizeOfText(text, styleContextStack) {
190
+ //TODO: refactor - extract from measure
191
+ let fontName = StyleContextStack.getStyleProperty({}, styleContextStack, 'font', 'Roboto');
192
+ let fontSize = StyleContextStack.getStyleProperty({}, styleContextStack, 'fontSize', 12);
193
+ let fontFeatures = StyleContextStack.getStyleProperty({}, styleContextStack, 'fontFeatures', null);
194
+ let bold = StyleContextStack.getStyleProperty({}, styleContextStack, 'bold', false);
195
+ let italics = StyleContextStack.getStyleProperty({}, styleContextStack, 'italics', false);
196
+ let lineHeight = StyleContextStack.getStyleProperty({}, styleContextStack, 'lineHeight', 1);
197
+ let characterSpacing = StyleContextStack.getStyleProperty({}, styleContextStack, 'characterSpacing', 0);
198
+
199
+ let font = this.pdfDocument.provideFont(fontName, bold, italics);
200
+
201
+ return {
202
+ width: this.widthOfText(text, { font: font, fontSize: fontSize, characterSpacing: characterSpacing, fontFeatures: fontFeatures }),
203
+ height: font.lineHeight(fontSize) * lineHeight,
204
+ fontSize: fontSize,
205
+ lineHeight: lineHeight,
206
+ ascender: font.ascender / 1000 * fontSize,
207
+ descender: font.descender / 1000 * fontSize
208
+ };
209
+ }
210
+
211
+ /**
212
+ * Returns size of the specified rotated string (without breaking it) using the current style
213
+ *
214
+ * @param {string} text text to be measured
215
+ * @param {number} angle
216
+ * @param {object} styleContextStack current style stack
217
+ * @returns {object} size of the specified string
218
+ */
219
+ sizeOfRotatedText(text, angle, styleContextStack) {
220
+ let angleRad = angle * Math.PI / -180;
221
+ let size = this.sizeOfText(text, styleContextStack);
222
+ return {
223
+ width: Math.abs(size.height * Math.sin(angleRad)) + Math.abs(size.width * Math.cos(angleRad)),
224
+ height: Math.abs(size.width * Math.sin(angleRad)) + Math.abs(size.height * Math.cos(angleRad))
225
+ };
226
+ }
227
+ }
228
+
229
+ export default TextInlines;
@@ -0,0 +1,122 @@
1
+
2
+ const MAX_REDIRECTS = 30;
3
+
4
+ /**
5
+ * @param {string} url
6
+ * @param {object} headers
7
+ * @param {(url: string) => boolean} urlAccessPolicy
8
+ * @returns {Promise<Response>}
9
+ */
10
+ export async function fetchUrl(url, headers = {}, urlAccessPolicy) {
11
+ for (let i = 0; i <= MAX_REDIRECTS; i++) {
12
+ if ((typeof urlAccessPolicy !== 'undefined') && (urlAccessPolicy(url) !== true)) {
13
+ throw new Error(`Access to URL denied by resource access policy: ${url}`);
14
+ }
15
+
16
+ try {
17
+ let response = await fetch(url, { headers, redirect: 'manual' });
18
+
19
+ // redirect url
20
+ if (response.status >= 300 && response.status < 400) {
21
+ let location = response.headers.get('location');
22
+ if (!location) {
23
+ throw new Error('Redirect response missing Location header');
24
+ }
25
+ url = new URL(location, url).href;
26
+ continue;
27
+ }
28
+
29
+ // browsers do not support redirect: 'manual'
30
+ if (response.type === 'opaqueredirect') {
31
+ response = await fetch(url, {headers});
32
+ }
33
+
34
+ if (!response.ok) {
35
+ throw new Error(`Failed to fetch (status code: ${response.status})`);
36
+ }
37
+
38
+ return response;
39
+
40
+ } catch (error) {
41
+ // w-pdfmaker: code ENOENT marks a resource that could not be downloaded (see imageFallback.js)
42
+ throw Object.assign(new Error(`Network request failed (url: "${url}", error: ${error.message})`, {cause: error}), { code: 'ENOENT' });
43
+ }
44
+ }
45
+
46
+ throw new Error(`Network request failed (url: "${url}", error: Too many redirects)`);
47
+ }
48
+
49
+ class URLResolver {
50
+ constructor(fs, sharedFs) {
51
+ this.fs = fs;
52
+ this.sharedFs = sharedFs;
53
+ this.resolving = {};
54
+ this.urlAccessPolicy = undefined;
55
+ this.errors = new Map(); // w-pdfmaker: url => failed download held back by resolve(…, holdNotFound)
56
+ }
57
+
58
+ /**
59
+ * @param {(url: string) => boolean} callback
60
+ */
61
+ setUrlAccessPolicy(callback) {
62
+ this.urlAccessPolicy = callback;
63
+ }
64
+
65
+ /**
66
+ * @param {string} url
67
+ * @param {object} headers
68
+ * @param {boolean} cache
69
+ * @param {boolean} holdNotFound w-pdfmaker: a failed download is kept in this.errors instead of rejecting,
70
+ * and thrown when the resource is used (images; `fallback` can then replace it)
71
+ * @returns {Promise}
72
+ */
73
+ resolve(url, headers = {}, cache = false, holdNotFound = false) {
74
+ if (typeof url !== 'string') {
75
+ return Promise.resolve();
76
+ }
77
+
78
+ const key = JSON.stringify([url, cache === true, holdNotFound === true]);
79
+ const resolveUrlInternal = async () => {
80
+ if (url.toLowerCase().startsWith('https://') || url.toLowerCase().startsWith('http://')) {
81
+ if (this.fs.existsSync(url)) {
82
+ if ((cache === true) && !this.sharedFs.existsSync(url)) {
83
+ this.fs.unlinkSync(url);
84
+ } else {
85
+ return; // url was downloaded earlier
86
+ }
87
+ }
88
+
89
+ const response = await fetchUrl(url, headers, this.urlAccessPolicy);
90
+
91
+ // validate access policy on redirected url (in browsers, only the final URL is validated)
92
+ if (response.redirected) {
93
+ if ((typeof this.urlAccessPolicy !== 'undefined') && (this.urlAccessPolicy(response.url) !== true)) {
94
+ throw new Error(`Access to URL denied by resource access policy: ${response.url}`);
95
+ }
96
+ }
97
+
98
+ const buffer = await response.arrayBuffer();
99
+ const target = cache === true ? this.sharedFs : this.fs;
100
+ target.writeFileSync(url, buffer);
101
+ }
102
+ // else cannot be resolved
103
+ };
104
+
105
+ if (!this.resolving[key]) {
106
+ this.resolving[key] = holdNotFound !== true ? resolveUrlInternal() : resolveUrlInternal().catch(error => {
107
+ if (error.code !== 'ENOENT') {
108
+ throw error; // access policy denials stay immediate
109
+ }
110
+ this.errors.set(url, error);
111
+ });
112
+ }
113
+ return this.resolving[key];
114
+ }
115
+
116
+ resolved() {
117
+ return Promise.all(Object.values(this.resolving));
118
+ }
119
+
120
+ }
121
+
122
+ export default URLResolver;