jspdf-dynamo 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/LICENSE +8 -0
  2. package/README.md +93 -0
  3. package/dist/index.cjs +2175 -0
  4. package/dist/index.d.cts +370 -0
  5. package/dist/index.d.ts +370 -0
  6. package/dist/index.js +2145 -0
  7. package/documentation/1. Introduction/Introduction.txt +91 -0
  8. package/documentation/2. JsPdfDynamo/JsPdfDynamo.txt +6 -0
  9. package/documentation/2. JsPdfDynamo/constructor.txt +31 -0
  10. package/documentation/2. JsPdfDynamo/getVariable.txt +29 -0
  11. package/documentation/2. JsPdfDynamo/prepareWrappedString.txt +28 -0
  12. package/documentation/2. JsPdfDynamo/processCommands.txt +27 -0
  13. package/documentation/2. JsPdfDynamo/toBlob.txt +19 -0
  14. package/documentation/2. JsPdfDynamo/toBlobUrl.txt +36 -0
  15. package/documentation/3. Variables/Introduction.txt +36 -0
  16. package/documentation/3. Variables/SystemMaintained.txt +190 -0
  17. package/documentation/4. Commands/AddBookmark.txt +47 -0
  18. package/documentation/4. Commands/AddImageFromFile.txt +59 -0
  19. package/documentation/4. Commands/AddImageFromUrl.txt +63 -0
  20. package/documentation/4. Commands/AddPage.txt +40 -0
  21. package/documentation/4. Commands/CheckPage.txt +52 -0
  22. package/documentation/4. Commands/CopyVar.txt +52 -0
  23. package/documentation/4. Commands/Do.txt +40 -0
  24. package/documentation/4. Commands/DoRepeat.txt +51 -0
  25. package/documentation/4. Commands/DrawBox.txt +67 -0
  26. package/documentation/4. Commands/DrawDebugGrid.txt +41 -0
  27. package/documentation/4. Commands/DrawImage.txt +92 -0
  28. package/documentation/4. Commands/DrawLine.txt +62 -0
  29. package/documentation/4. Commands/DrawText.txt +61 -0
  30. package/documentation/4. Commands/DrawTextBox.txt +99 -0
  31. package/documentation/4. Commands/DrawTextWrapped.txt +65 -0
  32. package/documentation/4. Commands/ForEachPage.txt +44 -0
  33. package/documentation/4. Commands/GetEnvVar.txt +56 -0
  34. package/documentation/4. Commands/IfBlank.txt +63 -0
  35. package/documentation/4. Commands/IfGt.txt +58 -0
  36. package/documentation/4. Commands/IfNotBlank.txt +60 -0
  37. package/documentation/4. Commands/IncCurrentX.txt +52 -0
  38. package/documentation/4. Commands/IncCurrentY.txt +50 -0
  39. package/documentation/4. Commands/IncVar.txt +73 -0
  40. package/documentation/4. Commands/Include.txt +44 -0
  41. package/documentation/4. Commands/MultVar.txt +70 -0
  42. package/documentation/4. Commands/SetCurrentX.txt +37 -0
  43. package/documentation/4. Commands/SetCurrentY.txt +37 -0
  44. package/documentation/4. Commands/SetDocumentInfo.txt +35 -0
  45. package/documentation/4. Commands/SetFillColour.txt +58 -0
  46. package/documentation/4. Commands/SetFontName.txt +4 -0
  47. package/documentation/4. Commands/SetFontSize.txt +22 -0
  48. package/documentation/4. Commands/SetFontStyle.txt +55 -0
  49. package/documentation/4. Commands/SetLineColour.txt +58 -0
  50. package/documentation/4. Commands/SetLineWidth.txt +42 -0
  51. package/documentation/4. Commands/SetMargin.txt +69 -0
  52. package/documentation/4. Commands/SetPageOrientation.txt +42 -0
  53. package/documentation/4. Commands/SetVar.txt +69 -0
  54. package/documentation/5. Other Definitions/jsPdfOptions.txt +56 -0
  55. package/documentation/5. Other Definitions/logger.txt +35 -0
  56. package/documentation/5. Other Definitions/pageSizes.txt +41 -0
  57. package/documentation/6. Other/PossibleEnhancements.txt +63 -0
  58. package/documentation/6. Other/To Be Documented.txt +50 -0
  59. package/documentation/Documentation.pdf +9859 -0
  60. package/documentation/README.md +7 -0
  61. package/documentation/documentation.txt +266 -0
  62. package/documentation/gendoc.spec.ts +22 -0
  63. package/examples/1.Simple/simple.pdf +247 -0
  64. package/examples/1.Simple/template.txt +21 -0
  65. package/examples/examples.spec.ts +26 -0
  66. package/package.json +58 -0
package/dist/index.cjs ADDED
@@ -0,0 +1,2175 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __typeError = (msg) => {
9
+ throw TypeError(msg);
10
+ };
11
+ var __export = (target, all) => {
12
+ for (var name in all)
13
+ __defProp(target, name, { get: all[name], enumerable: true });
14
+ };
15
+ var __copyProps = (to, from, except, desc) => {
16
+ if (from && typeof from === "object" || typeof from === "function") {
17
+ for (let key of __getOwnPropNames(from))
18
+ if (!__hasOwnProp.call(to, key) && key !== except)
19
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
20
+ }
21
+ return to;
22
+ };
23
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
24
+ // If the importer is in node compatibility mode or this is not an ESM
25
+ // file that has been converted to a CommonJS file using a Babel-
26
+ // compatible transform (i.e. "__esModule" has not been set), then set
27
+ // "default" to the CommonJS "module.exports" for node compatibility.
28
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
29
+ mod
30
+ ));
31
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
32
+ var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
33
+ var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
34
+ var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
35
+ var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
36
+ var __async = (__this, __arguments, generator) => {
37
+ return new Promise((resolve, reject) => {
38
+ var fulfilled = (value) => {
39
+ try {
40
+ step(generator.next(value));
41
+ } catch (e) {
42
+ reject(e);
43
+ }
44
+ };
45
+ var rejected = (value) => {
46
+ try {
47
+ step(generator.throw(value));
48
+ } catch (e) {
49
+ reject(e);
50
+ }
51
+ };
52
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
53
+ step((generator = generator.apply(__this, __arguments)).next());
54
+ });
55
+ };
56
+
57
+ // src/index.ts
58
+ var src_exports = {};
59
+ __export(src_exports, {
60
+ JsPdfDynamo: () => JsPdfDynamo
61
+ });
62
+ module.exports = __toCommonJS(src_exports);
63
+
64
+ // src/jsPdfDynamo.ts
65
+ var import_node_fetch = __toESM(require("node-fetch"), 1);
66
+
67
+ // src/models/jsPdfProcessor.ts
68
+ var import_jspdf = __toESM(require("jspdf"), 1);
69
+ var fs = __toESM(require("fs"), 1);
70
+
71
+ // src/models/logger.ts
72
+ var AppLogger = class {
73
+ constructor(logger = null) {
74
+ this._logLevel = 2;
75
+ if (logger) {
76
+ this._logger = logger;
77
+ } else {
78
+ this._logger = console;
79
+ }
80
+ }
81
+ trace(message, ...args) {
82
+ this.canLog(0) ? this._logger.trace(message, args) : null;
83
+ }
84
+ debug(message, ...args) {
85
+ this.canLog(1) ? this._logger.debug(message, args) : null;
86
+ }
87
+ info(message, ...args) {
88
+ this.canLog(2) ? this._logger.info(message, args) : null;
89
+ }
90
+ warn(message, ...args) {
91
+ this.canLog(3) ? this._logger.warn(message, args) : null;
92
+ }
93
+ error(message, ...args) {
94
+ this.canLog(4) ? this._logger.error(message, args) : null;
95
+ }
96
+ logLevel(newLevel) {
97
+ if (typeof newLevel === "string") {
98
+ const level = newLevel.toLowerCase();
99
+ switch (level) {
100
+ case "trace":
101
+ this._logLevel = 0;
102
+ break;
103
+ case "debug":
104
+ this._logLevel = 1;
105
+ break;
106
+ case "info":
107
+ this._logLevel = 2;
108
+ break;
109
+ case "warn":
110
+ this._logLevel = 3;
111
+ break;
112
+ case "error":
113
+ this._logLevel = 4;
114
+ break;
115
+ case "silent":
116
+ this._logLevel = 5;
117
+ break;
118
+ }
119
+ } else {
120
+ if (newLevel >= 0 && newLevel <= 5) {
121
+ this._logLevel = newLevel;
122
+ }
123
+ }
124
+ if (this._logger.logLevel) {
125
+ this._logger.logLevel(this._logLevel);
126
+ }
127
+ }
128
+ canLog(level) {
129
+ return level >= this._logLevel;
130
+ }
131
+ };
132
+
133
+ // src/utils/utils.ts
134
+ function removeTrailingZeros(numString) {
135
+ if (!numString.includes(".") || numString.includes("e") || numString.includes("E") || numString.includes("Infinity") || isNaN(Number(numString))) {
136
+ return numString;
137
+ }
138
+ let trimmedString = numString.trim();
139
+ let decimalIndex = trimmedString.indexOf(".");
140
+ while (trimmedString.length > decimalIndex && trimmedString.endsWith("0")) {
141
+ trimmedString = trimmedString.substring(0, trimmedString.length - 1);
142
+ }
143
+ if (trimmedString.endsWith(".")) {
144
+ return trimmedString.substring(0, trimmedString.length - 1);
145
+ }
146
+ return trimmedString;
147
+ }
148
+ function getNextNumber(input, maxPlaces = -1) {
149
+ let first = 0;
150
+ let rest = "";
151
+ if (!input) {
152
+ return { first, rest };
153
+ }
154
+ input = input.trimStart();
155
+ if (input.length === 0) {
156
+ return { first, rest };
157
+ }
158
+ let firstValue;
159
+ let ix = input.indexOf(" ");
160
+ if (ix < 0) {
161
+ firstValue = input;
162
+ } else {
163
+ firstValue = input.substring(0, ix);
164
+ rest = input.slice(ix).trimStart();
165
+ }
166
+ if (maxPlaces < 0) {
167
+ first = Number(firstValue);
168
+ } else {
169
+ first = Number(Number(firstValue).toFixed(maxPlaces));
170
+ }
171
+ return { first, rest };
172
+ }
173
+ function getNextString(input) {
174
+ let first = "";
175
+ let rest = "";
176
+ input = input.trimStart();
177
+ if (input.length === 0) {
178
+ return { first, rest };
179
+ }
180
+ let ix = input.indexOf(" ");
181
+ if (ix < 0) {
182
+ first = input;
183
+ } else {
184
+ first = input.substring(0, ix);
185
+ rest = input.slice(ix).trimStart();
186
+ }
187
+ return { first, rest };
188
+ }
189
+ function isBrowser() {
190
+ return typeof process === "object" && process + "" === "[object process]" ? false : true;
191
+ }
192
+ function pointsToMm(points) {
193
+ return points === null || points === void 0 ? points : Number((points * 0.352777778).toFixed(4));
194
+ }
195
+ function mmToPoints(mm) {
196
+ return mm === null || mm === void 0 ? mm : Number((mm / 0.352777778).toFixed(4));
197
+ }
198
+ function pointsToInches(points) {
199
+ return points === null || points === void 0 ? points : Number((points * 0.0138888611).toFixed(4));
200
+ }
201
+ function inchesToPoints(inches) {
202
+ return inches === null || inches === void 0 ? inches : Number((inches / 0.0138888611).toFixed(4));
203
+ }
204
+ function pixelsToMm(pixels, dpi = 96) {
205
+ return pixels === null || pixels === void 0 || isNaN(pixels) || isNaN(dpi) || dpi <= 0 ? pixels : Number((pixels * 25.4 / dpi).toFixed(4));
206
+ }
207
+ function pixelsToInches(pixels, dpi = 96) {
208
+ return pixels === null || pixels === void 0 || isNaN(pixels) || isNaN(dpi) || dpi <= 0 ? pixels : Number((pixels / dpi).toFixed(4));
209
+ }
210
+ function pointsToPixels(points, dpi = 96) {
211
+ return points === null || points === void 0 || isNaN(points) || isNaN(dpi) || dpi <= 0 ? points : Number((points * dpi / 72).toFixed(4));
212
+ }
213
+ function pixelsToPoints(pixels, dpi = 96) {
214
+ return pixels === null || pixels === void 0 || isNaN(pixels) || isNaN(dpi) || dpi <= 0 ? pixels : Number((pixels * 72 / dpi).toFixed(4));
215
+ }
216
+
217
+ // src/utils/page.utils.ts
218
+ var pageSizes = {
219
+ ledger: { width: 1224.7, height: 791 },
220
+ legal: { width: 612, height: 1008 },
221
+ "junior-legal": { width: 360, height: 575.5 },
222
+ letter: { width: 612, height: 792 },
223
+ "government-letter": { width: 575.5, height: 756.9 },
224
+ "credit-card": { width: 153, height: 243 },
225
+ tabloid: { width: 792, height: 1224 },
226
+ a0: { width: 2383.94, height: 3370.39 },
227
+ a1: { width: 1683.78, height: 2383.94 },
228
+ a2: { width: 1190.55, height: 1683.78 },
229
+ a3: { width: 841.89, height: 1190.55 },
230
+ a4: { width: 595.28, height: 841.89 },
231
+ a5: { width: 419.53, height: 595.28 },
232
+ a6: { width: 297.64, height: 419.53 },
233
+ a7: { width: 209.76, height: 297.64 },
234
+ a8: { width: 147.4, height: 209.76 },
235
+ a9: { width: 104.88, height: 147.4 },
236
+ a10: { width: 73.7, height: 104.88 },
237
+ b0: { width: 2834.65, height: 4008.19 },
238
+ b1: { width: 2004.09, height: 2834.65 },
239
+ b2: { width: 1417.32, height: 2004.09 },
240
+ b3: { width: 1000.63, height: 1417.32 },
241
+ b4: { width: 708.66, height: 1000.63 },
242
+ b5: { width: 498.9, height: 708.66 },
243
+ b6: { width: 354.33, height: 498.9 },
244
+ b7: { width: 249.45, height: 354.33 },
245
+ b8: { width: 175.75, height: 249.45 },
246
+ b9: { width: 124.72, height: 175.75 },
247
+ b10: { width: 87.87, height: 124.72 },
248
+ c0: { width: 2599.37, height: 3676.54 },
249
+ c1: { width: 1836.85, height: 2599.37 },
250
+ c2: { width: 1298.27, height: 1836.85 },
251
+ c3: { width: 918.43, height: 1298.27 },
252
+ c4: { width: 649.13, height: 918.43 },
253
+ c5: { width: 459.21, height: 649.13 },
254
+ c6: { width: 323.15, height: 459.21 },
255
+ c7: { width: 229.61, height: 323.15 },
256
+ c8: { width: 161.57, height: 229.61 },
257
+ c9: { width: 113.39, height: 161.57 },
258
+ c10: { width: 79.37, height: 113.39 },
259
+ dl: { width: 311.81, height: 623.62 }
260
+ };
261
+ function isValidPageSize(pageSize) {
262
+ return pageSizes.hasOwnProperty(pageSize);
263
+ }
264
+
265
+ // src/utils/types.ts
266
+ function isValidFontStyle(fontStyle) {
267
+ return ["bold", "italic", "normal", "bolditalic"].includes(fontStyle);
268
+ }
269
+
270
+ // src/models/jsPdfOptions.ts
271
+ var JsPdfOptions = class {
272
+ constructor(options = {}) {
273
+ var _a, _b, _c;
274
+ this.pageSize = ((_a = options.pageSize) == null ? void 0 : _a.toLocaleLowerCase()) || "a4";
275
+ this.orientation = ((_b = options.orientation) == null ? void 0 : _b.toLocaleLowerCase()) || "portrait";
276
+ this.unit = ((_c = options.unit) == null ? void 0 : _c.toLocaleLowerCase()) || "mm";
277
+ let defaultMargin;
278
+ switch (this.unit) {
279
+ case "mm":
280
+ defaultMargin = 10;
281
+ break;
282
+ case "in":
283
+ defaultMargin = 0.4;
284
+ break;
285
+ case "pt":
286
+ defaultMargin = 28;
287
+ break;
288
+ }
289
+ this.margins = Object.assign(
290
+ {
291
+ top: defaultMargin,
292
+ bottom: defaultMargin,
293
+ left: defaultMargin,
294
+ right: defaultMargin
295
+ },
296
+ options.margins
297
+ );
298
+ }
299
+ };
300
+
301
+ // src/models/jsPdfProcessor.ts
302
+ var JsPdfProcessor = class {
303
+ constructor(options, logger) {
304
+ this._variables = /* @__PURE__ */ new Map();
305
+ this._bookmarks = [];
306
+ this._images = [];
307
+ this._currentPageNumber = 0;
308
+ this._currentUom = "mm";
309
+ this._fillColour = "white";
310
+ this._fontHeight = 0;
311
+ this._fontName = "helvetica";
312
+ this._fontPointSize = 0;
313
+ this._fontStyle = "normal";
314
+ this._lastError = "";
315
+ this._lastImageAdded = "";
316
+ this._LastImageIndex = -1;
317
+ this._lastResult = "";
318
+ this._lineColour = "black";
319
+ this._lineWidth = 0.5;
320
+ this._logLevel = 2;
321
+ this._pageHeight = 0;
322
+ this._pageWidth = 0;
323
+ this._pageOrientation = "portrait";
324
+ this._pageSize = "a4";
325
+ this._marginBottom = 0;
326
+ this._marginBottomPt = 0;
327
+ this._marginTop = 0;
328
+ this._marginTopPt = 0;
329
+ this._marginLeft = 0;
330
+ this._marginLeftPt = 0;
331
+ this._marginRight = 0;
332
+ this._marginRightPt = 0;
333
+ this._lastObjectHeight = 0;
334
+ this._lastObjectWidth = 0;
335
+ this._posnX = 0;
336
+ this._posnY = 0;
337
+ this._spaceHoz = 0;
338
+ this._spaceVert = 0;
339
+ this._textColour = "";
340
+ this.logAndParseCommand = (command, input) => {
341
+ const result = this.substitute(input);
342
+ this._logger.debug(command + " " + result);
343
+ return result;
344
+ };
345
+ this._logger = logger;
346
+ const optn = new JsPdfOptions(options);
347
+ this._pdfDocument = new import_jspdf.default(optn);
348
+ this.pageSize = optn.pageSize;
349
+ this.pageOrientation = optn.orientation;
350
+ this.currentUom = optn.unit;
351
+ this._pdfDocument.setLineHeightFactor(1);
352
+ this._variables.set(
353
+ "_TIMEHM",
354
+ (/* @__PURE__ */ new Date()).toLocaleTimeString("en-US", {
355
+ hour12: false,
356
+ hour: "2-digit",
357
+ minute: "2-digit"
358
+ })
359
+ );
360
+ this._variables.set("_DATEDMY", (/* @__PURE__ */ new Date()).toLocaleDateString("en-GB"));
361
+ this._variables.set("_PAGENO", "1");
362
+ this._variables.set("_PAGES", "1");
363
+ this.spaceHoz = 0;
364
+ this.spaceVert = 0;
365
+ this.lineWidth = this.pointsToUom(mmToPoints(0.2));
366
+ this.lineColour = "black";
367
+ this.fontPointSize = 12;
368
+ this.fontName = "helvetica";
369
+ this.textColour = "black";
370
+ this.fillColour = "white";
371
+ this.marginTop = this.pixelsToUom(40);
372
+ this.marginLeft = this.marginTop;
373
+ this.marginBottom = this.marginTop;
374
+ this.marginRight = this.marginTop;
375
+ }
376
+ get PdfDocument() {
377
+ return this._pdfDocument;
378
+ }
379
+ get currentPageNumber() {
380
+ return this._currentPageNumber;
381
+ }
382
+ set currentPageNumber(value) {
383
+ if (isNaN(value)) {
384
+ this.lastResult = "0";
385
+ this.lastError = "Page number must be a number, received 'NaN'";
386
+ return;
387
+ }
388
+ if (value !== Math.floor(value)) {
389
+ this.lastResult = "0";
390
+ this.lastError = "Page number must be an integer";
391
+ return;
392
+ }
393
+ if (value < 0) {
394
+ this.lastResult = "0";
395
+ this.lastError = "Page number must be greater than 0";
396
+ return;
397
+ }
398
+ if (value > this.pageCount) {
399
+ this.lastResult = "0";
400
+ this.lastError = `Page number ${value} is greater than the number of pages`;
401
+ return;
402
+ }
403
+ this._currentPageNumber = value;
404
+ this._variables.set("_PAGENO", value.toString());
405
+ this.calcPageDimensions(this._pdfDocument);
406
+ }
407
+ get currentUom() {
408
+ return this._currentUom;
409
+ }
410
+ set currentUom(value) {
411
+ if (this._currentUom !== value) {
412
+ this._currentUom = value;
413
+ }
414
+ }
415
+ get fillColour() {
416
+ return this._fillColour;
417
+ }
418
+ set fillColour(value) {
419
+ this._fillColour = value.toLocaleLowerCase();
420
+ this._pdfDocument.setFillColor(this._fillColour);
421
+ this._variables.set("_FILLCOLOUR", this._fillColour);
422
+ }
423
+ get fontHeight() {
424
+ return this._fontHeight;
425
+ }
426
+ set fontHeight(value) {
427
+ this._fontHeight = value;
428
+ this._variables.set("_FONTHEIGHT", this.setFixedDec(value, 3));
429
+ }
430
+ get fontName() {
431
+ return this._fontName;
432
+ }
433
+ set fontName(value) {
434
+ this._fontName = value;
435
+ this.setCurrentFont(this.fontName, this.fontStyle);
436
+ this._variables.set("_FONTNAME", value);
437
+ }
438
+ get fontPointSize() {
439
+ return this._fontPointSize;
440
+ }
441
+ set fontPointSize(value) {
442
+ if (!value) {
443
+ this.lastError = "Font point size is required";
444
+ this.lastResult = "0";
445
+ return;
446
+ }
447
+ if (isNaN(Number(value))) {
448
+ this.lastError = "Font point size must be a number, received 'NaN'";
449
+ this.lastResult = "0";
450
+ return;
451
+ }
452
+ if (value <= 0) {
453
+ this.lastError = "Font point size must be greater than 0";
454
+ this.lastResult = "0";
455
+ return;
456
+ }
457
+ this._fontPointSize = value;
458
+ this._pdfDocument.setFontSize(value);
459
+ this.fontHeight = this.pointsToUom(value) * this.lineHeightFactor;
460
+ this._variables.set("_FONTPOINTSIZE", value.toString());
461
+ }
462
+ get lineHeightFactor() {
463
+ return this._pdfDocument["getLineHeightFactor"] ? this._pdfDocument["getLineHeightFactor"]() : 1.15;
464
+ }
465
+ get fontStyle() {
466
+ return this._fontStyle;
467
+ }
468
+ set fontStyle(value) {
469
+ this._fontStyle = value;
470
+ this.setCurrentFont(this.fontName, this.fontStyle);
471
+ this._variables.set("_FONTSTYLE", value);
472
+ }
473
+ get lastError() {
474
+ return this._lastError;
475
+ }
476
+ set lastError(value) {
477
+ this._lastError = value;
478
+ if (value !== "") {
479
+ this._logger.warn(value);
480
+ }
481
+ }
482
+ get lastImageAdded() {
483
+ return this._lastImageAdded;
484
+ }
485
+ set lastImageAdded(value) {
486
+ this._lastImageAdded = value;
487
+ this._variables.set("_LASTIMAGEADDED", value);
488
+ }
489
+ get lastImageIndex() {
490
+ return this._LastImageIndex;
491
+ }
492
+ set lastImageIndex(value) {
493
+ this._LastImageIndex = value;
494
+ this._variables.set("_LASTIMAGEINDEX", value.toString());
495
+ }
496
+ get lastResult() {
497
+ return this._lastResult;
498
+ }
499
+ set lastResult(value) {
500
+ this._lastResult = value;
501
+ this._variables.set("_LASTRESULT", value);
502
+ }
503
+ get lineColour() {
504
+ return this._lineColour;
505
+ }
506
+ set lineColour(value) {
507
+ this._lineColour = value.toLocaleLowerCase();
508
+ this._pdfDocument.setDrawColor(this._lineColour);
509
+ this._variables.set("_LINECOLOUR", this._lineColour);
510
+ }
511
+ get lineWidth() {
512
+ return this._lineWidth;
513
+ }
514
+ set lineWidth(value) {
515
+ this._logger.trace(`Setting line width to ${value}`);
516
+ this._lineWidth = value;
517
+ this._pdfDocument.setLineWidth(value);
518
+ this._variables.set("_LINEWIDTH", value.toString());
519
+ }
520
+ get pageHeight() {
521
+ return this._pageHeight;
522
+ }
523
+ set pageHeight(value) {
524
+ this._pageHeight = value;
525
+ this._variables.set("_PAGEHEIGHT", this.setFixedDec(value));
526
+ }
527
+ get pageWidth() {
528
+ return this._pageWidth;
529
+ }
530
+ set pageWidth(value) {
531
+ this._pageWidth = value;
532
+ this._variables.set("_PAGEWIDTH", this.setFixedDec(value));
533
+ }
534
+ get pageOrientation() {
535
+ return this._pageOrientation;
536
+ }
537
+ set pageOrientation(value) {
538
+ this._pageOrientation = value;
539
+ this._variables.set("_CURRENTPAGEORIENTATION", value);
540
+ this.calcPageDimensions(this.PdfDocument);
541
+ }
542
+ get pageSize() {
543
+ return this._pageSize;
544
+ }
545
+ set pageSize(value) {
546
+ if (!isValidPageSize(value)) {
547
+ this.lastError = "Invalid page size '" + value + "'";
548
+ this.lastResult = "0";
549
+ return;
550
+ }
551
+ this._pageSize = value;
552
+ this._variables.set("_CURRENTPAGESIZE", value);
553
+ this.calcPageDimensions(this.PdfDocument);
554
+ }
555
+ get marginBottom() {
556
+ return this._marginBottom;
557
+ }
558
+ set marginBottom(value) {
559
+ this._marginBottom = value > 0 ? value : 0;
560
+ this._marginBottomPt = this.uomToPoints(value);
561
+ this.calcPageDimensions(this.PdfDocument);
562
+ this._variables.set("_MARGINBOTTOM", value.toString());
563
+ }
564
+ get marginTop() {
565
+ return this._marginTop;
566
+ }
567
+ set marginTop(value) {
568
+ this._marginTop = value > 0 ? value : 0;
569
+ this._marginTopPt = this.uomToPoints(value);
570
+ this.calcPageDimensions(this.PdfDocument);
571
+ this._variables.set("_MARGINTOP", value.toString());
572
+ }
573
+ get marginLeft() {
574
+ return this._marginLeft;
575
+ }
576
+ set marginLeft(value) {
577
+ this._marginLeft = value > 0 ? value : 0;
578
+ this._marginLeftPt = this.uomToPoints(value);
579
+ this.calcPageDimensions(this.PdfDocument);
580
+ this._variables.set("_MARGINLEFT", value.toString());
581
+ }
582
+ get marginRight() {
583
+ return this._marginRight;
584
+ }
585
+ set marginRight(value) {
586
+ this._marginRight = value > 0 ? value : 0;
587
+ this._marginRightPt = this.uomToPoints(value);
588
+ this.calcPageDimensions(this.PdfDocument);
589
+ this._variables.set("_MARGINRIGHT", value.toString());
590
+ }
591
+ get lastObjectHeight() {
592
+ return this._lastObjectHeight;
593
+ }
594
+ set lastObjectHeight(value) {
595
+ this._lastObjectHeight = value;
596
+ this._variables.set("_LASTOBJECTHEIGHT", this.setFixedDec(value));
597
+ }
598
+ get lastObjectWidth() {
599
+ return this._lastObjectWidth;
600
+ }
601
+ set lastObjectWidth(value) {
602
+ this._lastObjectWidth = value;
603
+ this._variables.set("_LASTOBJECTWIDTH", this.setFixedDec(value));
604
+ }
605
+ get posnX() {
606
+ return this._posnX;
607
+ }
608
+ set posnX(value) {
609
+ this._posnX = value > 0 ? value : 0;
610
+ this._variables.set("_CURRENTX", this.setFixedDec(this.posnX));
611
+ }
612
+ get posnY() {
613
+ return this._posnY;
614
+ }
615
+ set posnY(value) {
616
+ this._posnY = value > 0 ? value : 0;
617
+ this._variables.set("_CURRENTY", this.setFixedDec(this._posnY));
618
+ }
619
+ get spaceHoz() {
620
+ return this._spaceHoz;
621
+ }
622
+ set spaceHoz(value) {
623
+ this._spaceHoz = value > 0 ? value : 0;
624
+ this._variables.set("_SPACEHOZ", this.setFixedDec(value));
625
+ }
626
+ get spaceVert() {
627
+ return this._spaceVert;
628
+ }
629
+ set spaceVert(value) {
630
+ this._spaceVert = value > 0 ? value : 0;
631
+ this._variables.set("_SPACEVERT", this.setFixedDec(value, 3));
632
+ }
633
+ get textColour() {
634
+ return this._textColour;
635
+ }
636
+ set textColour(value) {
637
+ this._textColour = value.toLocaleLowerCase();
638
+ this._variables.set("_TEXTCOLOUR", this._textColour);
639
+ this._pdfDocument.setTextColor(this._textColour);
640
+ }
641
+ get pageCount() {
642
+ return this._pdfDocument ? this._pdfDocument.internal.getNumberOfPages() : -1;
643
+ }
644
+ addBookmark(input) {
645
+ const subs = this.logAndParseCommand(".addBookmark", input);
646
+ const { first: parent, rest: rest1 } = getNextNumber(subs);
647
+ const { first: page, rest: title } = getNextNumber(rest1);
648
+ if (title === "") {
649
+ this.lastError = "A bookmark title is required.";
650
+ this.lastResult = "0";
651
+ return;
652
+ }
653
+ if (parent && isNaN(parent)) {
654
+ this.lastError = `The parent Id '${parent}' must be a number.`;
655
+ this.lastResult = "0";
656
+ return;
657
+ }
658
+ if (parent < 0 || this._bookmarks.length > 0 && parent > this._bookmarks.length - 1) {
659
+ this.lastError = `The parent Id is out of range of 0 to ${this._bookmarks.length - 1}`;
660
+ this.lastResult = "0";
661
+ return;
662
+ }
663
+ if (isNaN(page)) {
664
+ this.lastError = "Page must be a number";
665
+ this.lastResult = "0";
666
+ return;
667
+ }
668
+ if (this._bookmarks.length === 0) {
669
+ this._bookmarks.push({ title: "Root", options: {}, children: [] });
670
+ }
671
+ const outlineParent = parent === 0 ? null : this._bookmarks[parent];
672
+ const bookmark = this._pdfDocument.outline.add(
673
+ outlineParent,
674
+ title,
675
+ { pageNumber: page }
676
+ );
677
+ if (bookmark === null) {
678
+ this.lastError = "Error adding bookmark";
679
+ this.lastResult = "0";
680
+ return;
681
+ }
682
+ this.lastResult = this._bookmarks.length.toString();
683
+ this._bookmarks.push(bookmark);
684
+ if (!outlineParent && this._bookmarks[0]) {
685
+ this._bookmarks[0].children.push(bookmark);
686
+ }
687
+ }
688
+ addPage(input = "") {
689
+ let subs = this.logAndParseCommand(".addPage", input);
690
+ let { first: pageSize, rest: rest1 } = getNextString(subs);
691
+ let { first: pageOrientation } = getNextString(rest1);
692
+ pageSize = pageSize.toLocaleLowerCase();
693
+ pageOrientation = pageOrientation.toLocaleLowerCase();
694
+ if (pageSize !== "") {
695
+ this.setPageSize(pageSize);
696
+ if (this.lastResult === "0") {
697
+ return;
698
+ }
699
+ }
700
+ if (pageOrientation !== "") {
701
+ this.setPageOrientation(pageOrientation);
702
+ if (this.lastResult === "0") {
703
+ return;
704
+ }
705
+ }
706
+ this._pdfDocument.addPage(this.pageSize, this.pageOrientation);
707
+ this.posnX = 0;
708
+ this.posnY = 0;
709
+ this._variables.set("_PAGES", this.pageCount.toString());
710
+ this.currentPageNumber = this.pageCount;
711
+ this.calcPageDimensions(this._pdfDocument);
712
+ }
713
+ calcPageDimensions(document) {
714
+ if (!document) {
715
+ this.pageHeight = 0;
716
+ this.pageWidth = 0;
717
+ } else {
718
+ this.pageHeight = document.internal.pageSize.height - this._marginTop - this._marginBottom;
719
+ this.pageWidth = document.internal.pageSize.width - this._marginLeft - this._marginRight;
720
+ }
721
+ }
722
+ addImageFromFile(input) {
723
+ const subs = this.logAndParseCommand(".addImageFromFile", input);
724
+ let fileName = subs;
725
+ if (!fileName) {
726
+ this.lastError = "A file name is required.";
727
+ this.lastResult = "0";
728
+ return;
729
+ }
730
+ if (!fs.existsSync(fileName)) {
731
+ this.lastError = "File '" + fileName + "' cannot be found or accessed.";
732
+ this.lastResult = "0";
733
+ return;
734
+ }
735
+ try {
736
+ const image = fs.readFileSync(fileName);
737
+ this.saveImage(image, this.getContentType(fileName));
738
+ this.lastResult = "1";
739
+ } catch (ex) {
740
+ this.lastError = "Error reading file '" + fileName + "'.";
741
+ this.lastResult = "0";
742
+ }
743
+ }
744
+ addImageFromUrl(input) {
745
+ return __async(this, null, function* () {
746
+ const subs = this.logAndParseCommand(".addImageFromUrl", input);
747
+ let url = subs;
748
+ if (!url) {
749
+ this.lastError = "A URL is required.";
750
+ this.lastResult = "0";
751
+ return;
752
+ }
753
+ try {
754
+ const response = yield fetch(url, {
755
+ headers: { Accept: "image/*, */*;q=0.8" }
756
+ });
757
+ if (!response.ok) {
758
+ this.lastError = "Error reading image '" + url + "'.";
759
+ this.lastResult = "0";
760
+ return;
761
+ }
762
+ const arrayBuffer = yield response.arrayBuffer();
763
+ const imageBuffer = Buffer.from(arrayBuffer);
764
+ const mediaType = response.headers.get("content-type") || "image/png";
765
+ this.saveImage(imageBuffer, mediaType);
766
+ this.lastResult = "1";
767
+ } catch (ex) {
768
+ this.lastError = "Error reading file '" + url + "'";
769
+ this.lastResult = "0";
770
+ }
771
+ });
772
+ }
773
+ saveImage(imageBuffer, mediaType) {
774
+ const base64Image = imageBuffer.toString("base64");
775
+ const image = "data:" + mediaType + ";base64," + base64Image;
776
+ this.lastImageAdded = this._images.length.toString();
777
+ this._images.push(image);
778
+ const info = this._pdfDocument.getImageProperties(image);
779
+ this._variables.set(
780
+ "_IMAGEWIDTH",
781
+ this.setFixedDec(this.pixelsToUom(info.width), 3)
782
+ );
783
+ this._variables.set("_IMAGEWIDTHPX", info.width.toString());
784
+ this._variables.set(
785
+ "_IMAGEHEIGHT",
786
+ this.setFixedDec(this.pixelsToUom(info.height), 3)
787
+ );
788
+ this._variables.set("_IMAGEHEIGHTPX", info.height.toString());
789
+ }
790
+ getContentType(fileName) {
791
+ const mediaType = fileName.split(".").pop();
792
+ return mediaType ? "image/" + mediaType : "";
793
+ }
794
+ checkPage(jsPdfDynamo, input) {
795
+ return __async(this, null, function* () {
796
+ const subs = this.logAndParseCommand(".checkPage", input);
797
+ const { first: overflow, rest } = getNextNumber(subs);
798
+ if (this.posnY > this._pageHeight - overflow) {
799
+ this._logger.debug(
800
+ `* End of page detected at PosnVert: ${this.posnY}, PageHeight: ${this._pageHeight} Overflow: ${overflow}`
801
+ );
802
+ if (rest.length === 0) {
803
+ this.addPage();
804
+ } else {
805
+ yield jsPdfDynamo.processGroups(this, rest, false);
806
+ }
807
+ }
808
+ });
809
+ }
810
+ drawBox(input) {
811
+ const subs = this.logAndParseCommand(".drawBox", input);
812
+ const { first: left, rest: rest1 } = getNextNumber(subs);
813
+ const { first: top, rest: rest2 } = getNextNumber(rest1);
814
+ const { first: width, rest: rest3 } = getNextNumber(rest2);
815
+ const { first: height, rest: rest4 } = getNextNumber(rest3);
816
+ const { first: boxType } = getNextNumber(rest4);
817
+ if (!this.checkPosition(left, top)) {
818
+ return;
819
+ }
820
+ this.posnX = left;
821
+ this.posnY = top;
822
+ let lineWidthAdjustment = this._lineWidth;
823
+ let linePosnAdjustment = lineWidthAdjustment * 0.5;
824
+ const x = this.posnX - linePosnAdjustment + this._marginLeft;
825
+ const y = this.posnY - linePosnAdjustment + this._marginTop;
826
+ const w = width + lineWidthAdjustment * 2;
827
+ const h = height + lineWidthAdjustment * 2;
828
+ let style = "S";
829
+ switch (boxType) {
830
+ case 0:
831
+ break;
832
+ case 1:
833
+ style = "F";
834
+ this._pdfDocument.setFillColor(this.fillColour);
835
+ break;
836
+ case 2:
837
+ style = "FD";
838
+ this._pdfDocument.setFillColor(this.fillColour);
839
+ break;
840
+ }
841
+ this._pdfDocument.rect(x, y, w, h, style);
842
+ this.posnX = this.posnX + width + this.spaceHoz;
843
+ this.posnY = this.posnY + height + this.spaceVert;
844
+ this.lastObjectHeight = height;
845
+ this.lastObjectWidth = width;
846
+ this.lastResult = "1";
847
+ }
848
+ drawDebugGrid(input) {
849
+ const subs = this.logAndParseCommand(".drawDebugGrid", input);
850
+ const savedLineColour = this.lineColour;
851
+ const savedLineWidth = this.lineWidth;
852
+ const mm = 0.1;
853
+ const pts = mmToPoints(mm);
854
+ const lineWidth = this.pointsToUom(pts);
855
+ this.lineWidth = lineWidth;
856
+ this.lineColour = "lightgrey";
857
+ let offsetLeft = this._marginLeft;
858
+ let offsetTop = this._marginTop;
859
+ let offsetRight = this._marginRight;
860
+ let offsetBottom = this._marginBottom;
861
+ if (subs.toLocaleUpperCase().startsWith("P")) {
862
+ offsetLeft = 0;
863
+ offsetTop = 0;
864
+ offsetRight = 0;
865
+ offsetBottom = 0;
866
+ } else {
867
+ this.drawBox(`0 0 ${this._pageWidth} ${this._pageHeight} 0`);
868
+ }
869
+ let step = 30;
870
+ switch (this.currentUom) {
871
+ case "in" /* in */:
872
+ step = 0.5;
873
+ break;
874
+ case "mm" /* mm */:
875
+ step = 10;
876
+ break;
877
+ }
878
+ let width = this._pdfDocument.internal.pageSize.width - offsetLeft - offsetRight;
879
+ let height = this._pdfDocument.internal.pageSize.height - offsetTop - offsetBottom;
880
+ let currX = step;
881
+ let counter = 0;
882
+ while (currX < width) {
883
+ counter++;
884
+ this.lineWidth = this.currentUom === "in" /* in */ && counter % 2 === 0 ? lineWidth * 4 : lineWidth;
885
+ this._pdfDocument.line(
886
+ currX + offsetLeft,
887
+ offsetTop,
888
+ currX + offsetLeft,
889
+ height + offsetTop
890
+ );
891
+ currX = counter * step;
892
+ }
893
+ let currY = step;
894
+ counter = 0;
895
+ while (currY < height) {
896
+ counter++;
897
+ this.lineWidth = this.currentUom === "in" /* in */ && counter % 2 === 0 ? lineWidth * 4 : lineWidth;
898
+ this._pdfDocument.line(
899
+ offsetLeft,
900
+ currY + offsetTop,
901
+ width + offsetLeft,
902
+ currY + offsetTop
903
+ );
904
+ currY = counter * step;
905
+ }
906
+ this.lineColour = savedLineColour;
907
+ this.lineWidth = savedLineWidth;
908
+ }
909
+ drawLine(input) {
910
+ const subs = this.logAndParseCommand(".drawLine", input);
911
+ const { first: left, rest: rest1 } = getNextNumber(subs);
912
+ const { first: top, rest: rest2 } = getNextNumber(rest1);
913
+ const { first: right, rest: rest3 } = getNextNumber(rest2);
914
+ const { first: bottom } = getNextNumber(rest3);
915
+ if (!this.checkPosition(left, top) && !this.checkPosition(right, bottom)) {
916
+ return;
917
+ }
918
+ this._pdfDocument.line(
919
+ left + this._marginLeft,
920
+ top + this._marginTop,
921
+ right + this._marginLeft,
922
+ bottom + this._marginTop
923
+ );
924
+ this.lastObjectHeight = bottom - top;
925
+ this.lastObjectWidth = right - left;
926
+ this.lastResult = "1";
927
+ }
928
+ drawImage(input) {
929
+ const subs = this.logAndParseCommand(".drawImage", input);
930
+ const { first: imageNo, rest: rest1 } = getNextNumber(subs);
931
+ const { first: left, rest: rest2 } = getNextNumber(rest1);
932
+ const { first: top, rest: rest3 } = getNextNumber(rest2);
933
+ let { first: width, rest: rest4 } = getNextNumber(rest3);
934
+ let { first: height, rest: rest5 } = getNextNumber(rest4);
935
+ let { first: scale } = getNextNumber(rest5);
936
+ if (!subs) {
937
+ this.lastError = "An image number must be supplied";
938
+ this.lastResult = "0";
939
+ return;
940
+ }
941
+ if (this._images.length === 0) {
942
+ this.lastError = "No images have been loaded yet";
943
+ this.lastResult = "0";
944
+ return;
945
+ }
946
+ if (isNaN(imageNo) || imageNo < 0 || imageNo > this._images.length - 1) {
947
+ this.lastError = this._images.length ? "The image number must be in the range of 0 to " + (this._images.length - 1).toString() : "Only one image has been loaded, the image number can only be 0";
948
+ this.lastResult = "0";
949
+ return;
950
+ }
951
+ if (!this.checkPosition(left, top)) {
952
+ return;
953
+ }
954
+ const currentImage = this._images[imageNo];
955
+ if (!currentImage) {
956
+ this.lastError = "The image number is not valid!";
957
+ this.lastResult = "0";
958
+ return;
959
+ }
960
+ const info = this._pdfDocument.getImageProperties(currentImage);
961
+ if (scale === 0 && (width === 0 && height > 0 || width > 0 && height === 0)) {
962
+ scale = width === 0 ? this.pixelsToUom(info.height) / height : this.pixelsToUom(info.width) / width;
963
+ height = height === 0 ? this.pixelsToUom(info.height) / scale : height;
964
+ width = width === 0 ? this.pixelsToUom(info.width) / scale : width;
965
+ } else {
966
+ scale = scale === 0 ? 1 : scale;
967
+ height = height === 0 ? this.pixelsToUom(info.height) : height;
968
+ width = width === 0 ? this.pixelsToUom(info.width) : width;
969
+ height = height * scale;
970
+ width = width * scale;
971
+ }
972
+ if (width + left > this._pageWidth) {
973
+ this.lastError = `The image width ${width} plus the left position ${left} is greater than the page width ${this._pageWidth}`;
974
+ this.lastResult = "0";
975
+ return;
976
+ }
977
+ if (height + top > this._pageHeight) {
978
+ this.lastError = `The image height ${height} plus the top position ${top} is greater than the page height ${this._pageHeight}`;
979
+ this.lastResult = "0";
980
+ return;
981
+ }
982
+ this._pdfDocument.addImage(
983
+ currentImage,
984
+ info.format,
985
+ left + this._marginLeft,
986
+ top + this._marginTop,
987
+ width,
988
+ height
989
+ );
990
+ this.posnX = left + width + this.spaceHoz;
991
+ this.posnY = top + height + this.spaceVert;
992
+ this.lastImageIndex = imageNo;
993
+ this.lastObjectHeight = height;
994
+ this.lastObjectWidth = width;
995
+ this.lastResult = "1";
996
+ }
997
+ drawText(input) {
998
+ const subs = this.logAndParseCommand(".drawText", input);
999
+ const { first: left, rest: rest1 } = getNextNumber(subs);
1000
+ const { first: top, rest: rest2 } = getNextNumber(rest1);
1001
+ if (!this.checkPosition(left, top)) {
1002
+ return;
1003
+ }
1004
+ const maxWidth = this.pageWidth - left;
1005
+ const lines = this._pdfDocument.splitTextToSize(rest2, maxWidth);
1006
+ this.lastObjectWidth = 0;
1007
+ this.lastResult = "1";
1008
+ if (lines.length > 1) {
1009
+ this.lastError = "Text was truncated to fit within the available width";
1010
+ this.lastResult = "0";
1011
+ if (lines[0]) {
1012
+ if (this._pdfDocument.getTextWidth(lines[0]) < maxWidth) {
1013
+ lines[0] += "...";
1014
+ } else if (lines[0].length > 3) {
1015
+ lines[0] = lines[0].substring(0, lines[0].length - 3) + "...";
1016
+ }
1017
+ }
1018
+ }
1019
+ if (lines.length > 0) {
1020
+ this._pdfDocument.text(
1021
+ lines[0] ? lines[0].trimEnd() : "",
1022
+ left + this._marginLeft,
1023
+ top + this._marginTop + this.fontHeight * 0.5 / this.lineHeightFactor,
1024
+ { baseline: "middle" }
1025
+ );
1026
+ this.lastObjectWidth = this._pdfDocument.getTextWidth(
1027
+ lines[0] ? lines[0].trimEnd() : ""
1028
+ );
1029
+ }
1030
+ this.lastObjectHeight = this.fontHeight * this.lineHeightFactor;
1031
+ this.posnX = left + this.lastObjectWidth + this.spaceHoz;
1032
+ this.posnY = top + this.lastObjectHeight + this.spaceVert;
1033
+ }
1034
+ checkPosition(left, top) {
1035
+ if (isNaN(left)) {
1036
+ this.lastError = `Horizontal position '${left}' is not a number`;
1037
+ this.lastResult = "0";
1038
+ return false;
1039
+ }
1040
+ if (isNaN(top)) {
1041
+ this.lastError = `Vertical position '${top}' is not a number`;
1042
+ this.lastResult = "0";
1043
+ return false;
1044
+ }
1045
+ if (left < 0 || top < 0) {
1046
+ this.lastError = "Neither the horizontal nor vertical positions can be negative";
1047
+ this.lastResult = "0";
1048
+ return false;
1049
+ }
1050
+ if (left > this._pageWidth) {
1051
+ this.lastError = `Horizontal position ${left} is greater than the available page width ${this._pageWidth}`;
1052
+ this.lastResult = "0";
1053
+ return false;
1054
+ }
1055
+ if (top > this._pageHeight) {
1056
+ this.lastError = `Vertical position ${top} is greater than the page height ${this._pageHeight}`;
1057
+ this.lastResult = "0";
1058
+ return false;
1059
+ }
1060
+ return true;
1061
+ }
1062
+ drawTextBox(input) {
1063
+ const subs = this.logAndParseCommand(".drawTextBox", input);
1064
+ const { first: left, rest: rest1 } = getNextNumber(subs);
1065
+ const { first: top, rest: rest2 } = getNextNumber(rest1);
1066
+ const { first: width, rest: rest3 } = getNextNumber(rest2);
1067
+ const { first: height, rest: rest4 } = getNextNumber(rest3);
1068
+ let { first: alignH, rest: rest5 } = getNextString(rest4);
1069
+ let { first: alignV, rest: text } = getNextString(rest5);
1070
+ if (!this.checkPosition(left, top)) {
1071
+ return;
1072
+ }
1073
+ if (width <= 0) {
1074
+ this.lastError = "Width must be greater than 0.";
1075
+ this.lastResult = "0";
1076
+ return;
1077
+ }
1078
+ if (height <= 0) {
1079
+ this.lastError = "Height must be greater than 0.";
1080
+ this.lastResult = "0";
1081
+ return;
1082
+ }
1083
+ if (left + width > this.pageWidth) {
1084
+ this.lastError = `Left position (${left}) plus width (${width}) is greater than the page width (${this.pageWidth}).`;
1085
+ this.lastResult = "0";
1086
+ return;
1087
+ }
1088
+ if (top + height > this.pageHeight) {
1089
+ this.lastError = `Top position (${top}) plus height (${height}) is greater than the page height (${this.pageHeight}).`;
1090
+ this.lastResult = "0";
1091
+ return;
1092
+ }
1093
+ alignH = alignH.toLocaleLowerCase().trim();
1094
+ if (alignH === "") {
1095
+ this.lastError = "Horizontal alignment is required.";
1096
+ this.lastResult = "0";
1097
+ return;
1098
+ }
1099
+ alignV = alignV.toLocaleLowerCase().trim();
1100
+ if (alignV === "") {
1101
+ this.lastError = "Vertical alignment is required";
1102
+ this.lastResult = "0";
1103
+ return;
1104
+ }
1105
+ if (text === "") {
1106
+ this.lastError = "Text is required.";
1107
+ this.lastResult = "0";
1108
+ return;
1109
+ }
1110
+ let horzAlign = "center";
1111
+ let horzAdjust = 0;
1112
+ let vertAlign = "top";
1113
+ switch (alignH.substring(0, 1)) {
1114
+ case "l":
1115
+ horzAlign = "left";
1116
+ break;
1117
+ case "r":
1118
+ horzAlign = "right";
1119
+ horzAdjust = width;
1120
+ break;
1121
+ case "c":
1122
+ horzAlign = "center";
1123
+ horzAdjust = width * 0.5;
1124
+ break;
1125
+ default:
1126
+ this.lastError = `Invalid horizontal alignment value '${alignH}'.`;
1127
+ this.lastResult = "0";
1128
+ return;
1129
+ }
1130
+ switch (alignV.substring(0, 1)) {
1131
+ case "t":
1132
+ vertAlign = "top";
1133
+ break;
1134
+ case "c":
1135
+ vertAlign = "center";
1136
+ break;
1137
+ case "b":
1138
+ vertAlign = "bottom";
1139
+ break;
1140
+ default:
1141
+ this.lastError = `Invalid vertical alignment value '${alignV}'.`;
1142
+ this.lastResult = "0";
1143
+ return;
1144
+ }
1145
+ const lines = this._pdfDocument.splitTextToSize(text, width);
1146
+ let textHeight = this.fontHeight * lines.length;
1147
+ while (textHeight > height) {
1148
+ this._logger.warn(
1149
+ `Text does not fit within the box, dropped '${lines[lines.length - 1]}'`
1150
+ );
1151
+ lines.pop();
1152
+ textHeight = this.fontHeight * lines.length * this.lineHeightFactor;
1153
+ }
1154
+ if (lines.length === 0) {
1155
+ this.lastError = "Text cannot fit within the box";
1156
+ this.lastResult = "0";
1157
+ return;
1158
+ }
1159
+ let adjustTop = 0;
1160
+ if (vertAlign === "center") {
1161
+ adjustTop = (height - textHeight) / 2;
1162
+ } else if (vertAlign === "bottom") {
1163
+ adjustTop = height - textHeight;
1164
+ }
1165
+ this._pdfDocument.text(
1166
+ lines,
1167
+ left + this._marginLeft + horzAdjust,
1168
+ top + this._marginTop + adjustTop + this.fontHeight * 0.5 / this.lineHeightFactor,
1169
+ { align: horzAlign, baseline: "middle" }
1170
+ );
1171
+ this.lastObjectHeight = height;
1172
+ this.lastObjectWidth = width;
1173
+ this.posnX = left + this.lastObjectWidth + this.spaceHoz;
1174
+ this.posnY = top + this.lastObjectHeight + this.spaceVert;
1175
+ this.lastResult = "1";
1176
+ }
1177
+ drawTextWrapped(jsPdfDynamo, input) {
1178
+ return __async(this, null, function* () {
1179
+ const subs = this.logAndParseCommand(".drawTextWrapped", input);
1180
+ const { first: left, rest: rest1 } = getNextNumber(subs);
1181
+ const { first: top, rest: rest2 } = getNextNumber(rest1);
1182
+ const { first: maxWidth, rest: rest3 } = getNextNumber(rest2);
1183
+ let { first: cmdGroup, rest: text } = getNextString(rest3);
1184
+ if (!this.checkPosition(left, top)) {
1185
+ return;
1186
+ }
1187
+ if (maxWidth <= 0) {
1188
+ this.lastError = "Maximum width must be greater than 0";
1189
+ this.lastResult = "0";
1190
+ return;
1191
+ }
1192
+ if (text === "") {
1193
+ this.lastError = "No text has been provided";
1194
+ this.lastResult = "0";
1195
+ return;
1196
+ }
1197
+ let lastObjectHeight = 0;
1198
+ text = text.replace("\\n", " \n").replace("\\N", " \n") + " ";
1199
+ this.posnY = top;
1200
+ const lines = this._pdfDocument.splitTextToSize(text, maxWidth) || [];
1201
+ this._logger.trace(`Text was wrapped into ${lines.length} lines`, lines);
1202
+ while (lines.length > 0) {
1203
+ if (!cmdGroup.startsWith("*")) {
1204
+ yield jsPdfDynamo.processGroups(this, cmdGroup, false);
1205
+ }
1206
+ this.drawText(
1207
+ `${left.toFixed(2)} ${this.posnY.toFixed(2)} ${lines[0] ? lines[0].trimEnd() : ""}`
1208
+ );
1209
+ lines.shift();
1210
+ lastObjectHeight += this.fontHeight * this.lineHeightFactor;
1211
+ if (this.posnY > this.pageHeight && text !== "" && cmdGroup.startsWith("*")) {
1212
+ this.addPage();
1213
+ this.posnY = 0;
1214
+ }
1215
+ }
1216
+ this.posnX = left + maxWidth + this.spaceHoz;
1217
+ this.lastObjectHeight = lastObjectHeight;
1218
+ this.lastObjectWidth = maxWidth;
1219
+ });
1220
+ }
1221
+ forEachPage(jsPdfDynamo, input) {
1222
+ return __async(this, null, function* () {
1223
+ const subs = this.logAndParseCommand(".forEachPage", input);
1224
+ for (let ix = 1; ix <= this.pageCount; ix++) {
1225
+ this._pdfDocument.setPage(ix);
1226
+ this.currentPageNumber = ix;
1227
+ yield jsPdfDynamo.processGroups(this, subs);
1228
+ }
1229
+ this.lastResult = "1";
1230
+ });
1231
+ }
1232
+ ifBlank(jsPdfDynamo, input) {
1233
+ return __async(this, null, function* () {
1234
+ let { first: variable, rest } = getNextString(input);
1235
+ let subs = this.substitute(rest.trim());
1236
+ this._logger.debug(".ifBlank " + variable + " " + subs);
1237
+ let value = this._variables.get(variable.toLocaleUpperCase()) || "";
1238
+ this.lastResult = "-1";
1239
+ if (value.trim() === "") {
1240
+ yield jsPdfDynamo.processDot(this, rest);
1241
+ }
1242
+ });
1243
+ }
1244
+ ifEq(jsPdfDynamo, input) {
1245
+ return __async(this, null, function* () {
1246
+ const { first: value1, rest: rest1 } = getNextString(input);
1247
+ const { first: value2, rest: rest2 } = getNextString(rest1);
1248
+ const subs = this.substitute(rest2.trim());
1249
+ this._logger.debug(`.ifEq ${value1} ${value2} ${subs}`);
1250
+ const variable1 = this.substitute(value1);
1251
+ const variable2 = this.substitute(value2);
1252
+ this.lastResult = "0";
1253
+ if (!Number(variable1) || !Number(variable2)) {
1254
+ let compareResult = variable1.localeCompare(variable2);
1255
+ if (compareResult === 0) {
1256
+ yield jsPdfDynamo.processDot(this, subs);
1257
+ }
1258
+ } else {
1259
+ if (Number(variable1) === Number(variable2)) {
1260
+ yield jsPdfDynamo.processDot(this, subs);
1261
+ }
1262
+ }
1263
+ });
1264
+ }
1265
+ ifNe(jsPdfDynamo, input) {
1266
+ return __async(this, null, function* () {
1267
+ const { first: value1, rest: rest1 } = getNextString(input);
1268
+ const { first: value2, rest: rest2 } = getNextString(rest1);
1269
+ const subs = this.substitute(rest2.trim());
1270
+ this._logger.debug(`.ifNe ${value1} ${value2} ${subs}`);
1271
+ const variable1 = this.substitute(value1);
1272
+ const variable2 = this.substitute(value2);
1273
+ this.lastResult = "0";
1274
+ if (!Number(variable1) || !Number(variable2)) {
1275
+ let compareResult = variable1.localeCompare(variable2);
1276
+ if (compareResult !== 0) {
1277
+ yield jsPdfDynamo.processDot(this, subs);
1278
+ }
1279
+ } else {
1280
+ if (Number(variable1) !== Number(variable2)) {
1281
+ yield jsPdfDynamo.processDot(this, subs);
1282
+ }
1283
+ }
1284
+ });
1285
+ }
1286
+ ifGt(jsPdfDynamo, input) {
1287
+ return __async(this, null, function* () {
1288
+ const { first: value1, rest: rest1 } = getNextString(input);
1289
+ const { first: value2, rest: rest2 } = getNextString(rest1);
1290
+ const subs = this.substitute(rest2.trim());
1291
+ this._logger.debug(`.ifGt ${value1} ${value2} ${subs}`);
1292
+ const variable1 = this.substitute(value1);
1293
+ const variable2 = this.substitute(value2);
1294
+ this.lastResult = "0";
1295
+ if (!Number(variable1) || !Number(variable2)) {
1296
+ let compareResult = variable1.localeCompare(variable2);
1297
+ if (compareResult > 0) {
1298
+ yield jsPdfDynamo.processDot(this, rest2);
1299
+ }
1300
+ } else {
1301
+ if (Number(variable1) > Number(variable2)) {
1302
+ yield jsPdfDynamo.processDot(this, rest2);
1303
+ }
1304
+ }
1305
+ });
1306
+ }
1307
+ ifNotBlank(jsPdfDynamo, input) {
1308
+ return __async(this, null, function* () {
1309
+ let { first: variable, rest } = getNextString(input);
1310
+ const subs = this.substitute(rest.trim());
1311
+ this._logger.debug(".ifNotBlank " + variable + " " + subs);
1312
+ let value = this._variables.get(variable.toLocaleUpperCase()) || "";
1313
+ this.lastResult = "-1";
1314
+ if (value.trim() !== "") {
1315
+ yield jsPdfDynamo.processDot(this, rest);
1316
+ }
1317
+ });
1318
+ }
1319
+ incCurrentX(input) {
1320
+ let subs = this.logAndParseCommand(".incCurrentX", input);
1321
+ while (subs.length > 0) {
1322
+ const { first: value, rest } = getNextNumber(subs);
1323
+ subs = rest;
1324
+ if (!Number.isNaN(value)) {
1325
+ this.posnX = this.posnX + value;
1326
+ }
1327
+ }
1328
+ this.lastResult = "1";
1329
+ if (this.posnX < 0) {
1330
+ this.posnX = 0;
1331
+ this.lastError = "X Position resulted in negative value, adjusted to 0";
1332
+ }
1333
+ if (this.posnX > this._pageWidth) {
1334
+ this.posnX = this._pageWidth;
1335
+ this.lastError = "X Position exceeded page width, adjusted to page width";
1336
+ }
1337
+ }
1338
+ incCurrentY(input) {
1339
+ let subs = this.logAndParseCommand(".incCurrentY", input);
1340
+ while (subs.length > 0) {
1341
+ const { first: value, rest } = getNextNumber(subs);
1342
+ subs = rest;
1343
+ if (!Number.isNaN(value)) {
1344
+ this.posnY += value;
1345
+ }
1346
+ }
1347
+ this.lastResult = "1";
1348
+ if (this.posnY < 0) {
1349
+ this.posnY = 0;
1350
+ this.lastError = "Y Position resulted in negative value, adjusted to 0";
1351
+ }
1352
+ if (this.posnY > this._pageHeight) {
1353
+ this.posnY = this._pageHeight;
1354
+ this.lastError = "Y Position exceeded page height, adjusted to page height";
1355
+ }
1356
+ }
1357
+ incVar(input) {
1358
+ const subs = this.logAndParseCommand(".incVar", input);
1359
+ let { first: varName, rest } = getNextString(subs.toLocaleUpperCase());
1360
+ if (varName === "") {
1361
+ this.lastResult = "0";
1362
+ this.lastError = "IncVar must reference a variable";
1363
+ return;
1364
+ }
1365
+ if (varName.startsWith("_")) {
1366
+ this.lastResult = "0";
1367
+ this.lastError = "IncVar can not be used to update system maintained variables";
1368
+ return;
1369
+ }
1370
+ let varValue = this._variables.get(varName);
1371
+ if (!varValue) {
1372
+ this.lastResult = "0";
1373
+ this.lastError = "Variable '" + varName + "' is not defined";
1374
+ return;
1375
+ }
1376
+ if (isNaN(Number(varValue))) {
1377
+ this._variables.set(varName, "0");
1378
+ }
1379
+ while (rest.length > 0) {
1380
+ const { first: nextOp, rest: remainder } = getNextNumber(rest, 4);
1381
+ rest = remainder;
1382
+ let varValue2 = this._variables.get(varName);
1383
+ if (!isNaN(Number(varValue2)) && !isNaN(Number(nextOp))) {
1384
+ this._variables.set(
1385
+ varName,
1386
+ removeTrailingZeros((Number(varValue2) + nextOp).toFixed(4))
1387
+ );
1388
+ }
1389
+ }
1390
+ this.lastResult = "1";
1391
+ this._logger.trace(
1392
+ "Variable " + varName + " incremented to " + this._variables.get(varName)
1393
+ );
1394
+ }
1395
+ multVar(input) {
1396
+ let subs = this.substitute(input.trim());
1397
+ this._logger.debug(".multVar " + subs);
1398
+ let { first: varName, rest } = getNextString(subs.toLocaleUpperCase());
1399
+ if (varName === "") {
1400
+ this.lastResult = "0";
1401
+ this.lastError = "MultVar must reference a variable";
1402
+ return;
1403
+ }
1404
+ if (varName.startsWith("_")) {
1405
+ this.lastResult = "0";
1406
+ this.lastError = "MultVar can not be used to update system maintained variables";
1407
+ return;
1408
+ }
1409
+ let varValue = this._variables.get(varName);
1410
+ if (!varValue) {
1411
+ this.lastResult = "0";
1412
+ this.lastError = "Variable '" + varName + "' is not defined";
1413
+ return;
1414
+ }
1415
+ if (isNaN(Number(varValue))) {
1416
+ this._variables.set(varName, "0");
1417
+ }
1418
+ while (rest.length > 0) {
1419
+ const { first: nextOp, rest: remainder } = getNextNumber(rest, 4);
1420
+ rest = remainder;
1421
+ let varValue2 = this._variables.get(varName);
1422
+ if (!isNaN(Number(varValue2)) && !isNaN(Number(nextOp))) {
1423
+ this._variables.set(
1424
+ varName,
1425
+ removeTrailingZeros((Number(varValue2) * Number(nextOp)).toFixed(4))
1426
+ );
1427
+ }
1428
+ varValue2 = this._variables.get(varName);
1429
+ }
1430
+ this.lastResult = "1";
1431
+ this._logger.trace(
1432
+ "Variable " + varName + " incremented to " + this._variables.get(varName)
1433
+ );
1434
+ }
1435
+ savePdf(input) {
1436
+ let subs = this.logAndParseCommand(".savePdf", input.trim());
1437
+ if (isBrowser()) {
1438
+ this.lastError = "SavePdf is not supported in the browser";
1439
+ this.lastResult = "0";
1440
+ return;
1441
+ }
1442
+ if (subs.length === 0) {
1443
+ subs = "Document";
1444
+ }
1445
+ if (!subs.toLocaleUpperCase().endsWith(".PDF")) {
1446
+ subs = subs + ".pdf";
1447
+ }
1448
+ try {
1449
+ this._pdfDocument.save(subs);
1450
+ this.lastResult = "1";
1451
+ } catch (ex) {
1452
+ this._logger.error("Problem saving to " + subs);
1453
+ this.lastResult = "0";
1454
+ }
1455
+ }
1456
+ selectPage(input) {
1457
+ const subs = this.logAndParseCommand(".selectPage", input);
1458
+ const { first: pageNo } = getNextNumber(subs);
1459
+ if (!subs) {
1460
+ this.lastError = "A page number must be supplied";
1461
+ this.lastResult = "0";
1462
+ return;
1463
+ }
1464
+ if (isNaN(pageNo) || pageNo <= 0 || pageNo > this.pageCount) {
1465
+ this.lastError = "The page number must be in the range of 1 to " + this.pageCount;
1466
+ this.lastResult = "0";
1467
+ return;
1468
+ }
1469
+ this._pdfDocument.setPage(pageNo);
1470
+ this.currentPageNumber = pageNo;
1471
+ this.lastResult = pageNo.toString();
1472
+ this.posnX = 0;
1473
+ this.posnY = 0;
1474
+ }
1475
+ setCurrentFont(fontName, fontStyle) {
1476
+ this._pdfDocument.setFont(fontName, fontStyle);
1477
+ }
1478
+ setCurrentX(input) {
1479
+ const subs = this.logAndParseCommand(".setCurrentX", input);
1480
+ const { first: x } = getNextNumber(subs);
1481
+ this.posnX = x;
1482
+ this.lastResult = "1";
1483
+ }
1484
+ setCurrentY(input) {
1485
+ const subs = this.logAndParseCommand(".setCurrentY", input);
1486
+ const { first: y } = getNextNumber(subs);
1487
+ this.posnY = y;
1488
+ this.lastResult = "1";
1489
+ }
1490
+ setDocumentInfo(input) {
1491
+ let subs = this.substitute(input);
1492
+ this._logger.debug(".setDocumentInfo " + subs);
1493
+ let { first, rest } = getNextString(subs);
1494
+ this.lastResult = "1";
1495
+ switch (first.toLocaleLowerCase()) {
1496
+ case "application":
1497
+ this._pdfDocument.setProperties({ application: rest });
1498
+ break;
1499
+ case "author":
1500
+ this._pdfDocument.setProperties({ author: rest });
1501
+ break;
1502
+ case "creator":
1503
+ this._pdfDocument.setProperties({ creator: rest });
1504
+ break;
1505
+ case "keywords":
1506
+ this._pdfDocument.setProperties({ keywords: rest });
1507
+ break;
1508
+ case "subject":
1509
+ this._pdfDocument.setProperties({ subject: rest });
1510
+ break;
1511
+ case "title":
1512
+ this._pdfDocument.setProperties({ title: rest });
1513
+ break;
1514
+ default:
1515
+ this.lastResult = "0";
1516
+ this.lastError = "Unknown document info field " + first;
1517
+ break;
1518
+ }
1519
+ }
1520
+ setFillColour(input) {
1521
+ let subs = this.substitute(input);
1522
+ this._logger.debug(".setFillColour " + subs);
1523
+ this.fillColour = subs;
1524
+ this.lastResult = "1";
1525
+ }
1526
+ setFontName(input) {
1527
+ const subs = this.logAndParseCommand(".setFontName", input);
1528
+ const { first: fontName } = getNextString(subs);
1529
+ if (fontName === "") {
1530
+ this.lastResult = "0";
1531
+ this.lastError = "A font name must be specified";
1532
+ return;
1533
+ }
1534
+ this.fontName = fontName;
1535
+ this.lastResult = "1";
1536
+ }
1537
+ setFontSize(input) {
1538
+ const subs = this.logAndParseCommand(".setFontSize", input);
1539
+ let { first: size } = getNextNumber(subs);
1540
+ if (size > 0) {
1541
+ this.fontPointSize = size;
1542
+ this.lastResult = "1";
1543
+ } else {
1544
+ this.lastResult = "0";
1545
+ this.lastError = "Invalid font size " + size;
1546
+ }
1547
+ }
1548
+ setFontStyle(input) {
1549
+ const subs = this.logAndParseCommand(".setFontStyle", input);
1550
+ const { first: fontStyle } = getNextString(subs.toLocaleLowerCase());
1551
+ if (fontStyle === "") {
1552
+ this.lastResult = "0";
1553
+ this.lastError = "A font style must be specified";
1554
+ return;
1555
+ }
1556
+ if (!isValidFontStyle(fontStyle)) {
1557
+ this.lastResult = "0";
1558
+ this.lastError = "Invalid font style " + fontStyle;
1559
+ return;
1560
+ }
1561
+ this.fontStyle = fontStyle;
1562
+ this.lastResult = "1";
1563
+ }
1564
+ setLineColour(input) {
1565
+ let subs = this.substitute(input);
1566
+ this._logger.debug(".setLineColour " + subs);
1567
+ this.lineColour = subs;
1568
+ this.lastResult = "1";
1569
+ }
1570
+ setLineWidth(input) {
1571
+ const subs = this.logAndParseCommand(".setLineWidth", input);
1572
+ const { first: width } = getNextNumber(subs);
1573
+ if (!Number.isNaN(width) && width > 0) {
1574
+ this.lineWidth = width;
1575
+ this.lastResult = "1";
1576
+ } else {
1577
+ this.lastResult = "0";
1578
+ this.lastError = `Invalid line width 'width'`;
1579
+ }
1580
+ }
1581
+ setLogLevel(input) {
1582
+ const subs = this.logAndParseCommand(".setLogLevel", input);
1583
+ const { first: logLevel } = getNextString(subs);
1584
+ if (!this._logger.logLevel) {
1585
+ this.lastResult = "0";
1586
+ this.lastError = "The logger does not support setting the log level.";
1587
+ return;
1588
+ }
1589
+ if (logLevel === "") {
1590
+ this.lastResult = "0";
1591
+ this.lastError = "A log level must be specified.";
1592
+ return;
1593
+ }
1594
+ if (Number.isNaN(Number(logLevel))) {
1595
+ this._logger.logLevel(logLevel);
1596
+ } else {
1597
+ this._logger.logLevel(Number(logLevel));
1598
+ }
1599
+ this.lastResult = "1";
1600
+ }
1601
+ setMargin(input) {
1602
+ this.lastResult = "1";
1603
+ let subs = this.substitute(input);
1604
+ this._logger.debug(".setMargin " + subs);
1605
+ const { first: marginType, rest } = getNextString(subs.toLocaleUpperCase());
1606
+ const { first: size } = getNextNumber(rest);
1607
+ if (marginType.startsWith("A")) {
1608
+ this.marginLeft = size;
1609
+ this.marginRight = size;
1610
+ this.marginTop = size;
1611
+ this.marginBottom = size;
1612
+ } else if (marginType.startsWith("H")) {
1613
+ this.marginLeft = size;
1614
+ this.marginRight = size;
1615
+ } else if (marginType.startsWith("V")) {
1616
+ this.marginTop = size;
1617
+ this.marginBottom = size;
1618
+ } else if (marginType.startsWith("L")) {
1619
+ this.marginLeft = size;
1620
+ } else if (marginType.startsWith("R")) {
1621
+ this.marginRight = size;
1622
+ } else if (marginType.startsWith("T")) {
1623
+ this.marginTop = size;
1624
+ } else if (marginType.startsWith("B")) {
1625
+ this.marginBottom = size;
1626
+ } else {
1627
+ this.lastResult = "0";
1628
+ }
1629
+ }
1630
+ setPageOrientation(input) {
1631
+ let subs = this.substitute(input);
1632
+ const { first: orientation } = getNextString(subs.toLocaleLowerCase());
1633
+ this.lastResult = "1";
1634
+ if (orientation.startsWith("l")) {
1635
+ this.pageOrientation = "landscape";
1636
+ } else if (orientation.startsWith("p")) {
1637
+ this.pageOrientation = "portrait";
1638
+ } else {
1639
+ this.lastResult = "0";
1640
+ this.lastError = `Invalid page orientation '${orientation}'.`;
1641
+ }
1642
+ }
1643
+ setPageSize(input) {
1644
+ let subs = this.substitute(input);
1645
+ const { first: ps } = getNextString(subs.toLocaleLowerCase());
1646
+ if (ps === "") {
1647
+ this.lastResult = "0";
1648
+ this.lastError = "A page size must be specified";
1649
+ return;
1650
+ }
1651
+ if (isValidPageSize(ps)) {
1652
+ this.pageSize = ps;
1653
+ this.lastResult = "1";
1654
+ } else {
1655
+ this.lastResult = "0";
1656
+ this.lastError = "Invalid page size " + ps;
1657
+ }
1658
+ }
1659
+ setSpaceHoz(input) {
1660
+ const subs = this.logAndParseCommand(".setSpaceHoz", input);
1661
+ const { first: size } = getNextNumber(subs);
1662
+ this.spaceHoz = size;
1663
+ this.lastResult = "1";
1664
+ }
1665
+ setSpaceVert(input) {
1666
+ const subs = this.logAndParseCommand(".setSpaceVert", input);
1667
+ const { first: size } = getNextNumber(subs);
1668
+ this.spaceVert = size;
1669
+ this.lastResult = "1";
1670
+ }
1671
+ setTextColour(input) {
1672
+ const subs = this.logAndParseCommand(".setTextColour", input);
1673
+ this.textColour = subs;
1674
+ this.lastResult = "1";
1675
+ }
1676
+ copyVar(input) {
1677
+ let subs = this.substitute(input);
1678
+ this._logger.debug(".copyVar " + subs);
1679
+ const { first: varName, rest: fromVar } = getNextString(
1680
+ subs.toLocaleUpperCase()
1681
+ );
1682
+ if (varName === "" || fromVar === "") {
1683
+ this.lastResult = "0";
1684
+ this.lastError = "The CopyVar command requires two variable names to be specified";
1685
+ } else if (varName.startsWith("_")) {
1686
+ this.lastError = "The CopyVar command can not be used to update system maintained variables";
1687
+ this.lastResult = "0";
1688
+ } else {
1689
+ let value = this._variables.get(fromVar);
1690
+ if (value) {
1691
+ this._variables.set(varName, value);
1692
+ this.lastResult = "1";
1693
+ } else {
1694
+ this._variables.set(varName, "");
1695
+ this.lastResult = "0";
1696
+ this.lastError = "Variable '" + fromVar + "' is not defined";
1697
+ }
1698
+ }
1699
+ }
1700
+ getVar(variableName) {
1701
+ const value = this._variables.get(variableName.toLocaleUpperCase());
1702
+ this.lastResult = value ? "1" : "0";
1703
+ this.lastError = value ? this.lastError : "Variable '" + variableName + "' is not defined";
1704
+ return value || "";
1705
+ }
1706
+ setVar(input) {
1707
+ let subs = this.substitute(input);
1708
+ this._logger.debug(".setVar " + subs);
1709
+ let { first: varName, rest } = getNextString(subs);
1710
+ varName = varName.toLocaleUpperCase();
1711
+ if (varName === "") {
1712
+ this.lastError = "The SetVar command requires a variable name to be specified";
1713
+ this.lastResult = "0";
1714
+ return;
1715
+ }
1716
+ if (varName.startsWith("_")) {
1717
+ this.lastError = "The SetVar command can not be used to modify system maintained variables";
1718
+ this.lastResult = "0";
1719
+ return;
1720
+ }
1721
+ this._variables.set(varName, rest);
1722
+ this.lastResult = "1";
1723
+ }
1724
+ substitute(input) {
1725
+ let result = input;
1726
+ let upperInput = input.toUpperCase();
1727
+ let subsDelimiter = "%";
1728
+ let ix = upperInput.indexOf(subsDelimiter);
1729
+ do {
1730
+ if (ix === upperInput.length - 1) {
1731
+ break;
1732
+ }
1733
+ let iy = upperInput.indexOf(subsDelimiter, ix + 1);
1734
+ if (iy === -1) {
1735
+ break;
1736
+ }
1737
+ if (iy === ix + 1) {
1738
+ upperInput = upperInput.slice(0, ix) + upperInput.slice(ix + 1);
1739
+ result = result.slice(0, ix) + result.slice(ix + 1);
1740
+ if (ix === upperInput.length - 1) {
1741
+ break;
1742
+ }
1743
+ ix++;
1744
+ ix = upperInput.indexOf(subsDelimiter, ix);
1745
+ continue;
1746
+ }
1747
+ let valueName = upperInput.substring(ix + 1, iy).trim();
1748
+ let value = this._variables.get(valueName) || "";
1749
+ result = result.slice(0, ix) + result.slice(iy + 1);
1750
+ if (ix === upperInput.length - 1) {
1751
+ result = result + value;
1752
+ break;
1753
+ }
1754
+ result = result.slice(0, ix) + value + result.slice(ix);
1755
+ upperInput = result.toUpperCase();
1756
+ ix = ix + value.length;
1757
+ ix = upperInput.indexOf(subsDelimiter, ix);
1758
+ } while (ix > -1);
1759
+ return result;
1760
+ }
1761
+ writeLog(input) {
1762
+ const result = this.substitute(input);
1763
+ const { first: level, rest } = getNextString(result);
1764
+ switch (level.toLocaleLowerCase()) {
1765
+ case "0":
1766
+ case "trace":
1767
+ this._logger.trace(rest);
1768
+ break;
1769
+ case "1":
1770
+ case "debug":
1771
+ this._logger.debug(rest);
1772
+ break;
1773
+ case "2":
1774
+ case "info":
1775
+ this._logger.info(rest);
1776
+ break;
1777
+ case "3":
1778
+ case "warn":
1779
+ this._logger.warn(rest);
1780
+ break;
1781
+ case "4":
1782
+ case "error":
1783
+ this._logger.error(rest);
1784
+ break;
1785
+ }
1786
+ }
1787
+ pixelsToUom(value) {
1788
+ switch (this.currentUom) {
1789
+ case "mm":
1790
+ return pixelsToMm(value);
1791
+ case "in":
1792
+ return pixelsToInches(value);
1793
+ case "pt":
1794
+ return pixelsToPoints(value);
1795
+ }
1796
+ return value;
1797
+ }
1798
+ pointsToUom(points) {
1799
+ switch (this.currentUom) {
1800
+ case "mm":
1801
+ return pointsToMm(points);
1802
+ case "in":
1803
+ return pointsToInches(points);
1804
+ case "pt":
1805
+ return pointsToPixels(points);
1806
+ }
1807
+ return points;
1808
+ }
1809
+ uomToPoints(value) {
1810
+ switch (this.currentUom) {
1811
+ case "mm":
1812
+ return mmToPoints(value);
1813
+ case "in":
1814
+ return inchesToPoints(value);
1815
+ }
1816
+ return value;
1817
+ }
1818
+ setFixedDec(value, places = 2) {
1819
+ return value.toFixed(places);
1820
+ }
1821
+ };
1822
+
1823
+ // src/jsPdfDynamo.ts
1824
+ var _groups, _appLogger;
1825
+ var JsPdfDynamo = class {
1826
+ constructor(options = {}, logger = null) {
1827
+ __privateAdd(this, _groups, {});
1828
+ __privateAdd(this, _appLogger);
1829
+ __privateSet(this, _appLogger, new AppLogger(logger));
1830
+ this._processor = this.prepareNewPdf(options, __privateGet(this, _appLogger));
1831
+ }
1832
+ toBlob() {
1833
+ try {
1834
+ const result = this._processor.PdfDocument.output("blob");
1835
+ return result;
1836
+ } catch (e) {
1837
+ __privateGet(this, _appLogger).warn(
1838
+ "Attempt to generate a blob from an empty PDF stream."
1839
+ );
1840
+ return null;
1841
+ }
1842
+ }
1843
+ toBlobUrl() {
1844
+ try {
1845
+ const result = this._processor.PdfDocument.output(
1846
+ "bloburi",
1847
+ "application/pdf"
1848
+ );
1849
+ return result;
1850
+ } catch (e) {
1851
+ __privateGet(this, _appLogger).warn(
1852
+ "Attempt to generate a URL from an empty PDF stream."
1853
+ );
1854
+ return null;
1855
+ }
1856
+ }
1857
+ getVar(variableName) {
1858
+ var _a;
1859
+ return this._processor ? (_a = this._processor.getVar(variableName)) != null ? _a : null : null;
1860
+ }
1861
+ prepareNewPdf(options, logger) {
1862
+ return new JsPdfProcessor(options, logger);
1863
+ }
1864
+ prepareWrappedString(input) {
1865
+ if (!input) {
1866
+ return "";
1867
+ }
1868
+ return input.replace("%", "%%").replace("\\", "\\\\").replace(/\r?\n/g, "\\n");
1869
+ }
1870
+ processCommands(commands) {
1871
+ return __async(this, null, function* () {
1872
+ if (this._processor && commands && commands.length > 0) {
1873
+ yield this.processTemplate(this._processor, commands);
1874
+ }
1875
+ });
1876
+ }
1877
+ processTemplate(processor, input) {
1878
+ return __async(this, null, function* () {
1879
+ let inGroupProcessing = false;
1880
+ let grpName = "";
1881
+ let currGroup = [];
1882
+ for (let ix = 0; ix < input.length; ix++) {
1883
+ let currLine = input[ix];
1884
+ if (!currLine || currLine.length === 0 || currLine.startsWith(";")) {
1885
+ continue;
1886
+ }
1887
+ if (currLine.startsWith("[")) {
1888
+ if (inGroupProcessing) {
1889
+ inGroupProcessing = false;
1890
+ __privateGet(this, _appLogger).debug(
1891
+ `Finished loading group ${grpName} (${currLine})
1892
+ `
1893
+ );
1894
+ } else {
1895
+ if (currLine.length === 1) continue;
1896
+ grpName = currLine.substring(1);
1897
+ const iy = grpName.indexOf("]");
1898
+ if (iy >= 0) {
1899
+ grpName = grpName.substring(0, iy);
1900
+ }
1901
+ grpName = grpName.trim().toLocaleUpperCase();
1902
+ inGroupProcessing = true;
1903
+ __privateGet(this, _appLogger).debug(`Loading group ${grpName} (${currLine})
1904
+ `);
1905
+ currGroup = [];
1906
+ __privateGet(this, _groups)[grpName] = currGroup;
1907
+ }
1908
+ continue;
1909
+ }
1910
+ if (inGroupProcessing) {
1911
+ currGroup.push(currLine);
1912
+ __privateGet(this, _appLogger).trace(` ${currLine}`);
1913
+ continue;
1914
+ }
1915
+ if (currLine.length > 5 && currLine.substring(0, 6).toLocaleLowerCase() === ".dump ") {
1916
+ continue;
1917
+ }
1918
+ if (currLine.startsWith(".")) {
1919
+ yield this.processDot(processor, currLine);
1920
+ continue;
1921
+ }
1922
+ }
1923
+ });
1924
+ }
1925
+ processDot(processor, currLine) {
1926
+ return __async(this, null, function* () {
1927
+ const input = currLine.substring(1);
1928
+ let { first, rest: parameters } = getNextString(input);
1929
+ first = first.toLowerCase();
1930
+ switch (first) {
1931
+ case "AddBookmark".toLowerCase():
1932
+ processor.addBookmark(parameters);
1933
+ return;
1934
+ case "AddImageFromFile".toLowerCase():
1935
+ processor.addImageFromFile(parameters);
1936
+ return;
1937
+ case "AddImageFromUrl".toLowerCase():
1938
+ yield processor.addImageFromUrl(parameters);
1939
+ return;
1940
+ case "AddPage".toLowerCase():
1941
+ processor.addPage(parameters);
1942
+ return;
1943
+ case "CheckPage".toLowerCase():
1944
+ yield processor.checkPage(this, parameters);
1945
+ return;
1946
+ case "CopyVar".toLowerCase():
1947
+ processor.copyVar(parameters);
1948
+ return;
1949
+ case "Do".toLowerCase():
1950
+ yield this.processGroups(processor, parameters);
1951
+ return;
1952
+ case "DoRepeat".toLowerCase():
1953
+ yield this.processGroupsRepeat(processor, parameters);
1954
+ return;
1955
+ case "DrawBox".toLowerCase():
1956
+ processor.drawBox(parameters);
1957
+ return;
1958
+ case "DrawDebugGrid".toLowerCase():
1959
+ processor.drawDebugGrid(parameters);
1960
+ return;
1961
+ case "DrawImage".toLowerCase():
1962
+ processor.drawImage(parameters);
1963
+ return;
1964
+ case "DrawLine".toLowerCase():
1965
+ processor.drawLine(parameters);
1966
+ return;
1967
+ case "DrawText".toLowerCase():
1968
+ processor.drawText(parameters);
1969
+ return;
1970
+ case "DrawTextBox".toLowerCase():
1971
+ processor.drawTextBox(parameters);
1972
+ return;
1973
+ case "DrawTextWrapped".toLowerCase():
1974
+ yield processor.drawTextWrapped(this, parameters);
1975
+ return;
1976
+ case "ForEachPage".toLowerCase():
1977
+ yield processor.forEachPage(this, parameters);
1978
+ return;
1979
+ case "IfEq".toLowerCase():
1980
+ yield processor.ifEq(this, parameters);
1981
+ return;
1982
+ case "IfBlank".toLowerCase():
1983
+ yield processor.ifBlank(this, parameters);
1984
+ return;
1985
+ case "IfGt".toLowerCase():
1986
+ yield processor.ifGt(this, parameters);
1987
+ return;
1988
+ case "IfNe".toLowerCase():
1989
+ yield processor.ifNe(this, parameters);
1990
+ return;
1991
+ case "IfNotBlank".toLowerCase():
1992
+ yield processor.ifNotBlank(this, parameters);
1993
+ return;
1994
+ case "incCurrentY".toLowerCase():
1995
+ processor.incCurrentY(parameters);
1996
+ return;
1997
+ case "incCurrentX".toLowerCase():
1998
+ processor.incCurrentX(parameters);
1999
+ return;
2000
+ case "Include".toLowerCase():
2001
+ yield this.includeFile(processor, parameters);
2002
+ return;
2003
+ case "IncludeUri".toLowerCase():
2004
+ yield this.includeUri(processor, parameters);
2005
+ return;
2006
+ case "IncVar".toLowerCase():
2007
+ processor.incVar(parameters);
2008
+ return;
2009
+ case "MultVar".toLowerCase():
2010
+ processor.multVar(parameters);
2011
+ return;
2012
+ case "SavePdf".toLowerCase():
2013
+ processor.savePdf(parameters);
2014
+ return;
2015
+ case "SelectPage".toLowerCase():
2016
+ processor.selectPage(parameters);
2017
+ return;
2018
+ case "setCurrentX".toLowerCase():
2019
+ processor.setCurrentX(parameters);
2020
+ return;
2021
+ case "setCurrentY".toLowerCase():
2022
+ processor.setCurrentY(parameters);
2023
+ return;
2024
+ case "SetDocumentInfo".toLowerCase():
2025
+ processor.setDocumentInfo(parameters);
2026
+ return;
2027
+ case "SetFillColor".toLowerCase():
2028
+ case "SetFillColour".toLowerCase():
2029
+ processor.setFillColour(parameters);
2030
+ return;
2031
+ case "SetFontName".toLowerCase():
2032
+ processor.setFontName(parameters);
2033
+ return;
2034
+ case "SetFontSize".toLowerCase():
2035
+ processor.setFontSize(parameters);
2036
+ return;
2037
+ case "SetFontStyle".toLowerCase():
2038
+ processor.setFontStyle(parameters);
2039
+ return;
2040
+ case "SetLineColor".toLowerCase():
2041
+ case "SetLineColour".toLowerCase():
2042
+ processor.setLineColour(parameters);
2043
+ return;
2044
+ case "SetLineWidth".toLowerCase():
2045
+ processor.setLineWidth(parameters);
2046
+ return;
2047
+ case "SetLogLevel".toLowerCase():
2048
+ processor.setLogLevel(parameters);
2049
+ return;
2050
+ case "SetMargin".toLowerCase():
2051
+ processor.setMargin(parameters);
2052
+ return;
2053
+ case "SetSpaceHoz".toLowerCase():
2054
+ processor.setSpaceHoz(parameters);
2055
+ return;
2056
+ case "SetSpaceVert".toLowerCase():
2057
+ processor.setSpaceVert(parameters);
2058
+ return;
2059
+ case "SetTextColour".toLowerCase():
2060
+ case "SetTextColor".toLowerCase():
2061
+ processor.setTextColour(parameters);
2062
+ return;
2063
+ case "SetVar".toLowerCase():
2064
+ processor.setVar(parameters);
2065
+ return;
2066
+ case "WriteLog".toLowerCase():
2067
+ processor.writeLog(parameters);
2068
+ return;
2069
+ default:
2070
+ __privateGet(this, _appLogger).error(`Unknown command: ${input}`);
2071
+ }
2072
+ });
2073
+ }
2074
+ processGroups(processor, input, log = true) {
2075
+ return __async(this, null, function* () {
2076
+ let subs = processor.substitute(input.toLocaleUpperCase());
2077
+ if (log) {
2078
+ __privateGet(this, _appLogger).debug(`.Do ${subs}`);
2079
+ }
2080
+ processor.lastResult = "0";
2081
+ while (subs.length > 0) {
2082
+ let { first: group, rest } = getNextString(subs);
2083
+ subs = rest;
2084
+ __privateGet(this, _appLogger).debug(`
2085
+ [${group}]`);
2086
+ if (__privateGet(this, _groups)[group]) {
2087
+ yield this.processTemplate(processor, __privateGet(this, _groups)[group]);
2088
+ } else {
2089
+ __privateGet(this, _appLogger).warn(`Group ${group} was not found.`);
2090
+ processor.lastResult = "0";
2091
+ }
2092
+ }
2093
+ });
2094
+ }
2095
+ processGroupsRepeat(processor, input, log = true) {
2096
+ return __async(this, null, function* () {
2097
+ let subs = processor.substitute(input).toUpperCase();
2098
+ if (log) {
2099
+ __privateGet(this, _appLogger).debug(`.DoRepeat ${subs}`);
2100
+ }
2101
+ processor.lastResult = "0";
2102
+ let { first: count, rest } = getNextNumber(subs);
2103
+ while (count > 0) {
2104
+ count--;
2105
+ let groups = rest;
2106
+ while (groups.length > 0) {
2107
+ let { first: group, rest: remainder } = getNextString(groups);
2108
+ groups = remainder;
2109
+ __privateGet(this, _appLogger).debug(`
2110
+ [${group}]`);
2111
+ if (__privateGet(this, _groups)[group]) {
2112
+ yield this.processTemplate(processor, __privateGet(this, _groups)[group]);
2113
+ } else {
2114
+ __privateGet(this, _appLogger).warn(`Group ${group} was not found.`);
2115
+ processor.lastResult = "0";
2116
+ }
2117
+ }
2118
+ }
2119
+ });
2120
+ }
2121
+ includeFile(processor, input) {
2122
+ return __async(this, null, function* () {
2123
+ const subs = processor.substitute(input);
2124
+ __privateGet(this, _appLogger).debug(`.include ${subs}`);
2125
+ try {
2126
+ const fs2 = require("fs");
2127
+ let incArray = fs2.readFileSync(subs).toString().split("\n");
2128
+ let incList = incArray.map((line) => line.trim());
2129
+ yield this.processTemplate(processor, incList);
2130
+ __privateGet(this, _appLogger).debug(`${incList.length} lines included from ${subs}`);
2131
+ processor.lastResult = "1";
2132
+ } catch (ex) {
2133
+ let message = "";
2134
+ if (ex instanceof Error && ex.message) {
2135
+ message = `: ${ex.message}`;
2136
+ }
2137
+ __privateGet(this, _appLogger).error(`Unable to load or process file ${subs}${message}`);
2138
+ processor.lastResult = "0";
2139
+ }
2140
+ });
2141
+ }
2142
+ includeUri(processor, input) {
2143
+ return __async(this, null, function* () {
2144
+ const subs = processor.substitute(input);
2145
+ __privateGet(this, _appLogger).debug(`.includeUri ${subs}`);
2146
+ try {
2147
+ const response = yield (0, import_node_fetch.default)(subs, {
2148
+ headers: { Accept: "text/plain;q=0.9, text/*;q=0.8, */*;q=0.7" }
2149
+ });
2150
+ if (!response.ok) {
2151
+ throw new Error(`HTTP status ${response.status}.`);
2152
+ }
2153
+ const body = yield response.text();
2154
+ let incArray = body.split("\n");
2155
+ let incList = incArray.map((line) => line.trim());
2156
+ yield this.processTemplate(processor, incList);
2157
+ __privateGet(this, _appLogger).debug(`${incList.length} lines included from ${subs}`);
2158
+ processor.lastResult = "1";
2159
+ } catch (ex) {
2160
+ let message = "";
2161
+ if (ex instanceof Error && ex.message) {
2162
+ message = `: ${ex.message}`;
2163
+ }
2164
+ __privateGet(this, _appLogger).error(`Unable to load or process URI ${subs}${message}`);
2165
+ processor.lastResult = "0";
2166
+ }
2167
+ });
2168
+ }
2169
+ };
2170
+ _groups = new WeakMap();
2171
+ _appLogger = new WeakMap();
2172
+ // Annotate the CommonJS export names for ESM import in node:
2173
+ 0 && (module.exports = {
2174
+ JsPdfDynamo
2175
+ });