@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,159 @@
1
+ "use strict";
2
+
3
+ exports.__esModule = true;
4
+ exports.default = void 0;
5
+ var _variableType = require("./helpers/variableType");
6
+ function buildColumnWidths(columns, availableWidth, offsetTotal = 0, tableNode) {
7
+ let autoColumns = [];
8
+ let autoMin = 0;
9
+ let autoMax = 0;
10
+ let starColumns = [];
11
+ let starMaxMin = 0;
12
+ let starMaxMax = 0;
13
+ let fixedColumns = [];
14
+ let initial_availableWidth = availableWidth;
15
+ columns.forEach((column, colIndex) => {
16
+ if (isAutoColumn(column)) {
17
+ autoColumns.push(column);
18
+ autoMin += column._minWidth;
19
+ autoMax += column._maxWidth;
20
+ } else if (isStarColumn(column)) {
21
+ starColumns.push(column);
22
+ starMaxMin = Math.max(starMaxMin, column._minWidth);
23
+ starMaxMax = Math.max(starMaxMax, column._maxWidth);
24
+ } else {
25
+ fixedColumns.push({
26
+ column,
27
+ colIndex
28
+ });
29
+ }
30
+ });
31
+ fixedColumns.forEach(({
32
+ column: col,
33
+ colIndex
34
+ }) => {
35
+ let width = col.width;
36
+ // width specified as %
37
+ if (isPercentageColumn(col)) {
38
+ // In tables we have to take into consideration the reserved width for paddings and borders
39
+ let reservedWidth = 0;
40
+ if (tableNode) {
41
+ const paddingLeft = tableNode._layout.paddingLeft(colIndex, tableNode);
42
+ const paddingRight = tableNode._layout.paddingRight(colIndex, tableNode);
43
+ const borderLeft = tableNode._layout.vLineWidth(colIndex, tableNode);
44
+ const borderRight = tableNode._layout.vLineWidth(colIndex + 1, tableNode);
45
+ if (colIndex === 0) {
46
+ // first column assumes whole borderLeft and half of border right
47
+ reservedWidth = paddingLeft + paddingRight + borderLeft + borderRight / 2;
48
+ } else if (colIndex === columns.length - 1) {
49
+ // last column assumes whole borderRight and half of border left
50
+ reservedWidth = paddingLeft + paddingRight + borderLeft / 2 + borderRight;
51
+ } else {
52
+ // Columns in the middle assume half of each border
53
+ reservedWidth = paddingLeft + paddingRight + borderLeft / 2 + borderRight / 2;
54
+ }
55
+ }
56
+ const totalAvailableWidth = initial_availableWidth + offsetTotal;
57
+ width = parseFloat(col.width) * totalAvailableWidth / 100 - reservedWidth;
58
+ }
59
+ if (width < col._minWidth && col.elasticWidth) {
60
+ col._calcWidth = col._minWidth;
61
+ } else {
62
+ col._calcWidth = width;
63
+ }
64
+ availableWidth -= col._calcWidth;
65
+ });
66
+
67
+ // http://www.freesoft.org/CIE/RFC/1942/18.htm
68
+ // http://www.w3.org/TR/CSS2/tables.html#width-layout
69
+ // http://dev.w3.org/csswg/css3-tables-algorithms/Overview.src.htm
70
+ let minW = autoMin + starMaxMin * starColumns.length;
71
+ let maxW = autoMax + starMaxMax * starColumns.length;
72
+ if (minW >= availableWidth) {
73
+ // case 1 - there's no way to fit all columns within available width
74
+ // that's actually pretty bad situation with PDF as we have no horizontal scroll
75
+ // no easy workaround (unless we decide, in the future, to split single words)
76
+ // currently we simply use minWidths for all columns
77
+ autoColumns.forEach(col => {
78
+ col._calcWidth = col._minWidth;
79
+ });
80
+ starColumns.forEach(col => {
81
+ col._calcWidth = starMaxMin; // starMaxMin already contains padding
82
+ });
83
+ } else {
84
+ if (maxW < availableWidth) {
85
+ // case 2 - we can fit rest of the table within available space
86
+ autoColumns.forEach(col => {
87
+ col._calcWidth = col._maxWidth;
88
+ availableWidth -= col._calcWidth;
89
+ });
90
+ } else {
91
+ // maxW is too large, but minW fits within available width
92
+ let W = availableWidth - minW;
93
+ let D = maxW - minW;
94
+ autoColumns.forEach(col => {
95
+ let d = col._maxWidth - col._minWidth;
96
+ col._calcWidth = col._minWidth + d * W / D;
97
+ availableWidth -= col._calcWidth;
98
+ });
99
+ }
100
+ if (starColumns.length > 0) {
101
+ let starSize = availableWidth / starColumns.length;
102
+ starColumns.forEach(col => {
103
+ col._calcWidth = starSize;
104
+ });
105
+ }
106
+ }
107
+ }
108
+ function isAutoColumn(column) {
109
+ return column.width === 'auto';
110
+ }
111
+ function isStarColumn(column) {
112
+ return column.width === null || column.width === undefined || column.width === '*' || column.width === 'star';
113
+ }
114
+ function isPercentageColumn(column) {
115
+ return (0, _variableType.isString)(column.width) && /\d+%/.test(column.width);
116
+ }
117
+
118
+ //TODO: refactor and reuse in measureTable
119
+ function measureMinMax(columns) {
120
+ let result = {
121
+ min: 0,
122
+ max: 0
123
+ };
124
+ let maxStar = {
125
+ min: 0,
126
+ max: 0
127
+ };
128
+ let starCount = 0;
129
+ for (let i = 0, l = columns.length; i < l; i++) {
130
+ let c = columns[i];
131
+ if (isStarColumn(c)) {
132
+ maxStar.min = Math.max(maxStar.min, c._minWidth);
133
+ maxStar.max = Math.max(maxStar.max, c._maxWidth);
134
+ starCount++;
135
+ } else if (isAutoColumn(c) || isPercentageColumn(c)) {
136
+ result.min += c._minWidth;
137
+ result.max += c._maxWidth;
138
+ } else {
139
+ result.min += c.width !== undefined && c.width || c._minWidth;
140
+ result.max += c.width !== undefined && c.width || c._maxWidth;
141
+ }
142
+ }
143
+ if (starCount) {
144
+ result.min += starCount * maxStar.min;
145
+ result.max += starCount * maxStar.max;
146
+ }
147
+ return result;
148
+ }
149
+
150
+ /**
151
+ * Calculates column widths
152
+ */
153
+ var _default = exports.default = {
154
+ buildColumnWidths: buildColumnWidths,
155
+ measureMinMax: measureMinMax,
156
+ isAutoColumn: isAutoColumn,
157
+ isStarColumn: isStarColumn,
158
+ isPercentageColumn: isPercentageColumn
159
+ };
@@ -0,0 +1,122 @@
1
+ "use strict";
2
+
3
+ exports.__esModule = true;
4
+ exports.getNodeId = getNodeId;
5
+ exports.getNodeMargin = getNodeMargin;
6
+ exports.stringifyNode = stringifyNode;
7
+ var _variableType = require("./variableType");
8
+ function fontStringify(key, val) {
9
+ if (key === 'font') {
10
+ return 'font';
11
+ }
12
+ return val;
13
+ }
14
+
15
+ /**
16
+ * Convert node to readable string
17
+ *
18
+ * @param {object} node
19
+ * @returns {string}
20
+ */
21
+ function stringifyNode(node) {
22
+ return JSON.stringify(node, fontStringify);
23
+ }
24
+
25
+ /**
26
+ * @param {object} node
27
+ * @returns {?string}
28
+ */
29
+ function getNodeId(node) {
30
+ if (node.id) {
31
+ return node.id;
32
+ }
33
+ if (Array.isArray(node.text)) {
34
+ for (let n of node.text) {
35
+ let nodeId = getNodeId(n);
36
+ if (nodeId) {
37
+ return nodeId;
38
+ }
39
+ }
40
+ }
41
+ return null;
42
+ }
43
+
44
+ /**
45
+ * @param {object} node
46
+ * @param {object} styleStack object is instance of PDFDocument
47
+ * @returns {?Array}
48
+ */
49
+ function getNodeMargin(node, styleStack) {
50
+ function processSingleMargins(node, currentMargin, defaultMargin = 0) {
51
+ if (node.marginLeft !== undefined || node.marginTop !== undefined || node.marginRight !== undefined || node.marginBottom !== undefined) {
52
+ return [node.marginLeft ?? currentMargin[0] ?? defaultMargin, node.marginTop ?? currentMargin[1] ?? defaultMargin, node.marginRight ?? currentMargin[2] ?? defaultMargin, node.marginBottom ?? currentMargin[3] ?? defaultMargin];
53
+ }
54
+ return currentMargin;
55
+ }
56
+ function flattenStyleArray(styleArray, styleStack, visited = new Set()) {
57
+ styleArray = Array.isArray(styleArray) ? styleArray : [styleArray];
58
+
59
+ // style is not valid array of strings
60
+ if (!styleArray.every(item => (0, _variableType.isString)(item))) {
61
+ return {};
62
+ }
63
+ let flattenedStyles = {};
64
+ for (let index = 0; index < styleArray.length; index++) {
65
+ let styleName = styleArray[index];
66
+ let style = styleStack.styleDictionary[styleName];
67
+
68
+ // style not found
69
+ if (style === undefined) {
70
+ continue;
71
+ }
72
+ if (visited.has(styleName)) {
73
+ continue;
74
+ }
75
+ if (style.extends !== undefined) {
76
+ flattenedStyles = {
77
+ ...flattenedStyles,
78
+ ...flattenStyleArray(style.extends, styleStack, new Set([...visited, styleName]))
79
+ };
80
+ }
81
+ if (style.margin !== undefined) {
82
+ flattenedStyles = {
83
+ margin: convertMargin(style.margin)
84
+ };
85
+ continue;
86
+ }
87
+ flattenedStyles = {
88
+ margin: processSingleMargins(style, flattenedStyles.margin ?? {}, undefined)
89
+ };
90
+ }
91
+ return flattenedStyles;
92
+ }
93
+ function convertMargin(margin) {
94
+ if ((0, _variableType.isNumber)(margin)) {
95
+ margin = [margin, margin, margin, margin];
96
+ } else if (Array.isArray(margin)) {
97
+ if (margin.length === 2) {
98
+ margin = [margin[0], margin[1], margin[0], margin[1]];
99
+ }
100
+ }
101
+ return margin;
102
+ }
103
+ let margin = [undefined, undefined, undefined, undefined];
104
+ if (node.style) {
105
+ let styleArray = Array.isArray(node.style) ? node.style : [node.style];
106
+ let flattenedStyleArray = flattenStyleArray(styleArray, styleStack);
107
+ if (flattenedStyleArray) {
108
+ margin = processSingleMargins(flattenedStyleArray, margin);
109
+ }
110
+ if (flattenedStyleArray.margin) {
111
+ margin = convertMargin(flattenedStyleArray.margin);
112
+ }
113
+ }
114
+ margin = processSingleMargins(node, margin);
115
+ if (node.margin !== undefined) {
116
+ margin = convertMargin(node.margin);
117
+ }
118
+ if (margin[0] === undefined && margin[1] === undefined && margin[2] === undefined && margin[3] === undefined) {
119
+ return null;
120
+ }
121
+ return margin;
122
+ }
@@ -0,0 +1,46 @@
1
+ "use strict";
2
+
3
+ exports.__esModule = true;
4
+ exports.convertToDynamicContent = convertToDynamicContent;
5
+ exports.offsetVector = offsetVector;
6
+ exports.pack = pack;
7
+ function pack(...args) {
8
+ let result = {};
9
+ for (let i = 0, l = args.length; i < l; i++) {
10
+ let obj = args[i];
11
+ if (obj) {
12
+ for (let key in obj) {
13
+ if (obj.hasOwnProperty(key)) {
14
+ result[key] = obj[key];
15
+ }
16
+ }
17
+ }
18
+ }
19
+ return result;
20
+ }
21
+ function offsetVector(vector, x, y) {
22
+ switch (vector.type) {
23
+ case 'ellipse':
24
+ case 'rect':
25
+ vector.x += x;
26
+ vector.y += y;
27
+ break;
28
+ case 'line':
29
+ vector.x1 += x;
30
+ vector.x2 += x;
31
+ vector.y1 += y;
32
+ vector.y2 += y;
33
+ break;
34
+ case 'polyline':
35
+ for (let i = 0, l = vector.points.length; i < l; i++) {
36
+ vector.points[i].x += x;
37
+ vector.points[i].y += y;
38
+ }
39
+ break;
40
+ }
41
+ }
42
+ function convertToDynamicContent(staticContent) {
43
+ return () =>
44
+ // copy to new object
45
+ JSON.parse(JSON.stringify(staticContent));
46
+ }
@@ -0,0 +1,59 @@
1
+ "use strict";
2
+
3
+ exports.__esModule = true;
4
+ exports.isEmptyObject = isEmptyObject;
5
+ exports.isNumber = isNumber;
6
+ exports.isObject = isObject;
7
+ exports.isPositiveInteger = isPositiveInteger;
8
+ exports.isString = isString;
9
+ exports.isValue = isValue;
10
+ /**
11
+ * @param {any} variable
12
+ * @returns {boolean}
13
+ */
14
+ function isString(variable) {
15
+ return typeof variable === 'string' || variable instanceof String;
16
+ }
17
+
18
+ /**
19
+ * @param {any} variable
20
+ * @returns {boolean}
21
+ */
22
+ function isNumber(variable) {
23
+ return (typeof variable === 'number' || variable instanceof Number) && !Number.isNaN(variable);
24
+ }
25
+
26
+ /**
27
+ * @param {any} variable
28
+ * @returns {boolean}
29
+ */
30
+ function isPositiveInteger(variable) {
31
+ if (!isNumber(variable) || !Number.isInteger(variable) || variable <= 0) {
32
+ return false;
33
+ }
34
+ return true;
35
+ }
36
+
37
+ /**
38
+ * @param {any} variable
39
+ * @returns {boolean}
40
+ */
41
+ function isObject(variable) {
42
+ return variable !== null && !Array.isArray(variable) && !isString(variable) && !isNumber(variable) && typeof variable === 'object';
43
+ }
44
+
45
+ /**
46
+ * @param {any} variable
47
+ * @returns {boolean}
48
+ */
49
+ function isEmptyObject(variable) {
50
+ return isObject(variable) && Object.keys(variable).length === 0;
51
+ }
52
+
53
+ /**
54
+ * @param {any} variable
55
+ * @returns {boolean}
56
+ */
57
+ function isValue(variable) {
58
+ return variable !== undefined && variable !== null;
59
+ }
@@ -0,0 +1,23 @@
1
+ "use strict";
2
+
3
+ exports.__esModule = true;
4
+ exports.isNotFound = exports.EMPTY_SVG = void 0;
5
+ // w-pdfmaker: `fallback: true` on an image or svg node draws nothing in its place (an empty SVG keeping the node's size)
6
+ // when its source is missing: no value, a missing file, or a failed download. Errors marked with code ENOENT
7
+ // (failed downloads are marked too) are "not found"; access policy denials and broken files are not.
8
+
9
+ const EMPTY_SVG = exports.EMPTY_SVG = '<svg xmlns="http://www.w3.org/2000/svg" width="1" height="1"></svg>';
10
+
11
+ /**
12
+ * @param {Error} error
13
+ * @returns {boolean}
14
+ */
15
+ const isNotFound = error => {
16
+ for (; error; error = error.cause) {
17
+ if (error.code === 'ENOENT') {
18
+ return true;
19
+ }
20
+ }
21
+ return false;
22
+ };
23
+ exports.isNotFound = isNotFound;
package/js/index.js ADDED
@@ -0,0 +1,45 @@
1
+ "use strict";
2
+
3
+ const fs = require('fs');
4
+ const path = require('path');
5
+ const pdfmakeBase = require('./base').default;
6
+ const OutputDocumentServer = require('./OutputDocumentServer').default;
7
+ const {
8
+ thaiFonts
9
+ } = require('./thai');
10
+ class pdfmake extends pdfmakeBase {
11
+ constructor() {
12
+ super();
13
+ // w-pdfmaker defaults: bundled Thai fonts, no server-side URL downloads (SSRF), local files allowed like 0.2
14
+ this.fonts = thaiFonts(path.join(__dirname, '../fonts/'));
15
+ this.urlAccessPolicy = () => false;
16
+ this.localAccessPolicy = () => true;
17
+ }
18
+
19
+ /**
20
+ * @param {(path: string) => boolean} callback
21
+ */
22
+ setLocalAccessPolicy(callback) {
23
+ if (callback !== undefined && typeof callback !== 'function') {
24
+ throw new Error("Parameter 'callback' has an invalid type. Function or undefined expected.");
25
+ }
26
+ this.localAccessPolicy = callback;
27
+ }
28
+
29
+ /**
30
+ * w-pdfmaker: reads a file passed by path to merge() / stamp().
31
+ *
32
+ * @param {string} path
33
+ * @returns {Promise<Buffer>}
34
+ */
35
+ async _readFile(path) {
36
+ if (typeof this.localAccessPolicy !== 'undefined' && this.localAccessPolicy(path) !== true) {
37
+ throw new Error(`Access to local file denied by resource access policy: ${path}`);
38
+ }
39
+ return fs.promises.readFile(path);
40
+ }
41
+ _transformToDocument(doc) {
42
+ return new OutputDocumentServer(doc);
43
+ }
44
+ }
45
+ module.exports = new pdfmake();
@@ -0,0 +1,194 @@
1
+ "use strict";
2
+
3
+ exports.__esModule = true;
4
+ exports.merge = merge;
5
+ exports.stamp = stamp;
6
+ var _pdfLib = require("@cantoo/pdf-lib");
7
+ // w-pdfmaker: merging pages and stamping existing PDFs. Only Buffers (or file paths) go in and Buffers come out;
8
+ // no pdf-lib objects are exposed.
9
+
10
+ // A string is a file path, read by readFile (pdf-lib itself would take a string as base64).
11
+ // Password '' opens PDFs locked with an owner password only (they open without a password). The output is not encrypted.
12
+ const load = async (pdf, readFile) => _pdfLib.PDFDocument.load(typeof pdf === 'string' ? await readFile(pdf) : pdf, {
13
+ password: ''
14
+ });
15
+ const save = async doc => Buffer.from(await doc.save());
16
+
17
+ /**
18
+ * Joins pages of PDFs in the given order.
19
+ *
20
+ * @param {Array<Buffer|Uint8Array|string|{pdf: Buffer|Uint8Array|string, from?: number, to?: number}>} parts a whole PDF,
21
+ * or pages from..to (numbered from 1, inclusive; a range past the last page is cut at the last page)
22
+ * @param {Function} readFile path => Promise<Buffer|Uint8Array>
23
+ * @returns {Promise<Buffer>}
24
+ */
25
+ async function merge(parts, readFile) {
26
+ if (!Array.isArray(parts)) {
27
+ throw new Error("Parameter 'parts' has an invalid type. Array expected.");
28
+ }
29
+ const sources = new Map();
30
+ const ranges = [];
31
+ for (const part of parts) {
32
+ const {
33
+ pdf,
34
+ from = 1,
35
+ to = Infinity
36
+ } = part && part.pdf ? part : {
37
+ pdf: part
38
+ };
39
+ if (!Number.isInteger(from) || from < 1 || !(to === Infinity || Number.isInteger(to) && to >= 1)) {
40
+ throw new Error('Page numbers in merge() must be whole numbers starting at 1.');
41
+ }
42
+ if (!sources.has(pdf)) {
43
+ sources.set(pdf, {
44
+ doc: await load(pdf, readFile),
45
+ indices: []
46
+ });
47
+ }
48
+ const source = sources.get(pdf);
49
+ const length = Math.max(Math.min(to, source.doc.getPageCount()) - from + 1, 0);
50
+ source.indices.push(...Array.from({
51
+ length
52
+ }, (_, i) => from - 1 + i));
53
+ ranges.push({
54
+ source,
55
+ length
56
+ });
57
+ }
58
+ if (!ranges.some(({
59
+ length
60
+ }) => length)) {
61
+ // pdf-lib would save an empty document with a blank page
62
+ throw new Error('merge() selected no pages.');
63
+ }
64
+ const out = await _pdfLib.PDFDocument.create();
65
+ // One copyPages per source: fonts and images of a PDF split around other parts are copied once.
66
+ for (const source of sources.values()) {
67
+ source.pages = await out.copyPages(source.doc, source.indices);
68
+ }
69
+ for (const {
70
+ source,
71
+ length
72
+ } of ranges) {
73
+ source.pages.splice(0, length).forEach(page => out.addPage(page));
74
+ }
75
+ return save(out);
76
+ }
77
+
78
+ // pdfmake writes layout state into content nodes, so a node used on several pages (e.g. one watermark object)
79
+ // renders only once. Content is copied per page; functions and binary data are kept as they are.
80
+ const copy = value => {
81
+ if (Array.isArray(value)) {
82
+ return value.map(copy);
83
+ }
84
+ if (value && Object.getPrototypeOf(value) === Object.prototype) {
85
+ return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, copy(item)]));
86
+ }
87
+ return value;
88
+ };
89
+
90
+ /**
91
+ * Draws pdfmake content over the pages of an existing PDF. pdfmake renders a transparent page per stamped page
92
+ * (same size, no margins), which is placed over the original page.
93
+ *
94
+ * @param {Buffer|Uint8Array|string} pdf
95
+ * @param {Function} fn ({ pageNumber, pageCount, width, height }) => pdfmake content, or null to leave the page as it is;
96
+ * width and height are the page as shown (rotated pages included), coordinates start at its top left corner
97
+ * @param {Function} render docDefinition => Promise<Buffer>
98
+ * @param {Function} readFile path => Promise<Buffer|Uint8Array>
99
+ * @returns {Promise<Buffer>}
100
+ */
101
+ async function stamp(pdf, fn, render, readFile) {
102
+ if (typeof fn !== 'function') {
103
+ throw new Error("Parameter 'fn' has an invalid type. Function expected.");
104
+ }
105
+ let doc = await load(pdf, readFile);
106
+ if (doc.context.isDecrypted) {
107
+ // A decrypted PDF keeps its old /Encrypt objects when saved, and pdf-lib (ours included) then refuses the
108
+ // unencrypted file as encrypted. Its pages are copied to a new document, like merge(); outlines and forms are lost.
109
+ const decrypted = doc;
110
+ doc = await _pdfLib.PDFDocument.create();
111
+ (await doc.copyPages(decrypted, decrypted.getPageIndices())).forEach(page => doc.addPage(page));
112
+ }
113
+ const pages = doc.getPages();
114
+ const stamps = [];
115
+ for (const [i, page] of pages.entries()) {
116
+ const box = page.getCropBox(); // the visible area
117
+ let rotation = (page.getRotation().angle % 360 + 360) % 360;
118
+ if (rotation % 90) {
119
+ rotation = 0; // like viewers, ignore an invalid /Rotate
120
+ }
121
+ const sideways = rotation === 90 || rotation === 270;
122
+ const width = sideways ? box.height : box.width;
123
+ const height = sideways ? box.width : box.height;
124
+ const content = await fn({
125
+ pageNumber: i + 1,
126
+ pageCount: pages.length,
127
+ width,
128
+ height
129
+ });
130
+ if (content !== null && content !== undefined) {
131
+ stamps.push({
132
+ page,
133
+ box,
134
+ rotation,
135
+ width,
136
+ height,
137
+ content
138
+ });
139
+ }
140
+ }
141
+ if (stamps.length) {
142
+ const overlay = await load(await render({
143
+ pageMargins: 0,
144
+ // One section (page) per stamp. The empty text gives every section an item, otherwise the section
145
+ // after a stamp that draws nothing would reuse its page.
146
+ content: stamps.map(({
147
+ width,
148
+ height,
149
+ content
150
+ }) => ({
151
+ section: [{
152
+ text: '',
153
+ absolutePosition: {
154
+ x: 0,
155
+ y: 0
156
+ }
157
+ }, copy(content)],
158
+ pageSize: {
159
+ width,
160
+ height
161
+ }
162
+ }))
163
+ }));
164
+ if (overlay.getPageCount() !== stamps.length) {
165
+ throw new Error('Content returned to stamp() must fit on its page.');
166
+ }
167
+ const embedded = await doc.embedPdf(overlay, stamps.map((_, i) => i));
168
+ stamps.forEach(({
169
+ page,
170
+ box: {
171
+ x,
172
+ y,
173
+ width,
174
+ height
175
+ },
176
+ rotation
177
+ }, i) => {
178
+ // The viewer turns the page clockwise by /Rotate, so the overlay is turned back counter-clockwise
179
+ // around the box corner that is shown at the bottom left.
180
+ const [originX, originY] = {
181
+ 0: [x, y],
182
+ 90: [x + width, y],
183
+ 180: [x + width, y + height],
184
+ 270: [x, y + height]
185
+ }[rotation];
186
+ page.drawPage(embedded[i], {
187
+ x: originX,
188
+ y: originY,
189
+ rotate: (0, _pdfLib.degrees)(rotation)
190
+ });
191
+ });
192
+ }
193
+ return save(doc);
194
+ }
@@ -0,0 +1,48 @@
1
+ "use strict";
2
+
3
+ exports.__esModule = true;
4
+ exports.labelPages = labelPages;
5
+ exports.pageNumberFormats = void 0;
6
+ // w-pdfmaker: Word-like page numbering per section (section `pageNumbering: { start, format }`).
7
+
8
+ const THAI_LETTERS = 'กขคฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรลวศษสหฬอฮ'; // without obsolete ฃ ฅ, as in Thai theses
9
+ const ROMAN = [[1000, 'M'], [900, 'CM'], [500, 'D'], [400, 'CD'], [100, 'C'], [90, 'XC'], [50, 'L'], [40, 'XL'], [10, 'X'], [9, 'IX'], [5, 'V'], [4, 'IV'], [1, 'I']];
10
+ function toRoman(n) {
11
+ let result = '';
12
+ for (const [value, numeral] of ROMAN) {
13
+ for (; n >= value; n -= value) {
14
+ result += numeral;
15
+ }
16
+ }
17
+ return result;
18
+ }
19
+ const pageNumberFormats = exports.pageNumberFormats = {
20
+ '1': n => String(n),
21
+ 'i': n => toRoman(n).toLowerCase(),
22
+ 'I': toRoman,
23
+ '๑': n => String(n).replace(/\d/g, digit => '๐๑๒๓๔๕๖๗๘๙'[digit]),
24
+ // after ฮ, repeat the letter like Word does after z: กก, ขข, ...
25
+ 'ก': n => n > 0 ? THAI_LETTERS[(n - 1) % THAI_LETTERS.length].repeat(Math.ceil(n / THAI_LETTERS.length)) : ''
26
+ };
27
+
28
+ /**
29
+ * Sets `pageLabel` on every page. A section's first page may carry `pageNumbering`:
30
+ * `start` restarts the count, `format` changes it; otherwise numbering continues from the previous page.
31
+ */
32
+ function labelPages(pages) {
33
+ let number = 0;
34
+ let format = pageNumberFormats['1'];
35
+ for (const page of pages) {
36
+ const numbering = page.pageNumbering;
37
+ if (numbering && numbering.format !== undefined) {
38
+ format = typeof numbering.format === 'function' ? numbering.format : pageNumberFormats[numbering.format];
39
+ if (!format) {
40
+ throw new Error(`Unknown page number format '${numbering.format}', use one of '${Object.keys(pageNumberFormats).join('\', \'')}' or a function`);
41
+ }
42
+ }
43
+ if (numbering && numbering.start !== undefined) {
44
+ number = numbering.start - 1;
45
+ }
46
+ page.pageLabel = String(format(++number));
47
+ }
48
+ }