@formancy/report-render-pdf 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,3228 +0,0 @@
1
- import { EPC_CAPTION, EPC_FRAME, EPC_MAX_BYTES, EPC_MAX_VERSION, FACTUR_X, FACTUR_X_PROFILES, MAX_ASSET_BYTES, MAX_ASSET_SIDE, MAX_QR_BILL_ADDITIONAL_INFORMATION, MAX_SVG_COORDINATE, MAX_SVG_DEPTH, MAX_SVG_GROUPS, MAX_SVG_SEGMENTS, QR_BILL_CURRENCIES, QR_BILL_SIZE, QR_BILL_TOP, RenderRefusal, checkQrBillAmount, checkSvg, epcCaptionBreak, epcLeastVersion, epcModule, imageHeader, qrBillPageBreak, sniffImage } from "@formancy/report-runtime";
2
- import { encode } from "uqr";
3
- //#region src/glyphs.ts
4
- /** The face text in this weight and slant prints in. */
5
- function faceOf(bold, italic) {
6
- return bold ? italic ? "bolditalics" : "bold" : italic ? "italics" : "normal";
7
- }
8
- /** A line break: pdfmake breaks the line there and draws nothing for it. */
9
- const LINE_BREAKS = /* @__PURE__ */ new Set([10, 13]);
10
- /** The first character of `text` that `face` has no glyph for, as its code point; undefined when it has a glyph for every one. */
11
- function missingGlyph(text, face) {
12
- for (const character of text) {
13
- const point = character.codePointAt(0);
14
- if (!face.has(point) && !LINE_BREAKS.has(point)) return point;
15
- }
16
- }
17
- /** A code point as Unicode writes it: U+5C71. */
18
- function codePoint(point) {
19
- return `U+${point.toString(16).toUpperCase().padStart(4, "0")}`;
20
- }
21
- /**
22
- * The code points a TrueType font maps to a glyph other than glyph 0, from
23
- * its Unicode BMP character map: the Windows (3, 1) or Unicode (0, 3)
24
- * subtable, in format 4. A font without one is not one this renderer
25
- * embeds, and is an error, not a document's refusal.
26
- */
27
- function characterMap(font) {
28
- const view = new DataView(font.buffer, font.byteOffset, font.byteLength);
29
- const tables = view.getUint16(4);
30
- let cmap;
31
- for (let index = 0; index < tables; index++) {
32
- const record = 12 + 16 * index;
33
- if (String.fromCharCode(...font.subarray(record, record + 4)) === "cmap") cmap = view.getUint32(record + 8);
34
- }
35
- if (cmap === void 0) throw new Error("the font has no character map");
36
- const encodings = view.getUint16(cmap + 2);
37
- for (let index = 0; index < encodings; index++) {
38
- const record = cmap + 4 + 8 * index;
39
- const [platform, encoding] = [view.getUint16(record), view.getUint16(record + 2)];
40
- const subtable = cmap + view.getUint32(record + 4);
41
- if ((platform === 3 && encoding === 1 || platform === 0 && encoding === 3) && view.getUint16(subtable) === 4) return format4(view, subtable);
42
- }
43
- throw new Error("the font has no Unicode character map in format 4");
44
- }
45
- /** A format 4 subtable's segments, each mapping a range of code points by a delta or through the glyph array; glyph 0 is no glyph. */
46
- function format4(view, table) {
47
- const segments = view.getUint16(table + 6) / 2;
48
- const ends = table + 14;
49
- const starts = ends + 2 * segments + 2;
50
- const deltas = starts + 2 * segments;
51
- const offsets = deltas + 2 * segments;
52
- const mapped = /* @__PURE__ */ new Set();
53
- for (let segment = 0; segment < segments; segment++) {
54
- const end = view.getUint16(ends + 2 * segment);
55
- const start = view.getUint16(starts + 2 * segment);
56
- const delta = view.getUint16(deltas + 2 * segment);
57
- const offsetAt = offsets + 2 * segment;
58
- const offset = view.getUint16(offsetAt);
59
- for (let point = start; point <= end; point++) {
60
- const indexed = offset === 0 ? point : view.getUint16(offsetAt + offset + 2 * (point - start));
61
- if ((offset !== 0 && indexed === 0 ? 0 : indexed + delta & 65535) !== 0) mapped.add(point);
62
- }
63
- }
64
- return mapped;
65
- }
66
- //#endregion
67
- //#region src/engine.ts
68
- /** Roboto's faces, as pdfmake names them. */
69
- const FACES = [
70
- "normal",
71
- "bold",
72
- "italics",
73
- "bolditalics"
74
- ];
75
- /** Liberation Sans's, as pdfmake names them. */
76
- const BILL_FACES = ["normal", "bold"];
77
- /**
78
- * What `load` loads, loaded by the first call and kept for every call after
79
- * it: the fonts do not change while the process or the page runs. Calls made
80
- * while it loads share the one load. A load that fails is not kept: the
81
- * calls that shared it fail, and the next call loads again, so that a file
82
- * the process could not open just then, or a chunk the browser could not
83
- * fetch, fails the documents that asked for it and no document after.
84
- */
85
- function loadOnce(load) {
86
- let loading;
87
- return () => loading ??= load().catch((error) => {
88
- loading = void 0;
89
- throw error;
90
- });
91
- }
92
- /** The glyphs of `faces`, from the bytes `read` reads for each. */
93
- async function glyphsOf(faces, read) {
94
- const maps = await Promise.all(faces.map(async (face) => [face, characterMap(await read(face))]));
95
- return Object.fromEntries(maps);
96
- }
97
- /** The glyphs of `faces`, read by `read` the first time they are asked for and kept once every face has been read (`loadOnce`). */
98
- function glyphsOnce(faces, read) {
99
- return loadOnce(() => glyphsOf(faces, read));
100
- }
101
- /**
102
- * The PDF of the document `getStream` hands over, `finish` acting on it
103
- * first: what each entry's `run` does once it has configured its pdfmake.
104
- */
105
- async function written(document, finish) {
106
- const pdf = await document;
107
- finish?.(pdf);
108
- return collect(pdf);
109
- }
110
- /**
111
- * The PDF's bytes, read from PDFKit's stream. pdfmake's own `getBuffer`
112
- * listens for the end of the stream and never for an error, so a stream that
113
- * fails leaves its promise pending forever; this one rejects.
114
- */
115
- function collect(stream) {
116
- return new Promise((resolve, reject) => {
117
- const chunks = [];
118
- stream.on("data", (chunk) => chunks.push(chunk));
119
- stream.on("error", reject);
120
- stream.on("end", () => {
121
- const bytes = new Uint8Array(chunks.reduce((total, chunk) => total + chunk.length, 0));
122
- let offset = 0;
123
- for (const chunk of chunks) {
124
- bytes.set(chunk, offset);
125
- offset += chunk.length;
126
- }
127
- resolve(bytes);
128
- });
129
- stream.end();
130
- });
131
- }
132
- /**
133
- * The smallest module drawn: 0.4 mm, 1.13 pt. ISO/IEC 18004 leaves the
134
- * module's size to the application; SIX's Swiss Implementation Guidelines
135
- * for the QR-bill, version 2.3, section 6.3, require at least 0.4 mm when
136
- * printing, and that is taken here as what a printer prints and a phone's
137
- * camera reads reliably. A square too small for its text at that module is
138
- * refused, naming the size it needs, never drawn finer. It is a borrowed
139
- * minimum: the same guidelines draw their largest code finer (0020).
140
- */
141
- const MIN_MODULE = 28.8 / 25.4;
142
- /**
143
- * The most characters any QR code holds: 7089 digits, version 40 at level
144
- * L (ISO/IEC 18004, table 7). A character is a code point, as a reader
145
- * counts one: an emoji is one, though JavaScript holds it in two code
146
- * units. Longer text fits no version in any mode, and is refused before it
147
- * is encoded, which takes time and memory with the length of the text;
148
- * within it, the encoder decides by the bytes the text takes.
149
- */
150
- const MAX_CHARACTERS = 7089;
151
- const LEVELS = /* @__PURE__ */ new Set([
152
- "L",
153
- "M",
154
- "Q",
155
- "H"
156
- ]);
157
- /** How many code points `text` holds, counted without building them into an array. */
158
- function codePoints(text) {
159
- let count = 0;
160
- for (const _ of text) count++;
161
- return count;
162
- }
163
- /**
164
- * `code`'s symbol, or the refusal that says why it is not drawn: a level or
165
- * text no encoder can draw, as `unsupported`; text no version holds, or a
166
- * square too small for the version that holds it, as `content-too-large`.
167
- * Each names the code by its id. Its size is checked already.
168
- */
169
- function qrSymbol(code) {
170
- const { id, text, size, errorCorrection } = code;
171
- if (!LEVELS.has(errorCorrection)) throw new RenderRefusal("unsupported", `the QR code ${id} asks for the error correction level '${String(errorCorrection)}'; the levels are L, M, Q and H`, id);
172
- if (typeof text !== "string") throw new RenderRefusal("unsupported", `the QR code ${id} encodes something that is not text`, id);
173
- const lone = /\p{Cs}/u.exec(text)?.[0];
174
- if (lone !== void 0) throw new RenderRefusal("unsupported", `the QR code ${id} holds ${codePoint(lone.charCodeAt(0))}, half of a surrogate pair without the other, which has no UTF-8`, id);
175
- const characters = text.length > 7089 ? codePoints(text) : text.length;
176
- if (characters > 7089) throw new RenderRefusal("content-too-large", `the QR code ${id} holds ${characters} characters; no QR code holds more than ${MAX_CHARACTERS}`, id);
177
- const modules = encoded(text, errorCorrection, id);
178
- refuseFineModules({ modules }, size, `the QR code ${id}`, "its text", id);
179
- return { modules };
180
- }
181
- /**
182
- * Refuses `symbol` drawn in a square of `size` with its quiet zone when its
183
- * modules would be finer than 0.4 mm, naming the square `holds` needs:
184
- * the floor every code drawn with a quiet zone is held to (0020).
185
- */
186
- function refuseFineModules(symbol, size, what, holds, id) {
187
- const count = symbol.modules.length + 8;
188
- const smallest = count * MIN_MODULE;
189
- if (size < smallest) throw new RenderRefusal("content-too-large", `${what} is ${size} pt a side, which makes the ${count} modules across its symbol and quiet zone ${(size / count).toFixed(2)} pt each; the smallest module is 0.4 mm (${MIN_MODULE.toFixed(2)} pt), so ${holds} needs a square of at least ${(Math.ceil(smallest * 100) / 100).toFixed(2)} pt`, id);
190
- }
191
- /** The symbol uqr encodes, without its quiet zone; refused when no version holds the text, which uqr 0.1.3 says with this error and no other. */
192
- function encoded(text, level, id) {
193
- try {
194
- return encode(text, {
195
- ecc: level,
196
- border: 0,
197
- boostEcc: false
198
- }).data;
199
- } catch (error) {
200
- if (!(error instanceof RangeError && error.message === "Data too long")) throw error;
201
- throw new RenderRefusal("content-too-large", `the QR code ${id} holds ${new TextEncoder().encode(text).length} bytes of text, more than a QR code at level ${level} holds`, id);
202
- }
203
- }
204
- /**
205
- * The code's square, exactly `size` points a side: white, and over it its
206
- * dark modules in black, one path filled once, each run of them in a row a
207
- * rectangle of it. Drawn in modules, the square's own units, and scaled to
208
- * `size`.
209
- *
210
- * Filled once, because a run filled on its own is blended into the page on
211
- * its own: where two rows meet inside a pixel, each covers part of it, and
212
- * a viewer draws a light line between them. The path is drawn as an SVG,
213
- * because pdfmake 0.3.11 cannot place one in a canvas: its `offsetVector`
214
- * (`helpers/tools.js`) moves a canvas's rectangles, lines and polylines to
215
- * where the canvas stands, never a `path`, which stays at the page's
216
- * corner; and a polyline's points, moved in place, are not put back when a
217
- * page break makes it lay the document out again. An SVG it places as it
218
- * places an image.
219
- */
220
- function qrContent(symbol, size) {
221
- const across = symbol.modules.length + 8;
222
- return {
223
- svg: `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 ${across} ${across}"><rect width="${across}" height="${across}" fill="#ffffff"/><path d="${darkRuns(symbol, 4)}" fill="#000000"/></svg>`,
224
- width: size,
225
- height: size
226
- };
227
- }
228
- /** The symbol's dark modules as one path's subpaths, a rectangle for each run of them in a row, `offset` modules in from the square's corner. */
229
- function darkRuns(symbol, offset) {
230
- const runs = [];
231
- symbol.modules.forEach((row, y) => {
232
- for (let x = 0; x < row.length; x++) {
233
- if (!row[x]) continue;
234
- const start = x;
235
- while (row[x + 1] === true) x++;
236
- const length = x + 1 - start;
237
- runs.push(`M${offset + start} ${offset + y}h${length}v1h-${length}z`);
238
- }
239
- });
240
- return runs.join("");
241
- }
242
- /** Millimetres in points. */
243
- const mm$1 = (value) => value * 72 / 25.4;
244
- /** The largest version SIX allows (IG 6.2): 117 modules a side. */
245
- const SWISS_MAX_VERSION = 25;
246
- /** A Swiss QR Code's side, without a quiet zone, whatever its version (IG 6.4): its modules are this over theirs. */
247
- const SWISS_CODE_SIZE = mm$1(46);
248
- /**
249
- * A QR-bill's Swiss QR Code (IG 6), or the refusal that says why it is not
250
- * drawn: its payload as UTF-8 at level M (6.1), in the smallest version that
251
- * holds it (6.4), and never past version 25 (6.2). A payload of more than
252
- * 997 characters is refused unencoded; one whose UTF-8 is more than version
253
- * 25 holds, once the encoder finds none does. Every refusal names the
254
- * payment part, and none quotes the payload: it holds names and accounts.
255
- *
256
- * SIX prints the code at 46 mm whatever its version, so a module is 46 mm
257
- * over the symbol's modules, 0.393 mm at version 25: finer than the 0.4 mm
258
- * a `qrCode` is held to, which is SIX's own figure for print (6.3). SIX's
259
- * size is drawn, not the floor (0020's generic minimum does not apply).
260
- */
261
- function swissSymbol(payload) {
262
- const refuse = (code, what) => new RenderRefusal(code, `the payment part's Swiss QR Code ${what}`, "paymentPart");
263
- if (typeof payload !== "string") throw refuse("unsupported", "holds something that is not text");
264
- const lone = /\p{Cs}/u.exec(payload)?.[0];
265
- if (lone !== void 0) throw refuse("unsupported", `holds ${codePoint(lone.charCodeAt(0))}, half of a surrogate pair without the other, which has no UTF-8`);
266
- const characters = payload.length > 997 ? codePoints(payload) : payload.length;
267
- if (characters > 997) throw refuse("content-too-large", `holds ${characters} characters; SIX allows 997`);
268
- try {
269
- return { modules: encode(payload, {
270
- ecc: "M",
271
- border: 0,
272
- boostEcc: false,
273
- maxVersion: SWISS_MAX_VERSION
274
- }).data };
275
- } catch (error) {
276
- if (!(error instanceof RangeError && error.message === "Data too long")) throw error;
277
- throw refuse("content-too-large", `holds ${new TextEncoder().encode(payload).length} bytes, more than version ${SWISS_MAX_VERSION} holds at level M, the largest code SIX allows`);
278
- }
279
- }
280
- /**
281
- * The Swiss cross over the code's centre (IG 6.4.2), in millimetres: SIX's
282
- * logo, as schoero's generator draws it, is a white square of 7 mm, a black
283
- * square of 6 mm on it, and a white cross on that, its arms 7/6 mm wide and
284
- * 35/9 mm from end to end. manuelbl's draws the same black square and cross
285
- * on modules it clears, rather than on a white square.
286
- */
287
- const CROSS = {
288
- white: 7,
289
- black: 6,
290
- arm: 7 / 6,
291
- span: 35 / 9
292
- };
293
- /**
294
- * The Swiss QR Code's square, 46 mm a side, without a quiet zone of its own:
295
- * the slip leaves 5 mm unprinted around it (IG 3.5.2, 6.4.1). White, its
296
- * dark modules in black as one path filled once, as a `qrCode`'s are, and
297
- * over them the Swiss cross: its white square, its black square, and its
298
- * white cross, one path. Drawn in modules and scaled to the side.
299
- */
300
- function swissCodeContent(symbol) {
301
- const across = symbol.modules.length;
302
- const unit = across / 46;
303
- const centre = across / 2;
304
- const square = (side, fill) => `<rect x="${centre - side * unit / 2}" y="${centre - side * unit / 2}" width="${side * unit}" height="${side * unit}" fill="${fill}"/>`;
305
- const [arm, span] = [CROSS.arm * unit / 2, CROSS.span * unit / 2];
306
- const cross = `M${[
307
- [-arm, -span],
308
- [arm, -span],
309
- [arm, -arm],
310
- [span, -arm],
311
- [span, arm],
312
- [arm, arm],
313
- [arm, span],
314
- [-arm, span],
315
- [-arm, arm],
316
- [-span, arm],
317
- [-span, -arm],
318
- [-arm, -arm]
319
- ].map(([x, y]) => `${centre + x} ${centre + y}`).join("L")}z`;
320
- const size = SWISS_CODE_SIZE;
321
- return {
322
- svg: `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 ${across} ${across}"><rect width="${across}" height="${across}" fill="#ffffff"/><path d="${darkRuns(symbol, 0)}" fill="#000000"/>${square(CROSS.white, "#ffffff")}${square(CROSS.black, "#000000")}<path d="${cross}" fill="#ffffff"/></svg>`,
323
- width: size,
324
- height: size
325
- };
326
- }
327
- //#endregion
328
- //#region src/bill.ts
329
- /** The longest value a slip prints: a line of the additional information, which the message and the billing information share (IG Table 8). An address line is shorter. */
330
- const MAX_VALUE = MAX_QR_BILL_ADDITIONAL_INFORMATION;
331
- /** An amount as the slip prints it: a space between thousands, a point and two decimals (IG 3.5.3). Which amounts a bill pays is report-spec's `checkQrBillAmount`. */
332
- const AMOUNT = /^\d{1,3}(?: \d{3})*\.\d{2}$/;
333
- /** The lines an address prints: its name, its street and building number, its postal code and town (IG 3.5.4). */
334
- const ADDRESS_LINES = 3;
335
- /** The message and the billing information, each on its line. */
336
- const ADDITIONAL_LINES = 2;
337
- function refuse(what) {
338
- return new RenderRefusal("unsupported", `the payment part's ${what}`, "paymentPart");
339
- }
340
- /**
341
- * Refuses `page` for a slip by report-spec's rule, the one the editor
342
- * refuses it by (`qrBillPageBreak`): a page that is not A4 in portrait,
343
- * which has no foot the slip spans, and one whose top margin, with `above`
344
- * printed under it, reaches into the slip, which no layout can undo.
345
- */
346
- function refusePage(page, above = 0) {
347
- const broken = qrBillPageBreak(page, above);
348
- if (broken !== void 0) throw new RenderRefusal(broken.field === "page" ? "unsupported" : "content-too-large", broken.rule, "paymentPart");
349
- }
350
- /** Refuses what the renderer cannot draw of `bill` on `page`, the top margin alone before the header is measured, and encodes its code. */
351
- function checkBill(bill, page, glyphs) {
352
- const { kind } = bill;
353
- if (kind !== "swissQrBill") throw new RenderRefusal("unsupported", `the payment part is a '${String(kind)}', which the renderer does not know`, "paymentPart");
354
- refusePage(page);
355
- const text = (value, what, face) => {
356
- if (typeof value !== "string") throw refuse(`${what} holds something that is not text`);
357
- if (value.length > MAX_VALUE) throw refuse(`${what} holds a value longer than any SIX allows, ${MAX_VALUE} characters`);
358
- const missing = missingGlyph(value, glyphs[face]);
359
- if (missing !== void 0) throw refuse(`${what} prints ${codePoint(missing)}, which Liberation Sans has no glyph for: it would print as an empty box`);
360
- };
361
- const lines = (value, what, most, least) => {
362
- if (!Array.isArray(value)) throw refuse(`${what} is not lines of text`);
363
- if (value.length > most || value.length < least) throw refuse(`${what} has the wrong number of lines: a slip prints ${least} to ${most}`);
364
- for (const line of value) text(line, what, "normal");
365
- };
366
- const headings = bill.headings ?? {};
367
- for (const [key, face] of Object.entries(HEADING_FACES)) text(headings[key], `heading '${key}'`, face);
368
- text(bill.account, "account", "normal");
369
- lines(bill.creditor, "creditor's address", ADDRESS_LINES, 2);
370
- if (bill.reference !== null) text(bill.reference, "reference", "normal");
371
- lines(bill.additionalInformation, "additional information", ADDITIONAL_LINES, 0);
372
- if (bill.debtor !== null) lines(bill.debtor, "debtor's address", ADDRESS_LINES, 2);
373
- if (!QR_BILL_CURRENCIES.includes(bill.currency)) throw refuse(`currency is not one SIX allows: ${QR_BILL_CURRENCIES.join(" or ")}`);
374
- text(bill.currency, "currency", "normal");
375
- if (bill.amount !== null) {
376
- if (typeof bill.amount !== "string" || !AMOUNT.test(bill.amount)) throw refuse("amount is not written as the slip prints one: its thousands apart and two decimals");
377
- const paid = checkQrBillAmount(bill.amount.replaceAll(" ", ""));
378
- if (!paid.ok) throw refuse(`amount ${paid.rule}`);
379
- text(bill.amount, "amount", "normal");
380
- }
381
- return {
382
- bill,
383
- symbol: swissSymbol(bill.payload)
384
- };
385
- }
386
- /**
387
- * The face each heading a slip prints in, which its glyphs are held to:
388
- * `separate` regular, the rest bold (`slip.ts`). A table over every
389
- * heading, so that one added to the document's `QrBillHeadings` without
390
- * its face does not compile, rather than going unchecked.
391
- */
392
- const HEADING_FACES = {
393
- paymentPart: "bold",
394
- receipt: "bold",
395
- account: "bold",
396
- reference: "bold",
397
- additionalInformation: "bold",
398
- payableBy: "bold",
399
- currency: "bold",
400
- amount: "bold",
401
- acceptancePoint: "bold",
402
- separate: "normal"
403
- };
404
- //#endregion
405
- //#region src/bytes.ts
406
- /**
407
- * Byte arithmetic the renderer needs in Node and in a browser alike, written
408
- * on the standard library alone: neither `Buffer` nor `node:zlib` exists in a
409
- * browser, and the browser entry shares every line of this package but its
410
- * font loading (`browser.ts`).
411
- */
412
- const BASE64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
413
- /** Standard base64 with padding, as a `data:` URL carries bytes. */
414
- function base64(bytes) {
415
- const parts = [];
416
- for (let offset = 0; offset < bytes.length; offset += 3) {
417
- const [a = 0, b = 0, c = 0] = [
418
- bytes[offset],
419
- bytes[offset + 1],
420
- bytes[offset + 2]
421
- ];
422
- const left = bytes.length - offset;
423
- parts.push(BASE64[a >> 2] + BASE64[(a & 3) << 4 | b >> 4] + (left > 1 ? BASE64[(b & 15) << 2 | c >> 6] : "=") + (left > 2 ? BASE64[c & 63] : "="));
424
- }
425
- return parts.join("");
426
- }
427
- /** The bytes standard base64 with padding spells, as pdfmake's virtual files hold fonts; whitespace ignored, anything else not base64 refused. */
428
- function fromBase64(text) {
429
- const digits = text.replace(/\s+/g, "").replace(/=+$/, "");
430
- const bytes = new Uint8Array(Math.floor(digits.length * 3 / 4));
431
- let bits = 0;
432
- let held = 0;
433
- let at = 0;
434
- for (const digit of digits) {
435
- const value = BASE64.indexOf(digit);
436
- if (value === -1) throw new Error("not base64");
437
- bits = bits << 6 | value;
438
- held += 6;
439
- if (held >= 8) {
440
- held -= 8;
441
- bytes[at++] = bits >> held & 255;
442
- }
443
- }
444
- return bytes;
445
- }
446
- /**
447
- * Inflates zlib-wrapped `data` -- a PNG's image data -- with the platform's
448
- * own `DecompressionStream`, handing each chunk to `each` as it arrives and
449
- * stopping, without reading further, once more than `limit` bytes have come
450
- * out: the limit is what the image's header promises, so a PNG whose data
451
- * inflates to gigabytes costs no more than one that keeps its promise.
452
- *
453
- * Data that is not a whole zlib stream is `invalid`, and so is data with
454
- * bytes after the stream's end, which Node's `inflateSync` would ignore and
455
- * the Compression Streams standard refuses: refusing them costs a PNG some
456
- * decoder would have drawn, and keeps Node and a browser in agreement.
457
- */
458
- async function inflate(data, limit, each) {
459
- const reader = new Blob([data]).stream().pipeThrough(new DecompressionStream("deflate")).getReader();
460
- let length = 0;
461
- try {
462
- for (;;) {
463
- const { done, value } = await reader.read();
464
- if (done) return {
465
- kind: "done",
466
- length
467
- };
468
- if (length + value.length > limit) {
469
- await reader.cancel();
470
- return { kind: "too-long" };
471
- }
472
- each(value, length);
473
- length += value.length;
474
- }
475
- } catch {
476
- return { kind: "invalid" };
477
- }
478
- }
479
- //#endregion
480
- //#region src/build.ts
481
- /** The plan of a table nothing measured: a table in a keep-together block or a page region, which no rule breaks. */
482
- const UNPLANNED = {
483
- dontBreakRows: false,
484
- keepWithHeaderRows: 0,
485
- pitches: [],
486
- blocks: []
487
- };
488
- function newBuild(mode, checked, body = {
489
- top: 0,
490
- bottom: 0
491
- }, plans = /* @__PURE__ */ new Map()) {
492
- const { assets, codes, paths } = checked;
493
- return {
494
- mode,
495
- bodyTop: body.top,
496
- bodyBottom: body.bottom,
497
- plans,
498
- assets,
499
- codes,
500
- paths,
501
- imageKeys: /* @__PURE__ */ new Map(),
502
- images: {},
503
- rules: /* @__PURE__ */ new Map(),
504
- measuredRows: /* @__PURE__ */ new Map(),
505
- words: [],
506
- next: 1
507
- };
508
- }
509
- /** Marks `node`, keeping a mark it already has, and returns the mark. */
510
- function mark(node, build) {
511
- return node.headlineLevel ??= build.next++;
512
- }
513
- /** Whether a node with one of `ids`, among those pdfmake has on this page and the next, starts on `page`. */
514
- function startsOnPage(queries, ids, page) {
515
- return [...queries.getFollowingNodesOnPage(), ...queries.getNodesOnNextPage()].some((other) => other.id !== void 0 && ids.has(other.id) && other.startPosition.pageNumber === page);
516
- }
517
- /**
518
- * The page a node handed to pdfmake starts on in its last layout, read from
519
- * the node itself: pdfmake records each node's positions on it, and reports
520
- * the first as the node's `startPosition`. `startsOnPage` asks pdfmake's
521
- * queries, each of which walks every node to the end of the document, so a
522
- * rule per row of a long table made the rules' work grow with the square of
523
- * the table; this is one read. Undefined for a node pdfmake laid out
524
- * nowhere. `pdfmake.test.ts` holds that 0.3.11 still records positions here.
525
- */
526
- function pageOf$1(node) {
527
- return node.positions?.[0]?.pageNumber;
528
- }
529
- //#endregion
530
- //#region src/style.ts
531
- /**
532
- * A document's text styles as pdfmake's: the one place a font token becomes
533
- * a font, and a style becomes pdfmake's properties.
534
- *
535
- * **Fonts.** pdfmake ships one family, Roboto 3.014, under the SIL Open Font
536
- * License 1.1, which allows embedding in documents
537
- * ([0006](../../../docs/decisions/0006-dependencies-and-fonts-allow-public-source-and-licensed-production.md)).
538
- * `sans` is Roboto. `serif` and `mono` have no font here, and a report that
539
- * asks for one is refused as `unsupported` before anything is laid out
540
- * (`check.ts`): printing it in Roboto would be a substitution nobody sees
541
- * until the PDF is read, which plan section 20 rules out. Bold is Roboto
542
- * Medium, the heaviest face pdfmake ships, and italic its italic.
543
- */
544
- /** pdfmake's name for the family a report's own text prints in. */
545
- const ROBOTO = "Roboto";
546
- /**
547
- * pdfmake's name for Liberation Sans 2.1.5, under the SIL Open Font License
548
- * 1.1, which the package ships in its `fonts` directory: the family a
549
- * QR-bill's slip prints in, and nothing else. SIX allows Arial, Frutiger,
550
- * Helvetica and Liberation Sans on a slip (IG 3.4), and Roboto is none of
551
- * them. Regular and bold; SIX allows no italics.
552
- */
553
- const LIBERATION_SANS = "LiberationSans";
554
- /**
555
- * Liberation Sans's ascender and its line, ascender less descender, as
556
- * multiples of the font size: 1854 and 2288 of its 2048 units per em, from
557
- * its `hhea` table, Arial's metrics. pdfmake sets a line's baseline its
558
- * ascender below the line's top, and lays the line out its line tall times
559
- * the node's `lineHeight`.
560
- */
561
- const LIBERATION_ASCENDER = 1854 / 2048;
562
- const LIBERATION_LINE = 2288 / 2048;
563
- /** The font each token prints in; a token without one is refused. */
564
- const FONTS = { sans: ROBOTO };
565
- /**
566
- * Roboto's line, as a multiple of the font size: its ascender less its
567
- * descender, 2400 of its 2048 units per em. pdfmake lays out a line exactly
568
- * this tall.
569
- */
570
- const LINE_FACTOR = 2400 / 2048;
571
- /** A colour as the document writes one, and as pdfmake reads one: `#` and six lower-case hex digits. */
572
- const COLOR = /^#[0-9a-f]{6}$/;
573
- /** pdfmake's text properties for a style, the renderer's own defaults under it. Only what is set is written. */
574
- function textProperties(style, defaults) {
575
- const bold = style.bold ?? defaults.bold;
576
- const italic = style.italic ?? defaults.italic;
577
- return {
578
- fontSize: style.size ?? defaults.size,
579
- ...style.font === void 0 ? {} : { font: FONTS[style.font] },
580
- ...bold === void 0 ? {} : { bold },
581
- ...italic === void 0 ? {} : { italics: italic },
582
- ...style.color === void 0 ? {} : { color: style.color }
583
- };
584
- }
585
- //#endregion
586
- //#region src/epc.ts
587
- /**
588
- * An EPC QR code (EPC069-12 v3.1), encoded by uqr and drawn as a QR code
589
- * is (0020): its payload as UTF-8 at level M, in a symbol of version 13 at
590
- * most, encoded once when the document is checked, its dark modules one
591
- * path filled once over a white square exactly its size.
592
- *
593
- * Without a caption it is a QR code's square, its quiet zone of four
594
- * modules inside it, held to the 0.4 mm floor. With Austria's caption it
595
- * is the PSA's (PSA v3.0 5), laid out by report-spec's `epc-print.ts`, the
596
- * one place its rules are decided: modules of 15 to 20 mil, a frame of
597
- * half a module with corners of two, four modules from the symbol, and
598
- * "Zahlen mit Code" at 7 pt in Liberation Sans, reading from bottom to top
599
- * on the right. In a square the author sized, the version that just holds
600
- * a payload may have modules over 20 mil: the code is drawn at the least
601
- * version that prints (`epcLeastVersion`), a larger symbol of the same
602
- * payload at the same level.
603
- *
604
- * Every refusal names the code by its id, and none quotes the payload: it
605
- * holds a name and an account.
606
- */
607
- /** The version `symbol` is, from its modules a side (ISO/IEC 18004: 4 a version and 17). */
608
- const versionOf = (symbol) => (symbol.modules.length - 17) / 4;
609
- /**
610
- * `code`'s symbol, or the refusal that says why it is not drawn: a caption
611
- * the renderer does not know, or a payload that is not text, as
612
- * `unsupported`; a payload past 331 bytes, refused unencoded when it is
613
- * longer than that in characters, or modules the square cannot print, as
614
- * `content-too-large`. Its size is checked already.
615
- */
616
- function epcSymbol(code) {
617
- const { id, payload, size, caption } = code;
618
- const what = `the EPC QR code ${id}`;
619
- if (caption !== void 0 && caption !== "zahlenMitCode") throw new RenderRefusal("unsupported", `${what} asks for the caption '${String(caption)}', which the renderer does not know`, id);
620
- if (typeof payload !== "string") throw new RenderRefusal("unsupported", `${what} holds something that is not text`, id);
621
- const lone = /\p{Cs}/u.exec(payload)?.[0];
622
- if (lone !== void 0) throw new RenderRefusal("unsupported", `${what} holds ${codePoint(lone.charCodeAt(0))}, half of a surrogate pair without the other, which has no UTF-8`, id);
623
- if (payload.length > EPC_MAX_BYTES) throw new RenderRefusal("content-too-large", `${what} holds more than the ${EPC_MAX_BYTES} bytes the EPC allows`, id);
624
- const square = caption === void 0 ? void 0 : epcCaptionBreak(size);
625
- if (square !== void 0) throw new RenderRefusal("content-too-large", `${what} cannot be printed as the PSA prints it: ${square}`, id);
626
- const least = epcLeastVersion(size, caption);
627
- let symbol;
628
- try {
629
- symbol = { modules: encode(payload, {
630
- ecc: "M",
631
- border: 0,
632
- boostEcc: false,
633
- minVersion: least,
634
- maxVersion: EPC_MAX_VERSION
635
- }).data };
636
- } catch (error) {
637
- if (!(error instanceof RangeError && error.message === "Data too long")) throw error;
638
- throw new RenderRefusal("content-too-large", `${what} holds ${new TextEncoder().encode(payload).length} bytes, more than version ${EPC_MAX_VERSION} holds at level M, the largest code the EPC allows`, id);
639
- }
640
- if (caption === void 0) {
641
- refuseFineModules(symbol, size, what, "its payload", id);
642
- return symbol;
643
- }
644
- const version = epcCaptionBreak(size, versionOf(symbol));
645
- if (version !== void 0) throw new RenderRefusal("content-too-large", `${what} cannot be printed as the PSA prints it: ${version}`, id);
646
- return symbol;
647
- }
648
- /**
649
- * Between each end of the caption and the frame's right line, which is
650
- * broken where the caption stands: one module. The PSA's figure leaves
651
- * about that, and gives no number.
652
- */
653
- const CAPTION_GAP = 1;
654
- /**
655
- * Fails the render on anything the SVG converter would otherwise only
656
- * warn about and draw past: above all a face it could not open, which it
657
- * would replace by whatever face it last drew in, without a word.
658
- */
659
- function refuseWarning(warning) {
660
- throw new Error(`pdfmake's SVG converter could not draw an EPC QR code's caption as written: ${warning}`);
661
- }
662
- /** The code's square: a QR code's without a caption, the PSA's with one. */
663
- function epcContent(symbol, code) {
664
- return code.caption === void 0 ? qrContent(symbol, code.size) : captionedContent(symbol, code.size);
665
- }
666
- /**
667
- * A captioned code's square, `size` points a side, drawn in points: white,
668
- * the frame, the symbol's dark modules as one path, and the caption.
669
- *
670
- * Across, from the left, it is what `epcModule` counts: the frame's line,
671
- * half a module; four modules; the symbol; four modules; and the caption's
672
- * band, 7 pt, which holds the caption and the frame's right line along
673
- * its baseline, the line's outer edge the square's right edge. So the
674
- * frame spans the square's width. Down, the frame is the symbol and four
675
- * and a half modules above and below it, less than the square by the
676
- * band and half a module, and stands in the middle of the square's
677
- * height. The caption reads from bottom to top, its letters' tops towards
678
- * the symbol, centred on the symbol and no longer than it (report-spec
679
- * refuses a version whose symbol is shorter), and the frame's right line
680
- * is broken a module beyond each end of it.
681
- *
682
- * The caption is text, drawn by pdfmake's SVG converter in Liberation
683
- * Sans: it is in the PDF's text, and a reader finds it.
684
- *
685
- * What that takes of a 30 mm square (85.04 pt), measured on the PDF on 17
686
- * October 2026 (`epc-qr-code.test.ts`): the EPC's first example drawn in
687
- * version 8, modules of 0.479 mm; across, 8.5 modules and the band, 18.54
688
- * pt, so that the symbol is 78.2 % of the side; down, 9 modules, with
689
- * 3.16 pt of the square white above the frame and below it. At its
690
- * corners the frame, rounded by two modules as the PSA's figure is, comes
691
- * within 3.49 modules of both of the symbol's edges -- 4.93 from its
692
- * corner, straight -- and so half a module into the square of four
693
- * modules ISO/IEC 18004 keeps quiet; along the sides, four.
694
- */
695
- function captionedContent(symbol, size) {
696
- const modules = symbol.modules.length;
697
- const module = epcModule(size, versionOf(symbol), "zahlenMitCode");
698
- const line = EPC_FRAME.line * module;
699
- const inset = line + EPC_FRAME.distance * module;
700
- const side = modules * module;
701
- const frame = side + 2 * inset;
702
- const top = (size - frame) / 2;
703
- const [left, right, upper, lower] = [
704
- line / 2,
705
- size - line / 2,
706
- top + line / 2,
707
- top + frame - line / 2
708
- ];
709
- const radius = EPC_FRAME.radius * module;
710
- const centre = top + inset + side / 2;
711
- const broken = EPC_CAPTION.advance * EPC_CAPTION.size / 2 + CAPTION_GAP * module;
712
- const corner = (x, y) => `A${radius} ${radius} 0 0 1 ${x} ${y}`;
713
- const path = `M${right} ${centre + broken}V${lower - radius}${corner(right - radius, lower)}H${left + radius}${corner(left, lower - radius)}V${upper + radius}${corner(left + radius, upper)}H${right - radius}${corner(right, upper + radius)}V${centre - broken}`;
714
- return {
715
- svg: [
716
- `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 ${size} ${size}">`,
717
- `<rect width="${size}" height="${size}" fill="#ffffff"/>`,
718
- `<path d="${path}" fill="none" stroke="#000000" stroke-width="${line}"/>`,
719
- `<path transform="translate(${inset} ${top + inset}) scale(${module})" d="${darkRuns(symbol, 0)}" fill="#000000"/>`,
720
- `<text transform="translate(${right} ${centre}) rotate(-90)" text-anchor="middle" font-family="${LIBERATION_SANS}" font-size="${EPC_CAPTION.size}" fill="#000000">${EPC_CAPTION.words}</text>`,
721
- "</svg>"
722
- ].join(""),
723
- width: size,
724
- height: size,
725
- options: { warningCallback: refuseWarning }
726
- };
727
- }
728
- //#endregion
729
- //#region src/svg-content.ts
730
- /**
731
- * An SVG asset as pdfmake draws it (0030): the drawing `checkSvg` accepted,
732
- * handed to the SVG converter pdfmake 0.3.11 vendors, svg-to-pdfkit, as the
733
- * very text that was approved, in the image's box. The converter fits the
734
- * drawing's viewBox into the box itself, centred: `contain` is its
735
- * `xMidYMid meet`, all of the drawing as large as the box allows, and
736
- * `cover` its `xMidYMid slice`, the box filled and what falls outside it
737
- * clipped by the outer svg's viewport, which the converter clips to
738
- * (`pdfmake.test.ts` holds both). Nothing is drawn outside the box.
739
- *
740
- * What decides is the check: bytes that are not exactly what `cleanSvg`
741
- * writes never get this far (`assets.ts`). Two guards stand behind it, so
742
- * that a bug in the cleaner does not reach the converter as it would a
743
- * customer's file:
744
- *
745
- * - **The renderer's own list of elements.** Before it is handed on, the
746
- * text is held to the elements a cleaned drawing may hold, written here
747
- * and not taken from report-spec's tables, so that the two would have to
748
- * be wrong together: printable ASCII, no entity, and every tag one of
749
- * `DRAWN`. A link, an image, text, `use`, a style sheet, a comment or a
750
- * DOCTYPE is refused.
751
- * - **Callbacks that throw.** The converter would open an `<image>`'s file
752
- * past pdfmake's local access policy, or a virtual file in a browser, and
753
- * draws on past what it cannot read, saying so only to the console. Its
754
- * `imageCallback` and `warningCallback` throw instead, and its
755
- * `documentCallback` is left unset, so that it follows no reference out of
756
- * the drawing. They do not stop a link: the converter writes a link
757
- * annotation for an `<a>` whatever its callbacks say (`pdfmake.test.ts`),
758
- * which is why the list above refuses one.
759
- */
760
- /** The elements of a drawing in the form `cleanSvg` writes (0030), the renderer's own copy: it may refuse more than report-spec's tables, never less, and `svg-threats.test.ts` holds it to them. */
761
- const DRAWN = /* @__PURE__ */ new Set([
762
- "svg",
763
- "g",
764
- "defs",
765
- "path",
766
- "rect",
767
- "circle",
768
- "ellipse",
769
- "line",
770
- "polyline",
771
- "polygon",
772
- "linearGradient",
773
- "radialGradient",
774
- "stop",
775
- "clipPath"
776
- ]);
777
- /** A tag's name as a refusal may repeat it: short, and nothing but a name's characters. */
778
- const NAME = /^[A-Za-z][A-Za-z0-9:._-]{0,63}$/;
779
- /**
780
- * What in `svg` the renderer never hands the converter, or nothing: a
781
- * character that is not printable ASCII, an entity, or a tag -- an end tag,
782
- * a comment, a DOCTYPE or a processing instruction among them -- that is
783
- * not one of `DRAWN`.
784
- */
785
- function foreignMarkup(svg) {
786
- if (/[^\x20-\x7e]/.test(svg)) return "a character that is not printable ASCII";
787
- if (svg.includes("&")) return "an entity";
788
- for (const [, name = ""] of svg.matchAll(/<\/?([^\s/>]*)/g)) if (!DRAWN.has(name)) return NAME.test(name) ? `the element ${name}` : "markup that is not an element";
789
- }
790
- /**
791
- * The converter's options for the asset `id` drawn as `fit` says: the
792
- * viewBox fitted into the box, and both callbacks refusing the asset.
793
- * Neither repeats what the converter was handed: a callback is what holds
794
- * only where the check has failed, and then the drawing may hold anything
795
- * -- a file's path, an id, a word -- which the converter's warnings quote.
796
- */
797
- function converterOptions(id, fit) {
798
- return {
799
- preserveAspectRatio: fit === "cover" ? "xMidYMid slice" : "xMidYMid meet",
800
- imageCallback: () => {
801
- throw new RenderRefusal("invalid-asset", `the image asset ${id} asks pdfmake's SVG converter to open an image, which the renderer never lets it do`, id);
802
- },
803
- warningCallback: () => {
804
- throw new RenderRefusal("invalid-asset", `pdfmake's SVG converter could not draw the image asset ${id} as it was approved: it warned, and the renderer draws an SVG whole or not at all`, id);
805
- }
806
- };
807
- }
808
- /** The drawings that have passed the list: one in a page region is built anew for every page, and read once. */
809
- const PASSED = /* @__PURE__ */ new WeakSet();
810
- /** `image`, an SVG whose drawing the checks read as `vector`, as pdfmake's node: the drawing in the image's box, guarded and under the converter's options. */
811
- function svgContent(image, vector) {
812
- const { id } = image.asset;
813
- if (!PASSED.has(vector)) {
814
- const foreign = foreignMarkup(vector.svg);
815
- if (foreign !== void 0) throw new RenderRefusal("invalid-asset", `the image asset ${id} holds ${foreign}, which the renderer never hands pdfmake's SVG converter`, id);
816
- PASSED.add(vector);
817
- }
818
- return {
819
- svg: vector.svg,
820
- width: image.width,
821
- height: image.height,
822
- options: converterOptions(id, image.fit)
823
- };
824
- }
825
- //#endregion
826
- //#region src/breaks.ts
827
- /** Rows that close what is above them: a group's footer, a total. */
828
- const CLOSING = /* @__PURE__ */ new Set(["groupFooter", "total"]);
829
- /**
830
- * The blocks of rows of these kinds that stand on one page, overlapping
831
- * ones merged, in order. Closing rows are kept with the row before them only
832
- * when `closing`: a table whose rows may split across pages has no row
833
- * height to keep them by.
834
- */
835
- function keepBlocks(kinds, closing) {
836
- const blocks = [];
837
- kinds.forEach((kind, index) => {
838
- if (kind === "groupHeader" && index + 1 < kinds.length) blocks.push({
839
- first: index,
840
- last: index + 1
841
- });
842
- const before = kinds[index - 1];
843
- if (!closing || !CLOSING.has(kind) || before === void 0 || CLOSING.has(before) || before !== "detail" && before !== "empty") return;
844
- let last = index;
845
- while (kinds[last + 1] !== void 0 && CLOSING.has(kinds[last + 1])) last++;
846
- const anchor = index - 1;
847
- blocks.push({
848
- first: kinds[anchor - 1] === "groupHeader" ? anchor - 1 : anchor,
849
- last
850
- });
851
- });
852
- const merged = [];
853
- for (const block of blocks.sort((a, b) => a.first - b.first)) {
854
- const previous = merged.at(-1);
855
- if (previous !== void 0 && block.first <= previous.last) merged[merged.length - 1] = {
856
- first: previous.first,
857
- last: Math.max(previous.last, block.last)
858
- };
859
- else merged.push(block);
860
- }
861
- return merged;
862
- }
863
- /** The rows' height from `first` to `last`, each row's pitch being its height and the rule under it. */
864
- function blockHeight(pitches, block) {
865
- return pitches.slice(block.first, block.last + 1).reduce((sum, pitch) => sum + pitch, 0);
866
- }
867
- /** The blocks a table's rules can keep: each fits under the repeated header, and starts after the rows that move with it. */
868
- function keptBlocks(blocks, pitches, keepWithHeaderRows, room) {
869
- return blocks.filter((block) => block.first > keepWithHeaderRows && blockHeight(pitches, block) <= room);
870
- }
871
- /** A height closer than this to what is left of a page could fall either way in pdfmake's arithmetic: the plan stops there and leaves the rest to the rules. */
872
- const UNSURE = .01;
873
- /**
874
- * The rows, from `first` on, that the `blocks`' rules will break before,
875
- * laid out row after row as pdfmake lays out rows it keeps whole: a row
876
- * that does not fit in what is left of a page starts the next one. `sure`
877
- * is false when a height came too close to the foot of a page to say, and
878
- * the breaks are then those before it.
879
- */
880
- function plannedBreaks(pitches, blocks, first, geometry) {
881
- const { continued, bottom } = geometry;
882
- const starts = new Map(blocks.map((block) => [block.first, block]));
883
- const breaks = [];
884
- let y = geometry.top;
885
- /** Whether `height` fits below `y`, or undefined when that is too close to say. */
886
- const fits = (height) => {
887
- const left = bottom - y - height;
888
- return Math.abs(left) < UNSURE ? void 0 : left > 0;
889
- };
890
- for (let row = first; row < pitches.length; row++) {
891
- const fitting = fits(pitches[row]);
892
- if (fitting === void 0) return {
893
- breaks,
894
- sure: false
895
- };
896
- if (!fitting) y = continued;
897
- const block = starts.get(row);
898
- if (block !== void 0 && y > continued + UNSURE) {
899
- const whole = fits(blockHeight(pitches, block));
900
- if (whole === void 0) return {
901
- breaks,
902
- sure: false
903
- };
904
- if (!whole) {
905
- breaks.push(row);
906
- y = continued;
907
- }
908
- }
909
- y += pitches[row];
910
- }
911
- return {
912
- breaks,
913
- sure: true
914
- };
915
- }
916
- /** Where each row from `first` on stands when no rule breaks the table: how pdfmake lays out rows it keeps whole. */
917
- function naturalLayout(pitches, first, geometry) {
918
- const placed = [];
919
- let [y, page] = [geometry.top, 0];
920
- for (let row = first; row < pitches.length; row++) {
921
- const moves = y + pitches[row] > geometry.bottom;
922
- if (moves) [y, page] = [geometry.continued, page + 1];
923
- placed.push({
924
- page,
925
- top: y,
926
- first: moves || row === first
927
- });
928
- y += pitches[row];
929
- }
930
- return placed;
931
- }
932
- //#endregion
933
- //#region src/table-rules.ts
934
- function tableRules(rows, plan, build, continued) {
935
- const forced = /* @__PURE__ */ new Set();
936
- const ruled = plan.blocks.flatMap((block) => {
937
- const starts = printing(rows[block.first]);
938
- const end = rows.slice(block.first + 1, block.last + 1).findLast((row) => printing(row).length > 0);
939
- if (starts.length === 0 || end === void 0) return [];
940
- const ends = printing(end);
941
- for (const cell of [...starts, ...ends]) cell.id ??= `row-${build.next++}`;
942
- for (const cell of starts) add(cell, (node) => {
943
- const breaks = forced.has(cell) || !ends.some((other) => pageOf$1(other) === node.startPosition.pageNumber);
944
- if (breaks) {
945
- for (const other of starts) if (other !== cell) other.pageBreak = "before";
946
- }
947
- return breaks;
948
- }, build);
949
- return [block];
950
- });
951
- if (continued === void 0 || !plan.dontBreakRows || ruled.length === 0) return;
952
- const rowOf = /* @__PURE__ */ new Map();
953
- rows.forEach((row, index) => {
954
- const [first] = printing(row);
955
- if (first !== void 0 && index > 0) rowOf.set(mark(first, build), index);
956
- });
957
- const hookRow = rows.findIndex((row, index) => index > plan.keepWithHeaderRows && printing(row).length > 0);
958
- if (hookRow === -1 || hookRow > ruled[0].first) return;
959
- const hook = printing(rows[hookRow])[0];
960
- let done = false;
961
- const planning = (node, queries) => {
962
- if (!done) {
963
- done = true;
964
- const geometry = {
965
- top: node.startPosition.top,
966
- continued,
967
- bottom: build.bodyBottom
968
- };
969
- for (const [index, row] of planBreaks(plan, ruled, hookRow, geometry, node, queries, rowOf).entries()) printing(rows[row]).forEach((cell, at) => index === 0 && at === 0 ? forced.add(cell) : cell.pageBreak = "before");
970
- }
971
- return forced.has(hook);
972
- };
973
- add(hook, planning, build);
974
- }
975
- /** The rows the blocks' rules will break before, from row `hookRow` on; none when what pdfmake reports of this page and the next is not what the arithmetic gives. */
976
- function planBreaks(plan, blocks, hookRow, geometry, node, queries, rowOf) {
977
- if (geometry.top + plan.pitches[hookRow] > geometry.bottom) return [];
978
- const placed = naturalLayout(plan.pitches, hookRow, geometry);
979
- const page = node.startPosition.pageNumber;
980
- for (const other of [...queries.getFollowingNodesOnPage(), ...queries.getNodesOnNextPage()]) {
981
- const row = other.headlineLevel === void 0 ? void 0 : rowOf.get(other.headlineLevel);
982
- const at = row === void 0 ? void 0 : placed[row - hookRow];
983
- if (at === void 0 || at.first) continue;
984
- if (other.startPosition.pageNumber !== page + at.page || Math.abs(other.startPosition.top - at.top) > .01) return [];
985
- }
986
- return plannedBreaks(plan.pitches, blocks, hookRow, geometry).breaks;
987
- }
988
- /** Sets `rule` on `cell`'s mark, asked before a rule it has: the planning rule, before the block rule of a row that starts a block. */
989
- function add(cell, rule, build) {
990
- const at = mark(cell, build);
991
- const had = build.rules.get(at);
992
- build.rules.set(at, had === void 0 ? rule : (node, queries) => rule(node, queries) || had(node, queries));
993
- }
994
- /** The cells of a row that have text. */
995
- function printing(row) {
996
- return row.cells.filter((cell) => cell.text.trim() !== "");
997
- }
998
- //#endregion
999
- //#region src/widths.ts
1000
- /**
1001
- * Widths as the renderer hands them to pdfmake: always a number of points.
1002
- * pdfmake widens a column it is handed as `'*'` to its longest word, so a
1003
- * table, a columns block or a frame grew past the page with a long word in
1004
- * it; a fill column is therefore its share of the width worked out here,
1005
- * the one place the check (`check.ts`) and the content (`content.ts`,
1006
- * `table.ts`) take it from.
1007
- */
1008
- /** Points, or nothing for `'fill'`. */
1009
- function fixedWidth(width) {
1010
- return width === "fill" ? 0 : width;
1011
- }
1012
- /** The width each `'fill'` gets of `width`: what the fixed widths leave, shared equally. Infinity when there is none. */
1013
- function fillWidth(widths, width) {
1014
- const fixed = widths.reduce((sum, each) => sum + fixedWidth(each), 0);
1015
- const fills = widths.filter((each) => each === "fill").length;
1016
- return fills === 0 ? Infinity : (width - fixed) / fills;
1017
- }
1018
- /** Each column's width in points, of `width`: a fixed one its own, each fill its share. */
1019
- function columnWidths(widths, width) {
1020
- const fill = fillWidth(widths, width);
1021
- return widths.map((each) => each === "fill" ? fill : each);
1022
- }
1023
- /** The table layout: horizontal rules of half a point, no vertical ones, 4pt of padding at the sides and 2pt above and below. */
1024
- const RULE = .5;
1025
- const TABLE_LAYOUT = {
1026
- hLineWidth: () => RULE,
1027
- vLineWidth: () => 0,
1028
- hLineColor: (index) => index === 1 ? "#000000" : "#bfbfbf",
1029
- paddingLeft: () => 4,
1030
- paddingRight: () => 4,
1031
- paddingTop: () => 2,
1032
- paddingBottom: () => 2
1033
- };
1034
- /** Laid out as one line of text, as wide as a space, that no line break can fall in. */
1035
- const NO_BREAK_SPACE = String.fromCodePoint(160);
1036
- /** The renderer's own style for a row of each kind, under the document's: the column header and every row but a detail row in bold. */
1037
- const KIND_BOLD = {
1038
- header: true,
1039
- empty: false,
1040
- detail: false,
1041
- groupHeader: true,
1042
- groupFooter: true,
1043
- total: true
1044
- };
1045
- /**
1046
- * The content of `table`, standing `width` wide: `kept` inside a keep-together
1047
- * block or a page region, where no rule may break it; `record`ing its cells
1048
- * for the word check; `top` the body's top, outside any frame, where its
1049
- * breaks can be planned (`table-rules.ts`). Every column is handed to pdfmake
1050
- * as a number, a fill column as its share, never as `'*'`, which pdfmake
1051
- * widens to its longest word (`widths.ts`).
1052
- */
1053
- function tableContent(table, build, place) {
1054
- const { kept } = place;
1055
- const measuring = build.mode === "measure";
1056
- const columns = table.columns.length;
1057
- const widths = columnWidths(table.columns.map((column) => column.width), place.width).map((width) => width - 8);
1058
- const across = place.width - 8;
1059
- const cell = (text, column, kind, style, span) => ({
1060
- text: measuring && text === "" ? NO_BREAK_SPACE : text,
1061
- alignment: style.align ?? table.columns[column].align,
1062
- ...textProperties(style, {
1063
- size: 9,
1064
- bold: KIND_BOLD[kind]
1065
- }),
1066
- ...span === void 0 ? {} : { colSpan: span }
1067
- });
1068
- const covered = () => table.columns.slice(1).map((_, index) => cell("", index + 1, "detail", {}));
1069
- const empty = !table.rows.some((row) => row.kind === "detail");
1070
- const rows = [
1071
- {
1072
- kind: "header",
1073
- cells: table.header.map((text, column) => cell(text, column, "header", table.headerStyle ?? {}))
1074
- },
1075
- ...empty ? [{
1076
- kind: "empty",
1077
- cells: [cell(table.emptyText, 0, "empty", { italic: true }, columns), ...covered()]
1078
- }] : [],
1079
- ...table.rows.map((row) => {
1080
- const style = (column) => row.cellStyles?.[column] ?? row.style ?? {};
1081
- if (row.across === true) return {
1082
- kind: row.kind,
1083
- cells: [cell(row.cells[0], 0, row.kind, style(0), columns), ...covered()]
1084
- };
1085
- return {
1086
- kind: row.kind,
1087
- cells: row.cells.map((text, column) => cell(text, column, row.kind, style(column)))
1088
- };
1089
- })
1090
- ];
1091
- if (place.record) recordWords(table, rows, widths, across, build);
1092
- const plan = build.plans.get(table) ?? UNPLANNED;
1093
- if (measuring) build.measuredRows.set(table, rows.map((row) => ({
1094
- kind: row.kind,
1095
- mark: mark(row.cells[0], build)
1096
- })));
1097
- else if (!kept) tableRules(rows, plan, build, place.top === build.bodyTop ? build.bodyTop + RULE + (plan.pitches[0] ?? 0) : void 0);
1098
- return {
1099
- table: {
1100
- headerRows: measuring ? 0 : 1,
1101
- ...measuring || plan.keepWithHeaderRows === 0 ? {} : { keepWithHeaderRows: plan.keepWithHeaderRows },
1102
- ...measuring ? {} : { dontBreakRows: plan.dontBreakRows },
1103
- widths,
1104
- body: rows.map((row) => [...row.cells])
1105
- },
1106
- layout: TABLE_LAYOUT,
1107
- fontSize: 9
1108
- };
1109
- }
1110
- /** Every cell of the table, held to its column's width, or the table's for a cell across it (`words.ts`). */
1111
- function recordWords(table, rows, widths, across, build) {
1112
- let row = 0;
1113
- for (const { kind, cells } of rows) {
1114
- const which = kind === "header" ? `the header of table ${table.id}` : kind === "empty" ? `the empty text of table ${table.id}` : `row ${row++} of table ${table.id}`;
1115
- cells.forEach((cell, column) => {
1116
- if (cell.text === "") return;
1117
- const spans = cell.colSpan !== void 0;
1118
- build.words.push({
1119
- node: cell,
1120
- width: spans ? across : widths[column],
1121
- lines: 1,
1122
- what: spans ? which : `${which}, column ${column + 1}`,
1123
- subject: table.id
1124
- });
1125
- });
1126
- }
1127
- }
1128
- /** How much wider than its room a word may measure and still be laid out unbroken: rounding, not layout. */
1129
- const SLACK = .001;
1130
- /** Refuses the first text node whose widest word, as pdfmake measured it, is wider than its room. Nodes pdfmake has not measured are passed over. */
1131
- function checkWords(rooms) {
1132
- for (const { node, width, lines, what, subject } of rooms) {
1133
- const widest = node._minWidth;
1134
- if (typeof widest !== "number" || widest <= width * lines + SLACK) continue;
1135
- const room = lines === 1 ? `its column holds ${width.toFixed(2)} pt` : `${lines} lines of its width are ${(width * lines).toFixed(2)} pt`;
1136
- throw new RenderRefusal("content-too-large", `a word of ${what} is ${widest.toFixed(2)} pt wide, and ${room}; a word is broken only in a paragraph, and across no more than 16 lines`, subject);
1137
- }
1138
- }
1139
- /** The weight a rectangle's outline is drawn at, inside its box: the table rules' weight. */
1140
- const OUTLINE = .5;
1141
- /** How far a node may start below the top of what it sits under and still be first there: rounding, not layout. */
1142
- const AT_TOP = .5;
1143
- /** Content for the body's blocks, laid out `width` wide, or a page region's when `fields` are given. */
1144
- function contentOf(blocks, build, width, fields) {
1145
- const record = fields === void 0 || build.mode === "measure";
1146
- return sequence(blocks, build, fields === void 0 ? {
1147
- width,
1148
- kept: false,
1149
- top: build.bodyTop,
1150
- record
1151
- } : {
1152
- width,
1153
- kept: true,
1154
- top: 0,
1155
- fields,
1156
- record
1157
- });
1158
- }
1159
- /** Border and padding on each side of a section: what it takes from the width, and from a page's height above and below. */
1160
- function frameOf(section) {
1161
- return (section.border?.thickness ?? 0) + (section.padding ?? 0);
1162
- }
1163
- /** A section with neither border, fill nor padding is its blocks and nothing more. */
1164
- function framed(section) {
1165
- return section.border !== void 0 || section.fill !== void 0 || (section.padding ?? 0) > 0;
1166
- }
1167
- /** The blocks with every section that has no frame replaced by its blocks, which flow as though they stood in its place. */
1168
- function unframed(blocks) {
1169
- return blocks.flatMap((block) => block.kind === "section" && !framed(block) ? unframed(block.blocks) : [block]);
1170
- }
1171
- /**
1172
- * The blocks' content. Outside a kept scope, a keep-with-next paragraph
1173
- * breaks to the next page when the block it is kept with does not start on
1174
- * its page -- unless it is first on its page already, where a break would
1175
- * leave the page empty and the paragraph no better kept on the next.
1176
- */
1177
- function sequence(given, build, scope) {
1178
- const blocks = unframed(given);
1179
- const contents = blocks.map((block) => blockContent(block, build, scope));
1180
- if (build.mode !== "render" || scope.kept) return contents;
1181
- blocks.forEach((block, index) => {
1182
- if (block.kind !== "paragraph" || block.keepWithNext !== true) return;
1183
- const anchor = keptWith(blocks, contents, index);
1184
- if (anchor === void 0) return;
1185
- anchor.id ??= `kept-${build.next++}`;
1186
- const ids = /* @__PURE__ */ new Set([anchor.id]);
1187
- const own = build.next++;
1188
- contents[index].headlineLevel = own;
1189
- build.rules.set(own, (node, queries) => node.startPosition.top > scope.top + AT_TOP && !startsOnPage(queries, ids, node.startPosition.pageNumber));
1190
- });
1191
- return contents;
1192
- }
1193
- /** The first node of `node` that prints text, or an image or a QR code when no text comes first: where pdfmake records the content's start. */
1194
- function anchorOf(node) {
1195
- const inner = node.stack ?? node.columns ?? node.table?.body.flat();
1196
- if (inner !== void 0) {
1197
- for (const each of inner) {
1198
- const anchor = anchorOf(each);
1199
- if (anchor !== void 0) return anchor;
1200
- }
1201
- return;
1202
- }
1203
- return (typeof node.text === "string" ? node.text.trim() !== "" : Array.isArray(node.text)) || node.image !== void 0 || node.svg !== void 0 ? node : void 0;
1204
- }
1205
- /**
1206
- * Where the block a keep-with-next paragraph at `index` stays with starts:
1207
- * the anchor of the next block that prints text, an image or a QR code,
1208
- * past spacers, rules, rectangles and other keep-with-next paragraphs, so
1209
- * that a run of headings moves as one. None when a page break or the end of
1210
- * the list comes first: a heading over nothing is not kept with anything.
1211
- */
1212
- function keptWith(blocks, contents, index) {
1213
- for (let next = index + 1; next < blocks.length; next++) {
1214
- const block = blocks[next];
1215
- if (block.kind === "pageBreak") return void 0;
1216
- const anchor = block.kind === "paragraph" && block.keepWithNext === true ? void 0 : anchorOf(contents[next]);
1217
- if (anchor !== void 0) return anchor;
1218
- }
1219
- }
1220
- function blockContent(block, build, scope) {
1221
- switch (block.kind) {
1222
- case "paragraph": return paragraphContent(block, build, scope);
1223
- case "table": return tableContent(block, build, scope);
1224
- case "image": return imageContent(block, build);
1225
- case "qrCode": return qrContent(build.codes.get(block), block.size);
1226
- case "epcQrCode": return epcContent(build.codes.get(block), block);
1227
- case "rule": return ruleContent(block, scope.width);
1228
- case "rectangle": return rectangleContent(block);
1229
- case "spacer": return {
1230
- stack: [],
1231
- margin: [
1232
- 0,
1233
- block.height,
1234
- 0,
1235
- 0
1236
- ]
1237
- };
1238
- case "pageBreak": return {
1239
- stack: [],
1240
- pageBreak: "before"
1241
- };
1242
- case "keepTogether": return {
1243
- stack: sequence(block.blocks, build, {
1244
- ...scope,
1245
- kept: true
1246
- }),
1247
- unbreakable: build.mode === "render"
1248
- };
1249
- case "columns": return columnsContent(block, build, scope);
1250
- case "section": return sectionContent(block, build, scope);
1251
- }
1252
- }
1253
- function paragraphContent(paragraph, build, scope) {
1254
- const style = paragraph.style ?? {};
1255
- const content = {
1256
- text: paragraph.runs.length === 0 ? "" : paragraph.runs.map((run) => inline(run, scope.fields)),
1257
- alignment: style.align ?? "left",
1258
- ...textProperties(style, { size: 10 })
1259
- };
1260
- const at = build.paths.get(paragraph);
1261
- if (scope.record) build.words.push({
1262
- node: content,
1263
- width: scope.width,
1264
- lines: 16,
1265
- what: at,
1266
- subject: at
1267
- });
1268
- return content;
1269
- }
1270
- function inline(run, fields) {
1271
- if ("text" in run) return run.bold === void 0 ? { text: run.text } : {
1272
- text: run.text,
1273
- bold: run.bold
1274
- };
1275
- if (fields === void 0) throw new Error(`a ${run.field} field outside a page region`);
1276
- return { text: String(fields[run.field]) };
1277
- }
1278
- /**
1279
- * An image in its box, which the layout reserves whole. An SVG is drawn in
1280
- * the box itself, by pdfmake's SVG converter, which fits and centres it
1281
- * (`svg-content.ts`). For a PNG or a JPEG, `cover` is pdfmake's own: the box
1282
- * clipped, the image scaled to fill it and centred. `contain` is drawn at
1283
- * the size the box allows at the image's proportions, read from its pixels,
1284
- * and centred in the box by margins that make up the rest of it.
1285
- */
1286
- function imageContent(image, build) {
1287
- const checked = build.assets.get(image.asset);
1288
- if (checked.kind === "vector") return svgContent(image, checked);
1289
- const key = imageKey(image.asset, build);
1290
- if (image.fit === "cover") return {
1291
- image: key,
1292
- cover: {
1293
- width: image.width,
1294
- height: image.height,
1295
- align: "center",
1296
- valign: "center"
1297
- }
1298
- };
1299
- const scale = Math.min(image.width / checked.width, image.height / checked.height);
1300
- const [width, height] = [checked.width * scale, checked.height * scale];
1301
- const [x, y] = [(image.width - width) / 2, (image.height - height) / 2];
1302
- return {
1303
- image: key,
1304
- width,
1305
- height,
1306
- margin: [
1307
- x,
1308
- y,
1309
- image.width - width - x,
1310
- y
1311
- ]
1312
- };
1313
- }
1314
- function imageKey(asset, build) {
1315
- const known = build.imageKeys.get(asset);
1316
- if (known !== void 0) return known;
1317
- const key = `image${build.imageKeys.size}`;
1318
- build.imageKeys.set(asset, key);
1319
- build.images[key] = `data:${asset.mediaType};base64,${base64(asset.bytes)}`;
1320
- return key;
1321
- }
1322
- /**
1323
- * pdfmake makes a canvas as tall as its lowest point and strokes a line half
1324
- * its width to either side: the line half its width down, and the other half
1325
- * of it in the margin below.
1326
- */
1327
- function ruleContent(rule, width) {
1328
- const half = rule.thickness / 2;
1329
- return {
1330
- canvas: [{
1331
- type: "line",
1332
- x1: 0,
1333
- y1: half,
1334
- x2: width,
1335
- y2: half,
1336
- lineWidth: rule.thickness,
1337
- lineColor: rule.color ?? "#000000"
1338
- }],
1339
- margin: [
1340
- 0,
1341
- 3,
1342
- 0,
1343
- 3 + half
1344
- ]
1345
- };
1346
- }
1347
- /**
1348
- * A rectangle's box, exactly: its outline is stroked inside it, half the
1349
- * weight in from each edge, and the canvas, as tall as its lowest point,
1350
- * takes the rest of the box in a margin. A box no wider or taller than two
1351
- * outlines is all outline, and is filled with the outline's colour.
1352
- */
1353
- function rectangleContent(rectangle) {
1354
- const { width, height, fill, stroke } = rectangle;
1355
- if (stroke === void 0 || Math.min(width, height) <= 1) {
1356
- const color = stroke ?? fill;
1357
- return {
1358
- canvas: color === void 0 ? [] : [{
1359
- type: "rect",
1360
- x: 0,
1361
- y: 0,
1362
- w: width,
1363
- h: height,
1364
- color,
1365
- lineWidth: 0
1366
- }],
1367
- margin: [
1368
- 0,
1369
- 0,
1370
- 0,
1371
- color === void 0 ? height : 0
1372
- ]
1373
- };
1374
- }
1375
- const half = OUTLINE / 2;
1376
- return {
1377
- canvas: [{
1378
- type: "rect",
1379
- x: half,
1380
- y: half,
1381
- w: width - OUTLINE,
1382
- h: height - OUTLINE,
1383
- lineWidth: OUTLINE,
1384
- lineColor: stroke,
1385
- ...fill === void 0 ? {} : { color: fill }
1386
- }],
1387
- margin: [
1388
- 0,
1389
- 0,
1390
- 0,
1391
- half
1392
- ]
1393
- };
1394
- }
1395
- /** Columns at the widths worked out here, never pdfmake's `'*'`, which a long word widens past the page (`widths.ts`). */
1396
- function columnsContent(columns, build, scope) {
1397
- const widths = columnWidths(columns.columns.map((slot) => slot.width), scope.width);
1398
- return {
1399
- columns: columns.columns.map((slot, index) => {
1400
- const width = widths[index];
1401
- return {
1402
- width,
1403
- stack: sequence(slot.blocks, build, {
1404
- ...scope,
1405
- width,
1406
- kept: true
1407
- })
1408
- };
1409
- }),
1410
- columnGap: 0
1411
- };
1412
- }
1413
- /**
1414
- * A section with a frame is a table of one cell: pdfmake draws its border
1415
- * and fill around the part of it on each page, and lays out its blocks
1416
- * inside the padding as it lays out the body, tables with their repeated
1417
- * headers and page breaks included.
1418
- */
1419
- function sectionContent(section, build, scope) {
1420
- const frame = frameOf(section);
1421
- const border = section.border?.thickness ?? 0;
1422
- const color = section.border?.color ?? "#000000";
1423
- const padding = section.padding ?? 0;
1424
- const fill = section.fill;
1425
- const layout = {
1426
- hLineWidth: () => border,
1427
- vLineWidth: () => border,
1428
- hLineColor: () => color,
1429
- vLineColor: () => color,
1430
- paddingLeft: () => padding,
1431
- paddingRight: () => padding,
1432
- paddingTop: () => padding,
1433
- paddingBottom: () => padding,
1434
- ...fill === void 0 ? {} : { fillColor: () => fill }
1435
- };
1436
- const width = scope.width - 2 * frame;
1437
- const inner = sequence(section.blocks, build, {
1438
- ...scope,
1439
- width,
1440
- top: scope.top + frame
1441
- });
1442
- return {
1443
- table: {
1444
- widths: [width],
1445
- body: [[{ stack: inner }]]
1446
- },
1447
- layout
1448
- };
1449
- }
1450
- //#endregion
1451
- //#region src/bound.ts
1452
- /**
1453
- * A height the body cannot be shorter than, worked out from the document
1454
- * alone, so that a job too long for its page limit is refused before
1455
- * pdfmake measures it.
1456
- *
1457
- * pdfmake measures every node of a document before it lays out the first
1458
- * page, and the page limit stops only the layout: refusing 100,000 table
1459
- * rows against five pages took 20 seconds, all of it measuring, and nothing
1460
- * could interrupt it (measured on 2026-10-15, on an Intel i9-10900K under
1461
- * Node 24.21). A document whose least height is more than the limit's pages
1462
- * of body is refused here, for nothing.
1463
- *
1464
- * Least, never more than pdfmake lays out, so that nothing that fits is
1465
- * refused: a line of text is one line of its size, however it wraps; a
1466
- * table row one line of its largest text and its padding, without its rule;
1467
- * an image, a rectangle and a rule their own height, without the space
1468
- * around a rule, and a QR code and an EPC QR code its side; a frame its border and padding
1469
- * once. A spacer and a page break count nothing, since a spacer at the foot
1470
- * of a page gives up its space, and a page region is not body.
1471
- */
1472
- function leastHeight(blocks) {
1473
- return blocks.reduce((sum, block) => sum + least(block), 0);
1474
- }
1475
- function least(block) {
1476
- switch (block.kind) {
1477
- case "paragraph": return block.runs.length === 0 ? 0 : line$1(block.style, 10);
1478
- case "table": return tableHeight(block);
1479
- case "image":
1480
- case "rectangle": return block.height;
1481
- case "qrCode":
1482
- case "epcQrCode": return block.size;
1483
- case "rule": return block.thickness;
1484
- case "spacer":
1485
- case "pageBreak": return 0;
1486
- case "keepTogether": return leastHeight(block.blocks);
1487
- case "section": return leastHeight(block.blocks) + 2 * frameOf(block);
1488
- case "columns": return Math.max(0, ...block.columns.map((slot) => leastHeight(slot.blocks)));
1489
- }
1490
- }
1491
- function line$1(style, size) {
1492
- return (style?.size ?? size) * LINE_FACTOR;
1493
- }
1494
- /** A row: one line of the largest text in it, and the cells' padding above and below. */
1495
- function rowHeight(cells, style) {
1496
- return Math.max(0, ...cells.map((text, column) => text === "" ? 0 : line$1(style(column), 9))) + 4;
1497
- }
1498
- /** The header once, and each row. */
1499
- function tableHeight(table) {
1500
- const header = rowHeight(table.header, () => table.headerStyle);
1501
- return table.rows.reduce((sum, row) => sum + rowHeight(row.cells, (column) => row.cellStyles?.[column] ?? row.style), header);
1502
- }
1503
- /**
1504
- * Refuses a body whose least height needs more than `maxPages` pages of
1505
- * `bodyHeight`, with `reserved` points more at its end: the room a QR-bill's
1506
- * slip keeps on the last page. That room is less than a page's body, so it
1507
- * takes at least its own height of the pages whether it ends the last page
1508
- * of the body or starts one of its own, and the two heights together stay
1509
- * a least height.
1510
- */
1511
- function refuseOversized(blocks, bodyHeight, maxPages, reserved = 0) {
1512
- const height = leastHeight(blocks) + reserved;
1513
- if (height > maxPages * bodyHeight) {
1514
- const slip = reserved > 0 ? `, the ${reserved.toFixed(2)} pt the payment part's slip keeps at its end included` : "";
1515
- throw new RenderRefusal("too-many-pages", `the report needs more than ${maxPages} pages: its body is at least ${height.toFixed(2)} pt tall${slip}, and ${maxPages} pages hold ${(maxPages * bodyHeight).toFixed(2)} pt`);
1516
- }
1517
- }
1518
- //#endregion
1519
- //#region src/assets.ts
1520
- /**
1521
- * Image assets checked before pdfmake sees them. pdfmake, through PDFKit,
1522
- * copies a PNG's compressed data and a JPEG's scan into the PDF without
1523
- * decoding either, so bytes that only look like an image arrive in the PDF
1524
- * as a broken one, and bytes that do not look like one at all fail with an
1525
- * error that names no asset. Both are refused here instead, naming it, as
1526
- * `invalid-asset`.
1527
- *
1528
- * What is checked: the size limits; a PNG's or a JPEG's structure, by
1529
- * report-spec's `imageHeader`, which a builder refuses an image a person
1530
- * adds by too (0033) -- for a PNG, every chunk's length and CRC, the header
1531
- * and the palette, and for a JPEG, the segment structure up to the scan,
1532
- * one frame header, read where PDFKit reads it, its size and its component
1533
- * count, and the end marker; and here, that a PNG's image data inflates to
1534
- * exactly the scanlines the header promises, each with a known filter,
1535
- * which needs the platform's decompressor. A JPEG's entropy-coded scan is
1536
- * not decoded: a corrupt scan inside an otherwise well-formed JPEG still
1537
- * reaches the PDF.
1538
- *
1539
- * An SVG is checked by report-spec's `checkSvg`, which the runtime hands
1540
- * on: its bytes must be exactly the drawing `cleanSvg` writes, so that what
1541
- * prints is in the form that was approved, and nothing is cleaned, dropped
1542
- * or rewritten at print (0030). Its size is its viewBox's, and with it come
1543
- * what it costs to draw, which `check.ts` holds a render to.
1544
- *
1545
- * The size returned is the size the image is shown at, as `imageHeader`
1546
- * reads it: a JPEG whose Exif orientation turns it a quarter turn is as wide
1547
- * as its frame is tall, as PDFKit draws it. The check runs on the standard
1548
- * library alone, so that the browser entry makes exactly the same one
1549
- * (`bytes.ts`).
1550
- */
1551
- /**
1552
- * The image data one render may hold, once inflated: two images of the
1553
- * largest kind an asset may be, 4096 by 4096 pixels of 16-bit RGBA, whose
1554
- * scanlines inflate to 134,221,824 bytes each. PDFKit decodes such a PNG to
1555
- * embed it: one took 1.8 seconds and grew the process by 343 MB, two 3.4
1556
- * seconds, four 6.5 seconds (measured on 2026-10-15, on an Intel i9-10900K
1557
- * under Node 24.21). A JPEG is embedded as it is, and counts its bytes.
1558
- */
1559
- const MAX_IMAGE_DATA = 2 * MAX_ASSET_SIDE * (1 + MAX_ASSET_SIDE * 8);
1560
- /** The asset as it is drawn, once its bytes pass; refused as `invalid-asset`, naming it and why, when they do not. */
1561
- async function checkImageAsset(asset) {
1562
- const read = await readAsset(asset);
1563
- if (typeof read === "string") throw new RenderRefusal("invalid-asset", `the image asset ${asset.id} ${read}`, asset.id);
1564
- return read;
1565
- }
1566
- /** The asset as it is drawn, or what is wrong with it. */
1567
- async function readAsset(asset) {
1568
- const { bytes } = asset;
1569
- if (!(bytes instanceof Uint8Array)) return "has no bytes";
1570
- if (bytes.length > MAX_ASSET_BYTES) return `is ${bytes.length} bytes; the limit is ${MAX_ASSET_BYTES} (20 MB)`;
1571
- const sniffed = sniffImage(bytes);
1572
- const isPng = sniffed === "image/png";
1573
- const isJpeg = sniffed === "image/jpeg";
1574
- const actually = () => isPng ? ": it is a PNG" : isJpeg ? ": it is a JPEG" : checkSvg(bytes).ok ? ": it is an SVG" : "";
1575
- if (asset.mediaType === "image/png") return isPng ? readRaster(bytes) : `is declared a PNG and is not one${actually()}`;
1576
- if (asset.mediaType === "image/jpeg") return isJpeg ? readRaster(bytes) : `is declared a JPEG and is not one${actually()}`;
1577
- if (asset.mediaType === "image/svg+xml") return isPng || isJpeg ? `is declared an SVG and is not one${actually()}` : readSvg(bytes);
1578
- return `is of a media type the renderer does not draw (${String(asset.mediaType)})`;
1579
- }
1580
- /**
1581
- * The drawing one render may cost the renderer, in units of what
1582
- * svg-to-pdfkit does each time it draws an SVG: once for each image of it in
1583
- * the body, and on every page for one in a page region, which pdfmake lays
1584
- * out and draws anew on each page (0030). A move, a line or a close is one
1585
- * unit; a curve, an element, a gradient stop and a page-sized transparency
1586
- * group are weighted by what each costs beside a line, rounded up; and every
1587
- * `DRAWING_WEIGHT.bytes` bytes of the drawing are one unit more, since
1588
- * pdfmake reads the whole text again with xmldoc in every pass and the
1589
- * converter on every draw, whatever it draws. At the budget the renderer
1590
- * spends about 2.9 seconds drawing SVGs, about what `MAX_IMAGE_DATA`'s two
1591
- * largest PNGs cost it to decode.
1592
- *
1593
- * Measured on 2026-10-18 on an Intel i9-10900K, shared with other work,
1594
- * under Node 24.21.0 with pdfmake 0.3.11: whole renders, every pass, of an
1595
- * SVG 15 mm square in the page header of a report of so many pages, against
1596
- * the same report with an SVG of one rectangle in its place, medians of five
1597
- * (three at 400 pages). A line costs 2.9 microseconds a page (30,000 lines on
1598
- * 32 pages, 2.79 s more); a cubic 6.8, 2.3 lines (9,999 on 32 pages, 2.18 s);
1599
- * an element 33 beyond its segments, 11.4 lines (6,001 rectangles on 8 pages,
1600
- * 2.29 s); a gradient stop 17, 5.9 lines (a 64-stop gradient on 400
1601
- * rectangles on 7 pages, 3.2 s); a transparency group 0.10 ms beyond its
1602
- * element and segments, 34 to 36 lines (four clipped shapes, and two shapes
1603
- * painted with a translucent gradient, on 400 pages, 0.32 s and 0.25 s).
1604
- * Those lines were short, seven bytes each. On 16 pages a line of 18.7
1605
- * bytes cost 4.4 microseconds a page and one of 37 bytes 5.2, against 3.1
1606
- * for a short one; and 10,506 arcs that draw nothing, a mebibyte of
1607
- * seventeen-digit numbers, cost 109 ms a page on 8 pages, what 35,000 short
1608
- * lines do, though each is counted as a line. With a unit more for every 32
1609
- * bytes, each of these drawings costs from 13 % less than its units say
1610
- * (900 rectangles of seventeen-digit numbers and dash arrays) to 27 % more
1611
- * (the 37-byte lines).
1612
- */
1613
- const MAX_SVG_DRAWING = 1e6;
1614
- /** What each thing svg-to-pdfkit draws costs the renderer, in lines' worth of its time, rounded up, and how many bytes of the drawing are one more unit (`MAX_SVG_DRAWING`). */
1615
- const DRAWING_WEIGHT = {
1616
- curve: 3,
1617
- element: 12,
1618
- stop: 6,
1619
- group: 40,
1620
- bytes: 32
1621
- };
1622
- /** What drawing an SVG once costs the renderer, in `MAX_SVG_DRAWING`'s units. */
1623
- function drawingUnits(checked) {
1624
- const { lines, curves, elements, stops } = checked.drawn;
1625
- return lines + DRAWING_WEIGHT.curve * curves + DRAWING_WEIGHT.element * elements + DRAWING_WEIGHT.stop * stops + DRAWING_WEIGHT.group * checked.groups + Math.ceil(checked.bytes.length / DRAWING_WEIGHT.bytes);
1626
- }
1627
- /** An SVG's drawing, when its bytes are exactly what `cleanSvg` writes; report-spec's refusal, which repeats no value, when they are not. */
1628
- function readSvg(bytes) {
1629
- const checked = checkSvg(bytes);
1630
- if (!checked.ok) return `is not an SVG the renderer draws: ${checked.message}`;
1631
- const { viewBox, segments, groups, extent } = checked;
1632
- return {
1633
- kind: "vector",
1634
- x: viewBox.x,
1635
- y: viewBox.y,
1636
- width: viewBox.width,
1637
- height: viewBox.height,
1638
- svg: ascii(checked.bytes),
1639
- segments,
1640
- groups,
1641
- units: drawingUnits(checked),
1642
- extent
1643
- };
1644
- }
1645
- /** ASCII bytes as text, a chunk at a time: a mebibyte is more than one call takes as arguments. */
1646
- function ascii(bytes) {
1647
- let text = "";
1648
- for (let start = 0; start < bytes.length; start += 8192) text += String.fromCharCode(...bytes.subarray(start, start + 8192));
1649
- return text;
1650
- }
1651
- /**
1652
- * A PNG or a JPEG as it is drawn, once its structure, read by
1653
- * `imageHeader`, and a PNG's image data pass. A JPEG is embedded as it is,
1654
- * and counts its bytes; a PNG counts its scanlines, which PDFKit decodes.
1655
- */
1656
- async function readRaster(bytes) {
1657
- const header = imageHeader(bytes);
1658
- if (!header.ok) return header.message;
1659
- if (header.mediaType === "image/jpeg") return {
1660
- kind: "raster",
1661
- width: header.width,
1662
- height: header.height,
1663
- data: bytes.length,
1664
- cmyk: header.components === 4
1665
- };
1666
- return await scanlineProblem(header) ?? {
1667
- kind: "raster",
1668
- width: header.width,
1669
- height: header.height,
1670
- data: inflatedLength(header),
1671
- cmyk: false
1672
- };
1673
- }
1674
- /** Adam7's seven passes: the first column and row of each, and the steps between them. */
1675
- const ADAM7 = [
1676
- [
1677
- 0,
1678
- 0,
1679
- 8,
1680
- 8
1681
- ],
1682
- [
1683
- 4,
1684
- 0,
1685
- 8,
1686
- 8
1687
- ],
1688
- [
1689
- 0,
1690
- 4,
1691
- 4,
1692
- 8
1693
- ],
1694
- [
1695
- 2,
1696
- 0,
1697
- 4,
1698
- 4
1699
- ],
1700
- [
1701
- 0,
1702
- 2,
1703
- 2,
1704
- 4
1705
- ],
1706
- [
1707
- 1,
1708
- 0,
1709
- 2,
1710
- 2
1711
- ],
1712
- [
1713
- 0,
1714
- 1,
1715
- 1,
1716
- 2
1717
- ]
1718
- ];
1719
- /** The scanlines of each pass of the image: the bytes of one, its filter byte included, and how many there are. */
1720
- function scanlines(header) {
1721
- return (header.interlaced ? ADAM7.map(([x, y, dx, dy]) => [Math.ceil((header.width - x) / dx), Math.ceil((header.height - y) / dy)]) : [[header.width, header.height]]).filter(([width, height]) => width > 0 && height > 0).map(([width, height]) => ({
1722
- bytes: 1 + Math.ceil(width * header.bitsPerPixel / 8),
1723
- count: height
1724
- }));
1725
- }
1726
- /** The bytes the image data inflates to, as the header promises. */
1727
- function inflatedLength(header) {
1728
- return scanlines(header).reduce((total, row) => total + row.bytes * row.count, 0);
1729
- }
1730
- /**
1731
- * Whether the image data inflates to exactly the scanlines the header
1732
- * promises, each starting with a filter type PNG defines. Read as it
1733
- * inflates: the filter bytes are where the scanlines say, so nothing of the
1734
- * image is kept.
1735
- */
1736
- async function scanlineProblem(header) {
1737
- const rows = scanlines(header);
1738
- const expected = inflatedLength(header);
1739
- const filters = filterOffsets(rows);
1740
- let next = filters.next();
1741
- let unknown;
1742
- const inflated = await inflate(header.data, expected, (chunk, offset) => {
1743
- while (unknown === void 0 && !next.done && next.value < offset + chunk.length) {
1744
- const filter = chunk[next.value - offset];
1745
- if (filter > 4) unknown = filter;
1746
- next = filters.next();
1747
- }
1748
- });
1749
- if (inflated.kind === "too-long") return `has more image data than the ${expected} bytes its header promises`;
1750
- if (inflated.kind === "invalid") return "has image data that does not inflate";
1751
- if (inflated.length < expected) return `has image data of ${inflated.length} bytes where its header promises ${expected}`;
1752
- return unknown === void 0 ? void 0 : `has a scanline with an unknown filter type (${unknown})`;
1753
- }
1754
- /** Where each scanline's filter byte is in the inflated data, in order. */
1755
- function* filterOffsets(rows) {
1756
- let offset = 0;
1757
- for (const row of rows) for (let index = 0; index < row.count; index++, offset += row.bytes) yield offset;
1758
- }
1759
- //#endregion
1760
- //#region src/e-invoice.ts
1761
- /**
1762
- * The e-invoice a document carries (0027): the XML the runtime wrote from
1763
- * the values the page prints, and what to embed it as -- the file's name,
1764
- * its relationship to the PDF and the conformance level the PDF's XMP
1765
- * states, report-spec's `FACTUR_X` and `FACTUR_X_PROFILES` handed on by the
1766
- * runtime. The renderer decides none of them, and writes nothing of the XML:
1767
- * it draws the document as a PDF/A-3b that embeds the file (`pdfa.ts`,
1768
- * 0031).
1769
- *
1770
- * **What it does not know it refuses**, before pdfmake sees the document:
1771
- * a file it is not handed as one, XML that is not text or that holds a
1772
- * lone surrogate, which UTF-8 cannot encode as it stands, and a name, a
1773
- * conformance level or a relationship that is not report-spec's. A file
1774
- * from a runtime that names it otherwise would be embedded as something
1775
- * its reader does not look for. A refusal names what is unknown, never a
1776
- * value: the XML holds people's names, accounts and VAT identifiers.
1777
- */
1778
- /** `file`, once the renderer knows it: report-spec's name, one of its profiles' conformance levels, and that profile's relationship. */
1779
- function checkEInvoice(file) {
1780
- const refusal = (message) => new RenderRefusal("unsupported", message, "eInvoice");
1781
- if (typeof file !== "object" || file === null) throw refusal("the e-invoice is not a file the renderer knows");
1782
- const { xml, fileName, relationship, conformanceLevel } = file;
1783
- if (typeof xml !== "string") throw refusal("the e-invoice's XML is not text");
1784
- if (LONE_SURROGATE.test(xml)) throw refusal("the e-invoice's XML holds a lone surrogate, which UTF-8 cannot encode as it stands");
1785
- if (fileName !== FACTUR_X.fileName) throw refusal("the e-invoice is embedded under a file name the renderer does not know");
1786
- const profile = Object.values(FACTUR_X_PROFILES).find((each) => each.conformanceLevel === conformanceLevel);
1787
- if (profile === void 0) throw refusal("the e-invoice states a conformance level the renderer does not know");
1788
- if (relationship !== profile.relationship) throw refusal("the e-invoice is related to the PDF otherwise than a file of its conformance level is");
1789
- return {
1790
- xml,
1791
- fileName,
1792
- relationship: profile.relationship,
1793
- conformanceLevel: profile.conformanceLevel
1794
- };
1795
- }
1796
- const LONE_SURROGATE = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/;
1797
- /**
1798
- * Refuses an e-invoice's title that PDFKit cannot write into the PDF/A's
1799
- * XMP: it puts the title into `dc:title` as it stands, unescaped (pdfkit.js
1800
- * 6025-6032; `pdfmake.test.ts` holds it), so an ampersand or an angle
1801
- * bracket, or a character XML 1.0 cannot write, leaves the XMP not
1802
- * well-formed -- a PDF that says it is a PDF/A and is not one (veraPDF
1803
- * 6.6.2.1-4). report-spec refuses such a title in an e-invoice report, so
1804
- * a report the runtime resolved never reaches this; a document made
1805
- * otherwise is refused here, naming the title and not quoting it. The
1806
- * information dictionary would hold it as written, and in a report that is
1807
- * no e-invoice it reaches no XMP and is drawn.
1808
- */
1809
- function checkEInvoiceTitle(title) {
1810
- if (/[&<>]/.test(title) || [...title].some((character) => !xmlCharacter(character.codePointAt(0)))) throw new RenderRefusal("unsupported", "an e-invoice's title is written into its PDF/A's XMP as it stands, where it may hold no &, < or > and no character XML 1.0 cannot write: this one does", "info.title");
1811
- }
1812
- /** XML 1.0's Char: tab, line feed and carriage return, and every code point from U+0020 but the surrogates, U+FFFE and U+FFFF. A lone surrogate is read as its own code point, and is none. */
1813
- function xmlCharacter(code) {
1814
- return code === 9 || code === 10 || code === 13 || code >= 32 && code <= 55295 || code >= 57344 && code <= 65533 || code >= 65536 && code <= 1114111;
1815
- }
1816
- //#endregion
1817
- //#region src/svg-pdfa.ts
1818
- /**
1819
- * An SVG in an e-invoice (0030, beside 0031): what the PDF/A-3 an e-invoice
1820
- * is drawn as holds an image of one to, checked before pdfmake runs. PDF/A-2
1821
- * and -3 make ISO 32000-1's implementation limits requirements (ISO
1822
- * 19005-2, 6.1.13): no integer past 2,147,483,647 in magnitude, and the
1823
- * graphics state nested no deeper than 28. PDFKit writes a whole number
1824
- * with no point, as an integer (pdfkit.js 173-178), and svg-to-pdfkit
1825
- * computes some of its numbers through the inverse of the drawing's matrix
1826
- * and the image's box: a drawing whose clip and transparency are shrunk a
1827
- * millionfold, drawn a point square, wrote a group's /BBox of
1828
- * 78,520,000,000 into an e-invoice that said it was a PDF/A-3b, which
1829
- * veraPDF 1.30.3 failed on its rule 6.1.13-1 (measured 18 October 2026).
1830
- *
1831
- * So the check bounds, from above, every number the converter writes for
1832
- * an image -- from report-spec's extent of the drawing (`svg-extent.ts`),
1833
- * the image's box and fit, and the page, the image standing anywhere on it,
1834
- * since where pdfmake puts it is not known before it runs -- and refuses an
1835
- * image whose bound passes `SVG_INTEGER_BOUND`, or whose drawing nests
1836
- * deeper than `PDF_A_NESTING`, as `unsupported`, naming it and saying what
1837
- * to do. pdfmake draws an image in the page's own stream, whether it stands
1838
- * in the body, a page region, a section, columns or a keep-together block,
1839
- * and nests nothing around it (measured that day with veraPDF), so the
1840
- * drawing's nesting is the stream's. A report that is no e-invoice is no
1841
- * PDF/A, and draws such an image as it always did.
1842
- */
1843
- /** The largest integer, in magnitude, a PDF/A-2 or -3 may hold (ISO 19005-2, 6.1.13; veraPDF's rule 6.1.13-1). A real may reach 3.403 × 10^38, past the 10^21 at which PDFKit throws. */
1844
- const PDF_A_INTEGER = 2147483647;
1845
- /**
1846
- * What floating point may put between the bound and what the converter
1847
- * writes, relative, derived and not measured. The groups' term is computed
1848
- * from the matrix the cleaner composed, and the converter composes the same
1849
- * matrices in its own order, the page's flip and the fit's scale first, and
1850
- * inverts the product to find a group's box. Below the svg at most
1851
- * `MAX_SVG_DEPTH` - 1 elements bring a matrix each, and the fit comes
1852
- * before them, so the product is at most `MAX_SVG_DEPTH` products (the
1853
- * flip is exact); an entry of a product's linear part is two products
1854
- * summed, so each rounds it at most twice, by 2^-53 of an entry that no
1855
- * cancellation shrank: 2 × `MAX_SVG_DEPTH` units. Inverting magnifies that
1856
- * by the matrix's condition number, at most 4 × `MAX_SVG_COORDINATE`² for
1857
- * a matrix whose entries and whose inverse's are each at most
1858
- * `MAX_SVG_COORDINATE`, as the cleaner's `compose` holds them; and twice
1859
- * that, for the two computations: 2 × 4 × 10^12 × 2 × 32 × 2^-53, 5.7 %.
1860
- * The other terms invert nothing, and lose less. Not bounded by it:
1861
- * matrices built to cancel one another term by term, whose products
1862
- * floating point gets wrong in both (0030).
1863
- */
1864
- const SVG_INTEGER_MARGIN = 2 * (4 * MAX_SVG_COORDINATE ** 2) * (2 * MAX_SVG_DEPTH) * 2 ** -53;
1865
- /** The largest an SVG's numbers may be bounded at in an e-invoice: `PDF_A_INTEGER` less `SVG_INTEGER_MARGIN`. */
1866
- const SVG_INTEGER_BOUND = Math.floor(PDF_A_INTEGER * (1 - SVG_INTEGER_MARGIN));
1867
- /**
1868
- * What the converter writes of the drawing besides its outlines' points,
1869
- * which the extent's `own` holds: each element's own matrix, a stroke's
1870
- * width and dashes, a gradient's ends, each a number the cleaner holds to
1871
- * `MAX_SVG_COORDINATE`; and a radial gradient's focus, which the converter
1872
- * moves inside its circle (`source.js:1884-1888`), within twice it.
1873
- */
1874
- const WRITTEN = 2 * MAX_SVG_COORDINATE;
1875
- /** The numbers the drawing itself writes, wherever it is placed: its outlines' points, and the rest at `WRITTEN`. */
1876
- function outlines({ extent }) {
1877
- return Math.max(WRITTEN, extent.own);
1878
- }
1879
- /** The numbers that grow with where the drawing is placed and how large: `svgReach`'s fit, groups, gradients and what is written in a group's own coordinates. */
1880
- function placed(vector, image, paper) {
1881
- const { extent } = vector;
1882
- const across = {
1883
- x: image.width / vector.width,
1884
- y: image.height / vector.height
1885
- };
1886
- const s = image.fit === "cover" ? Math.max(across.x, across.y) : Math.min(across.x, across.y);
1887
- const dx = (image.width - vector.width * s) / 2;
1888
- const dy = (image.height - vector.height * s) / 2;
1889
- const side = Math.max(paper.paperWidth, paper.paperHeight);
1890
- const d = Math.max(Math.abs(dx), Math.abs(dy));
1891
- const fit = Math.max(s, Math.abs(dx - s * vector.x), Math.abs(dy - s * vector.y));
1892
- const groups = extent.groups.inverse === 0 ? 0 : extent.groups.origin + extent.groups.inverse * (side + d) / s;
1893
- const patterns = Math.max(s * extent.patterns.linear, extent.patterns.linear === 0 ? 0 : side + s * extent.patterns.offset + d);
1894
- return Math.max(fit, groups, patterns, extent.local);
1895
- }
1896
- /** Refuses `image`, an SVG of `vector`, where an e-invoice's PDF/A-3 cannot hold what the converter writes for it on `paper`. */
1897
- function checkSvgInEInvoice(vector, image, paper) {
1898
- const { id } = image.asset;
1899
- if (vector.extent.nesting > 28) throw new RenderRefusal("unsupported", `the image ${id} is an SVG that pdfmake's converter draws ${vector.extent.nesting} graphics states deep, and an e-invoice is drawn as a PDF/A-3, which nests them 28 deep at most: flatten the groups it nests`, id);
1900
- const own = outlines(vector);
1901
- const reach = Math.max(own, placed(vector, image, paper));
1902
- if (reach > SVG_INTEGER_BOUND) {
1903
- const advice = own === reach ? "save it again from the drawing program, its arcs drawn with radii that reach their ends and its smooth curves with control points of their own" : "draw it larger, or flatten the transforms under its clips, its transparency and its gradients";
1904
- throw new RenderRefusal("unsupported", `the image ${id} is an SVG whose numbers, drawn ${image.width} × ${image.height} pt, could reach ${Math.ceil(reach)}, and an e-invoice is drawn as a PDF/A-3, which holds an integer to ${PDF_A_INTEGER}, ${SVG_INTEGER_BOUND} with the renderer's margin for rounding: ${advice}`, id);
1905
- }
1906
- }
1907
- //#endregion
1908
- //#region src/check.ts
1909
- /** Portrait sizes in points, as PDF engines write them: ISO A4 is 210 by 297 millimetres, US Letter 8.5 by 11 inches. */
1910
- const PAPER = {
1911
- A4: {
1912
- width: 595.28,
1913
- height: 841.89
1914
- },
1915
- Letter: {
1916
- width: 612,
1917
- height: 792
1918
- }
1919
- };
1920
- async function checkDocument(document, glyphs, maxPages) {
1921
- const creationDate = new Date(document.info.creationDate);
1922
- if (Number.isNaN(creationDate.getTime())) throw new RenderRefusal("unsupported", `the creation date '${document.info.creationDate}' is not a date`, "info.creationDate");
1923
- if (typeof document.info.title !== "string") throw new RenderRefusal("unsupported", "the title is not text", "info.title");
1924
- const eInvoice = document.eInvoice === void 0 ? void 0 : checkEInvoice(document.eInvoice);
1925
- if (eInvoice !== void 0) checkEInvoiceTitle(document.info.title);
1926
- const page = pageOf(document.page);
1927
- const walk = {
1928
- glyphs,
1929
- paths: /* @__PURE__ */ new Map(),
1930
- images: [],
1931
- codes: /* @__PURE__ */ new Map(),
1932
- captioned: false,
1933
- tall: [],
1934
- measured: []
1935
- };
1936
- const top = {
1937
- kept: false,
1938
- column: false,
1939
- width: page.width,
1940
- inset: 0,
1941
- depth: 0
1942
- };
1943
- checkBlocks(document.pageHeader, "pageHeader", {
1944
- ...top,
1945
- region: true
1946
- }, walk);
1947
- checkBlocks(document.pageFooter, "pageFooter", {
1948
- ...top,
1949
- region: true
1950
- }, walk);
1951
- checkBlocks(document.body, "body", {
1952
- ...top,
1953
- region: false
1954
- }, walk);
1955
- return {
1956
- page,
1957
- creationDate,
1958
- eInvoice,
1959
- assets: await checkImages(walk.images, maxPages, eInvoice !== void 0, page),
1960
- codes: walk.codes,
1961
- captioned: walk.captioned,
1962
- tall: walk.tall,
1963
- paths: walk.paths,
1964
- measured: walk.measured
1965
- };
1966
- }
1967
- /**
1968
- * Every image's asset, read once however many images draw it, and what the
1969
- * images cost together, each refusal naming the asset whose image crossed
1970
- * it:
1971
- *
1972
- * - the image data the PNGs and JPEGs hold, once for each asset, against
1973
- * `MAX_IMAGE_DATA`, as `content-too-large`: each is embedded once;
1974
- * - in an e-invoice, a JPEG PDFKit draws in DeviceCMYK, refused as
1975
- * `unsupported`: the PDF/A-3 it is drawn as has an sRGB output intent,
1976
- * beside which no image may be CMYK (veraPDF 6.2.4.3-3), and a second
1977
- * intent would have to share its profile (6.2.3-2);
1978
- * - in an e-invoice, an image of an SVG whose numbers, at its box and on
1979
- * its page, could pass the integers a PDF/A-3 holds, or whose drawing
1980
- * nests the graphics state deeper than one may, refused as
1981
- * `unsupported` (`svg-pdfa.ts`): each image, since its box decides;
1982
- * - what drawing the SVGs costs the renderer, for every image of one,
1983
- * against `MAX_SVG_DRAWING`, as `content-too-large`: the converter draws an SVG wherever it
1984
- * stands, and one in a page region on every page, counted as `maxPages`,
1985
- * the pages the report may have, which is known before the render;
1986
- * - what the SVGs cost a reader to paint, against `MAX_SVG_SEGMENTS` and
1987
- * `MAX_SVG_GROUPS`, as `content-too-large`, the bounds of one drawing, measured as what one page
1988
- * may cost: every SVG image of the body counted as though all of them fell
1989
- * on one page, beside those of the page regions, which every page draws.
1990
- * Which page each lands on is known only once pdfmake has laid the body
1991
- * out.
1992
- */
1993
- async function checkImages(images, maxPages, eInvoice, page) {
1994
- const assets = /* @__PURE__ */ new Map();
1995
- const total = {
1996
- data: 0,
1997
- units: 0,
1998
- segments: 0,
1999
- groups: 0
2000
- };
2001
- for (const { image, region } of images) {
2002
- const { id } = image.asset;
2003
- let read = assets.get(image.asset);
2004
- if (read === void 0) {
2005
- read = await checkImageAsset(image.asset);
2006
- if (eInvoice && read.kind === "raster" && read.cmyk) throw new RenderRefusal("unsupported", `the image ${id} is a CMYK JPEG, which an e-invoice cannot hold: it is drawn as a PDF/A-3 whose output intent is sRGB, beside which no image may be CMYK`, id);
2007
- assets.set(image.asset, read);
2008
- total.data += read.kind === "raster" ? read.data : 0;
2009
- if (total.data > MAX_IMAGE_DATA) throw new RenderRefusal("content-too-large", `the images up to ${id} hold ${total.data} bytes of image data; a render may hold ${MAX_IMAGE_DATA}`, id);
2010
- }
2011
- if (eInvoice && read.kind === "vector") checkSvgInEInvoice(read, image, page);
2012
- if (read.kind === "vector") addVector(total, read, region ? maxPages : 1, id);
2013
- }
2014
- return assets;
2015
- }
2016
- /** One more SVG image, drawn `times` times, added to what the render's SVG images cost; refused past a bound. */
2017
- function addVector(total, vector, times, id) {
2018
- total.units += vector.units * times;
2019
- total.segments += vector.segments;
2020
- total.groups += vector.groups;
2021
- if (total.units > 1e6) throw new RenderRefusal("content-too-large", `the SVG images up to ${id} cost ${total.units} units to draw, each in a page region counted on every page the report may have; a render may draw ${MAX_SVG_DRAWING}`, id);
2022
- const onePage = "on one page, every SVG image of the body counted as though it fell there beside those of the page regions";
2023
- if (total.segments > MAX_SVG_SEGMENTS) throw new RenderRefusal("content-too-large", `the SVG images up to ${id} would cost a reader ${total.segments} weighted segments to paint ${onePage}; a page may cost ${MAX_SVG_SEGMENTS}`, id);
2024
- if (total.groups > MAX_SVG_GROUPS) throw new RenderRefusal("content-too-large", `the SVG images up to ${id} would make ${total.groups} units of page-sized transparency groups ${onePage}; a page may make ${MAX_SVG_GROUPS}`, id);
2025
- }
2026
- function pageOf(setup) {
2027
- const paper = Object.hasOwn(PAPER, setup.size) ? PAPER[setup.size] : void 0;
2028
- if (paper === void 0) throw new RenderRefusal("unsupported", `the page size '${String(setup.size)}' is not one the renderer knows`, "page.size");
2029
- if (setup.orientation !== "portrait" && setup.orientation !== "landscape") throw new RenderRefusal("unsupported", `the orientation '${String(setup.orientation)}' is not one the renderer knows`, "page.orientation");
2030
- const [paperWidth, paperHeight] = setup.orientation === "portrait" ? [paper.width, paper.height] : [paper.height, paper.width];
2031
- const { margins } = setup;
2032
- if (![
2033
- margins.top,
2034
- margins.right,
2035
- margins.bottom,
2036
- margins.left
2037
- ].every((margin) => Number.isFinite(margin) && margin >= 0)) throw new RenderRefusal("unsupported", "a page margin is negative or not a number", "page.margins");
2038
- const width = paperWidth - margins.left - margins.right;
2039
- const height = paperHeight - margins.top - margins.bottom;
2040
- if (width <= 0 || height <= 0) throw new RenderRefusal("content-too-large", `the margins leave no printable area (${width.toFixed(2)} × ${height.toFixed(2)} pt)`, "page.margins");
2041
- return {
2042
- paperWidth,
2043
- paperHeight,
2044
- margins,
2045
- width,
2046
- height
2047
- };
2048
- }
2049
- function checkBlocks(blocks, path, place, walk) {
2050
- if (place.depth > 16) throw new RenderRefusal("unsupported", `${path} is nested more than 16 blocks deep`, path);
2051
- blocks.forEach((block, index) => checkBlock(block, `${path}[${index}]`, place, walk));
2052
- }
2053
- function checkBlock(block, at, place, walk) {
2054
- switch (block.kind) {
2055
- case "paragraph":
2056
- walk.paths.set(block, at);
2057
- if (!place.region && block.runs.some((run) => "field" in run)) throw new RenderRefusal("unsupported", `${at} prints a page field; pdfmake knows the page number only in the page header and footer`, at);
2058
- checkStyle(block.style, at);
2059
- if (block.runs.some((run) => !("text" in run) && run.field !== "pageNumber" && run.field !== "pageCount")) throw new RenderRefusal("unsupported", `${at} prints a field the renderer does not know`, at);
2060
- for (const run of block.runs) if ("text" in run) checkText(run.text, faceOf(run.bold ?? block.style?.bold ?? false, block.style?.italic ?? false), walk, at);
2061
- tall(walk, place, (block.style?.size ?? 0) * LINE_FACTOR, `a line of ${at}`, at);
2062
- return;
2063
- case "table":
2064
- if (place.column) throw new RenderRefusal("unsupported", `table ${block.id} stands inside a columns block; a table is part of the flow`, block.id);
2065
- checkTable(block, place.width);
2066
- checkTableText(block, walk);
2067
- tall(walk, place, tallestCellLine(block), `a line of table ${block.id}`, block.id);
2068
- if (!place.region && !place.kept) walk.measured.push({
2069
- block,
2070
- at,
2071
- width: place.width,
2072
- inset: place.inset
2073
- });
2074
- return;
2075
- case "image":
2076
- checkImage(block, place, walk);
2077
- walk.images.push({
2078
- image: block,
2079
- region: place.region
2080
- });
2081
- return;
2082
- case "qrCode":
2083
- checkQrCode(block, place, walk);
2084
- return;
2085
- case "epcQrCode":
2086
- checkEpcQrCode(block, place, walk);
2087
- return;
2088
- case "rule":
2089
- if (!(block.thickness > 0 && Number.isFinite(block.thickness))) throw new RenderRefusal("unsupported", `${at} is a rule ${block.thickness} pt thick`, at);
2090
- checkColor(block.color, at);
2091
- tall(walk, place, block.thickness + 6, `the rule ${at}`, at);
2092
- return;
2093
- case "rectangle":
2094
- checkRectangle(block, at, place, walk);
2095
- return;
2096
- case "spacer":
2097
- if (!(block.height >= 0 && Number.isFinite(block.height))) throw new RenderRefusal("unsupported", `${at} is a spacer ${block.height} pt tall`, at);
2098
- return;
2099
- case "pageBreak": {
2100
- const inside = place.region ? "page region" : place.kept ? "keep-together block" : place.column ? "columns block" : void 0;
2101
- if (inside !== void 0) throw new RenderRefusal("unsupported", `${at} is a page break inside a ${inside}`, at);
2102
- return;
2103
- }
2104
- case "keepTogether":
2105
- if (!place.region && !place.kept) walk.measured.push({
2106
- block,
2107
- at,
2108
- width: place.width,
2109
- inset: place.inset
2110
- });
2111
- checkBlocks(block.blocks, `${at}.blocks`, {
2112
- ...place,
2113
- kept: true,
2114
- depth: place.depth + 1
2115
- }, walk);
2116
- return;
2117
- case "columns":
2118
- checkColumns(block, at, place, walk);
2119
- return;
2120
- case "section":
2121
- checkSection(block, at, place, walk);
2122
- return;
2123
- default: throw new RenderRefusal("unsupported", `${at} is a ${String(block.kind)} block, which the renderer does not know`, at);
2124
- }
2125
- }
2126
- /** Something drawn at a fixed height in the body: judged against the body once the regions are measured. A page region's is judged by measuring the region. */
2127
- function tall(walk, place, height, what, subject) {
2128
- if (!place.region) walk.tall.push({
2129
- height,
2130
- inset: place.inset,
2131
- what,
2132
- subject
2133
- });
2134
- }
2135
- /**
2136
- * Text, held to being a string -- an array would reach pdfmake as inlines
2137
- * carrying any property of its own, a link among them -- and to the face it
2138
- * prints in, which must have a glyph for each of its characters.
2139
- */
2140
- function checkText(text, face, walk, at, subject = at) {
2141
- if (typeof text !== "string") throw new RenderRefusal("unsupported", `${at} prints something that is not text`, subject);
2142
- const missing = missingGlyph(text, walk.glyphs[face]);
2143
- if (missing !== void 0) throw new RenderRefusal("unsupported", `${at} prints ${codePoint(missing)}, which Roboto has no glyph for: it would print as an empty box, and as nothing in the PDF's text, and no other font is embedded`, subject);
2144
- }
2145
- /** Every cell of `table` as text in the face it prints in: the renderer's weight for its row's kind, under the cell's style. */
2146
- function checkTableText(table, walk) {
2147
- const at = `table ${table.id}`;
2148
- const face = (style, bold, italic = false) => faceOf(style?.bold ?? bold, style?.italic ?? italic);
2149
- table.header.forEach((text, column) => checkText(text, face(table.headerStyle, KIND_BOLD.header), walk, `${at}'s header, column ${column + 1},`, table.id));
2150
- checkText(table.emptyText, face(void 0, KIND_BOLD.empty, true), walk, `${at}'s empty text`, table.id);
2151
- table.rows.forEach((row, index) => {
2152
- row.cells.forEach((text, column) => {
2153
- checkText(text, face(row.cellStyles?.[column] ?? row.style, KIND_BOLD[row.kind]), walk, `${at}, row ${index}, column ${column + 1},`, table.id);
2154
- });
2155
- });
2156
- }
2157
- function checkStyle(style, at) {
2158
- if (style === void 0) return;
2159
- if (style.font !== void 0 && !Object.hasOwn(FONTS, style.font)) throw new RenderRefusal("unsupported", `${at} is set in the ${String(style.font)} font; the renderer embeds Roboto alone, as the sans font, and prints no other in its place`, at);
2160
- if (style.size !== void 0 && !(style.size > 0 && Number.isFinite(style.size))) throw new RenderRefusal("unsupported", `${at} is set at ${style.size} pt`, at);
2161
- if (style.align !== void 0 && style.align !== "left" && style.align !== "center" && style.align !== "right") throw new RenderRefusal("unsupported", `${at} is aligned '${String(style.align)}'`, at);
2162
- checkColor(style.color, at);
2163
- }
2164
- function checkColor(color, at) {
2165
- if (color !== void 0 && !COLOR.test(color)) throw new RenderRefusal("unsupported", `${at} names the colour '${color}', which is not #rrggbb in lower case`, at);
2166
- }
2167
- function checkTable(table, width) {
2168
- const columns = table.columns.length;
2169
- if (columns === 0) throw new RenderRefusal("unsupported", `table ${table.id} has no columns`, table.id);
2170
- if (table.columns.some((column) => column.align !== "left" && column.align !== "center" && column.align !== "right")) throw new RenderRefusal("unsupported", `table ${table.id} aligns a column in a way the renderer does not know`, table.id);
2171
- if (table.header.length !== columns) throw new RenderRefusal("unsupported", `the header of table ${table.id} has ${table.header.length} cells for ${columns} columns`, table.id);
2172
- table.rows.forEach((row, index) => {
2173
- const cells = row.across === true ? 1 : columns;
2174
- if (row.cells.length !== cells) throw new RenderRefusal("unsupported", `row ${index} of table ${table.id} has ${row.cells.length} cells for ${row.across === true ? "a row across the table, which has one" : `${columns} columns`}`, table.id);
2175
- if (row.cellStyles !== void 0 && row.cellStyles.length !== row.cells.length) throw new RenderRefusal("unsupported", `row ${index} of table ${table.id} has ${row.cellStyles.length} cell styles for ${row.cells.length} cells`, table.id);
2176
- for (const style of [row.style, ...row.cellStyles ?? []]) checkStyle(style ?? void 0, table.id);
2177
- });
2178
- checkStyle(table.headerStyle, table.id);
2179
- const narrow = table.columns.find((column) => column.width !== "fill" && !(column.width > 8 && Number.isFinite(column.width)));
2180
- if (narrow !== void 0) throw new RenderRefusal("unsupported", `table ${table.id} has a column of ${String(narrow.width)} pt, no wider than its cell padding`, table.id);
2181
- const widths = table.columns.map((column) => column.width);
2182
- const fixed = widths.reduce((sum, each) => sum + fixedWidth(each), 0);
2183
- if (fixed > width || fillWidth(widths, width) <= 8) throw new RenderRefusal("content-too-large", `table ${table.id}'s fixed columns are ${fixed} pt wide; it stands ${width.toFixed(2)} pt wide`, table.id);
2184
- }
2185
- /** The tallest line a cell of the table prints, with the cell's padding: a row no page can start. */
2186
- function tallestCellLine(table) {
2187
- const styles = [table.headerStyle, ...table.rows.flatMap((row) => [row.style, ...row.cellStyles ?? []])];
2188
- return Math.max(0, ...styles.map((style) => style?.size ?? 0)) * LINE_FACTOR + 4;
2189
- }
2190
- function checkImage(image, place, walk) {
2191
- const { id } = image.asset;
2192
- if (image.fit !== "contain" && image.fit !== "cover") throw new RenderRefusal("unsupported", `the image ${id} is fitted '${String(image.fit)}', which the renderer does not know`, id);
2193
- if (!(image.width > 0 && image.height > 0 && Number.isFinite(image.width) && Number.isFinite(image.height))) throw new RenderRefusal("unsupported", `the image ${id} is drawn ${image.width} × ${image.height} pt`, id);
2194
- if (image.width > place.width) throw new RenderRefusal("content-too-large", `the image ${id} is ${image.width} pt wide; it stands ${place.width.toFixed(2)} pt wide`, id);
2195
- tall(walk, place, image.height, `the image ${id}`, id);
2196
- }
2197
- /** A QR code is a square that stands where an image may: no wider than where it stands, no taller than the body. */
2198
- function checkQrCode(code, place, walk) {
2199
- const { id, size } = code;
2200
- if (!(size > 0 && Number.isFinite(size))) throw new RenderRefusal("unsupported", `the QR code ${id} is drawn ${size} pt a side`, id);
2201
- if (size > place.width) throw new RenderRefusal("content-too-large", `the QR code ${id} is ${size} pt wide; it stands ${place.width.toFixed(2)} pt wide`, id);
2202
- walk.codes.set(code, qrSymbol(code));
2203
- tall(walk, place, size, `the QR code ${id}`, id);
2204
- }
2205
- /** An EPC QR code is a square that stands where a QR code may, and its caption, when it has one, is drawn inside it. */
2206
- function checkEpcQrCode(code, place, walk) {
2207
- const { id, size } = code;
2208
- if (!(size > 0 && Number.isFinite(size))) throw new RenderRefusal("unsupported", `the EPC QR code ${id} is drawn ${size} pt a side`, id);
2209
- if (size > place.width) throw new RenderRefusal("content-too-large", `the EPC QR code ${id} is ${size} pt wide; it stands ${place.width.toFixed(2)} pt wide`, id);
2210
- walk.codes.set(code, epcSymbol(code));
2211
- walk.captioned ||= code.caption !== void 0;
2212
- tall(walk, place, size, `the EPC QR code ${id}`, id);
2213
- }
2214
- function checkRectangle(rectangle, at, place, walk) {
2215
- if (!(rectangle.width > 0 && rectangle.height > 0 && Number.isFinite(rectangle.width) && Number.isFinite(rectangle.height))) throw new RenderRefusal("unsupported", `${at} is a rectangle of ${rectangle.width} × ${rectangle.height} pt`, at);
2216
- checkColor(rectangle.fill, at);
2217
- checkColor(rectangle.stroke, at);
2218
- if (rectangle.width > place.width) throw new RenderRefusal("content-too-large", `${at} is a rectangle ${rectangle.width} pt wide; it stands ${place.width.toFixed(2)} pt wide`, at);
2219
- tall(walk, place, rectangle.height, `the rectangle ${at}`, at);
2220
- }
2221
- function checkColumns(columns, at, place, walk) {
2222
- if (columns.columns.length === 0) throw new RenderRefusal("unsupported", `${at} is a columns block with no columns`, at);
2223
- const widths = columns.columns.map((slot) => slot.width);
2224
- if (widths.some((width) => width !== "fill" && !(width > 0 && Number.isFinite(width)))) throw new RenderRefusal("unsupported", `${at} has a column of no width`, at);
2225
- const fixed = widths.reduce((sum, each) => sum + fixedWidth(each), 0);
2226
- const fill = fillWidth(widths, place.width);
2227
- if (fixed > place.width || fill <= 0) throw new RenderRefusal("content-too-large", `${at}'s fixed columns are ${fixed} pt wide; it stands ${place.width.toFixed(2)} pt wide`, at);
2228
- columns.columns.forEach((slot, index) => {
2229
- const width = slot.width === "fill" ? fill : slot.width;
2230
- checkBlocks(slot.blocks, `${at}.columns[${index}].blocks`, {
2231
- ...place,
2232
- column: true,
2233
- width,
2234
- depth: place.depth + 1
2235
- }, walk);
2236
- });
2237
- }
2238
- function checkSection(section, at, place, walk) {
2239
- if (section.border !== void 0) {
2240
- if (!(section.border.thickness > 0 && Number.isFinite(section.border.thickness))) throw new RenderRefusal("unsupported", `${at} has a border ${section.border.thickness} pt thick`, at);
2241
- checkColor(section.border.color, at);
2242
- }
2243
- checkColor(section.fill, at);
2244
- if (section.padding !== void 0 && !(section.padding >= 0 && Number.isFinite(section.padding))) throw new RenderRefusal("unsupported", `${at} has a padding of ${section.padding} pt`, at);
2245
- const frame = frameOf(section);
2246
- const width = place.width - 2 * frame;
2247
- if (width <= 0) throw new RenderRefusal("content-too-large", `${at}'s border and padding leave its blocks no width`, at);
2248
- if (frame > 0) tall(walk, place, 2 * frame, `the border and padding of ${at}`, at);
2249
- checkBlocks(section.blocks, `${at}.blocks`, {
2250
- ...place,
2251
- width,
2252
- inset: place.inset + 2 * frame,
2253
- depth: place.depth + 1
2254
- }, walk);
2255
- }
2256
- /**
2257
- * Refuses what the body cannot hold once its height is known: a block of
2258
- * fixed height, or a line, taller than a page's body less the frames around
2259
- * it. pdfmake would draw it past the foot of the page, or not at all.
2260
- */
2261
- function refuseTall(tall, bodyHeight) {
2262
- for (const each of tall) if (each.height > bodyHeight - each.inset) throw new RenderRefusal("content-too-large", `${each.what} is ${each.height.toFixed(2)} pt tall; the body is ${(bodyHeight - each.inset).toFixed(2)} pt where it stands`, each.subject);
2263
- }
2264
- //#endregion
2265
- //#region src/pdfa.ts
2266
- /**
2267
- * An e-invoice drawn as what it is (0031, extending 0027): a PDF/A-3b that
2268
- * embeds the XML the runtime wrote, as `factur-x.xml`, and says so in its
2269
- * XMP. pdfmake takes the PDF/A part of it as two options of the definition
2270
- * (`PDF_A_3B`), and PDFKit writes the rest -- the pdfaid identification,
2271
- * the sRGB output intent and its ICC profile -- as it ends the document.
2272
- * The file and the fx properties have no key in pdfmake's definition, so
2273
- * they are added to PDFKit's document between layout and `end`, the one
2274
- * hook the engines take (`Engine.run`'s `finish`), on the final pass alone.
2275
- *
2276
- * Only a document with an e-invoice is a PDF/A: the version, the subset and
2277
- * the hook are all three its own, and every other report is drawn as it
2278
- * always was (0031 weighs PDF/A for every report, and why not).
2279
- *
2280
- * The renderer decides none of what the file says. The XML is the
2281
- * runtime's, encoded as UTF-8 and changed in nothing; its name, its
2282
- * relationship and the conformance level are the document's, held to
2283
- * report-spec's by `checkEInvoice`; the fx namespace, prefix, document type
2284
- * and version are report-spec's `FACTUR_X`. Only the words that describe
2285
- * the four properties in the extension schema are the renderer's own:
2286
- * PDF/A asks that an extension schema describe each property it declares,
2287
- * and no specification's wording is copied for it.
2288
- */
2289
- /**
2290
- * pdfmake's options for a PDF/A-3b. Level b is the one within reach: level
2291
- * a needs a structure tree, which pdfmake does not build, and PDFKit has
2292
- * no level u (pdfkit.js 5320-5332). The version must be given, or PDFKit writes a PDF 1.3
2293
- * with no XMP and says nothing (pdfkit.js 6070; `pdfmake.test.ts`).
2294
- */
2295
- const PDF_A_3B = {
2296
- version: "1.7",
2297
- subset: "PDF/A-3b"
2298
- };
2299
- /**
2300
- * The hook that makes the final pass's PDF the e-invoice: `file` embedded,
2301
- * dated `created`, the document's own creation date -- so that the same
2302
- * document renders to the same bytes, and no file system's clock reaches
2303
- * the PDF: PDFKit dates a file it reads from a path by `fs.statSync`, and
2304
- * one it is handed by nothing but these options (pdfkit.js 5184-5200) --
2305
- * and the fx properties appended to the XMP.
2306
- */
2307
- function embedEInvoice(file, created) {
2308
- const xml = exactBuffer(new TextEncoder().encode(file.xml));
2309
- const description = `E-invoice XML, ${file.conformanceLevel}`;
2310
- return (document) => {
2311
- document.file(xml, {
2312
- name: file.fileName,
2313
- type: FACTUR_X.mediaType,
2314
- description,
2315
- relationship: file.relationship,
2316
- creationDate: created,
2317
- modifiedDate: created
2318
- });
2319
- document.appendXML(facturXmp(file));
2320
- };
2321
- }
2322
- /** The ArrayBuffer of exactly `bytes`: an encoder's view may sit in a larger buffer, all of which PDFKit would embed. */
2323
- function exactBuffer(bytes) {
2324
- return bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
2325
- }
2326
- /**
2327
- * The extension schemas' own namespaces: the container's as veraPDF's rule
2328
- * 6.6.2.3.3-1 names it, and the schema's and the property's as akretion's
2329
- * factur-x and PDFlib's sample extension schema write them [S], which
2330
- * veraPDF 1.30.3's 6.6.2.3.3 rules pass (0031; report-corpus's
2331
- * `XMP_NAMESPACES` says the same).
2332
- */
2333
- const PDFA_EXTENSION = "http://www.aiim.org/pdfa/ns/extension/";
2334
- const PDFA_SCHEMA = "http://www.aiim.org/pdfa/ns/schema#";
2335
- const PDFA_PROPERTY = "http://www.aiim.org/pdfa/ns/property#";
2336
- /**
2337
- * The extension schema's name, as the Factur-X specification gives it in
2338
- * its section 6.3.1 [S], as 0031 gives it: a name, the one item here not a value, and
2339
- * one no validator in the gate reads.
2340
- */
2341
- const SCHEMA_NAME = "Factur-X PDFA Extension Schema";
2342
- /** The four fx properties, each with its description: the renderer's own words, a Text of the external category, as PDF/A has an extension schema declare a property (6.6.2.3.3). */
2343
- const PROPERTIES = [
2344
- ["DocumentFileName", "The name under which this PDF embeds the invoice as XML"],
2345
- ["DocumentType", "What kind of business document the embedded XML is"],
2346
- ["Version", "The version of the hybrid format this PDF and its XML follow"],
2347
- ["ConformanceLevel", "The profile the embedded XML conforms to"]
2348
- ];
2349
- /** Text as XML writes it between tags and in a double-quoted attribute. Every value here is report-spec's or checked against it, and is escaped all the same. */
2350
- const escaped = (text) => text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
2351
- /**
2352
- * The fx description and the extension schema that declares its four
2353
- * properties, as two `rdf:Description`s PDFKit puts into the packet before
2354
- * its own (pdfkit.js 6011-6013). Without the schema, veraPDF fails the
2355
- * properties (6.6.2.3.1-1, -2).
2356
- */
2357
- function facturXmp(file) {
2358
- const fx = FACTUR_X.xmpPrefix;
2359
- const values = {
2360
- DocumentFileName: file.fileName,
2361
- DocumentType: FACTUR_X.documentType,
2362
- Version: FACTUR_X.version,
2363
- ConformanceLevel: file.conformanceLevel
2364
- };
2365
- const property = ([name, description]) => `<rdf:li rdf:parseType="Resource"><pdfaProperty:name>${name}</pdfaProperty:name><pdfaProperty:valueType>Text</pdfaProperty:valueType><pdfaProperty:category>external</pdfaProperty:category><pdfaProperty:description>${escaped(description)}</pdfaProperty:description></rdf:li>`;
2366
- return [
2367
- `<rdf:Description rdf:about="" xmlns:${fx}="${escaped(FACTUR_X.xmpNamespace)}">`,
2368
- ...PROPERTIES.map(([name]) => `<${fx}:${name}>${escaped(values[name])}</${fx}:${name}>`),
2369
- "</rdf:Description>",
2370
- `<rdf:Description rdf:about="" xmlns:pdfaExtension="${PDFA_EXTENSION}" xmlns:pdfaSchema="${PDFA_SCHEMA}" xmlns:pdfaProperty="${PDFA_PROPERTY}">`,
2371
- "<pdfaExtension:schemas><rdf:Bag><rdf:li rdf:parseType=\"Resource\">",
2372
- `<pdfaSchema:schema>${SCHEMA_NAME}</pdfaSchema:schema>`,
2373
- `<pdfaSchema:namespaceURI>${escaped(FACTUR_X.xmpNamespace)}</pdfaSchema:namespaceURI>`,
2374
- `<pdfaSchema:prefix>${fx}</pdfaSchema:prefix>`,
2375
- `<pdfaSchema:property><rdf:Seq>${PROPERTIES.map(property).join("")}</rdf:Seq></pdfaSchema:property>`,
2376
- "</rdf:li></rdf:Bag></pdfaExtension:schemas>",
2377
- "</rdf:Description>"
2378
- ].join("\n");
2379
- }
2380
- //#endregion
2381
- //#region src/slip.ts
2382
- /**
2383
- * A QR-bill's slip, the receipt and the payment part, as pdfmake content:
2384
- * where SIX puts each heading, value, field, line and the code, and at what
2385
- * size, in Liberation Sans. Nothing here formats a value: the runtime hands
2386
- * every text as it prints (report-runtime's `QrBill`).
2387
- *
2388
- * The numbers are SIX's: "IG" is the Swiss Implementation Guidelines for
2389
- * the QR-bill, version 2.4, and "SG" its Style Guide, version 1.1, whose
2390
- * page 6 gives every section's place and size in millimetres, page 7 the
2391
- * blank fields', and page 15 the sizes and line spacing. What neither gives
2392
- * is taken from manuelbl's SwissQRBill generator, which matches SG 7 drawn
2393
- * to scale: where the blank amount fields stand, and 2 pt between a
2394
- * debtor's heading and its field.
2395
- *
2396
- * Positions are in points from the slip's top left. The slip is
2397
- * report-spec's `QR_BILL_SIZE`, 210 by 105 mm, and stands at its
2398
- * `QR_BILL_TOP`, spanning the paper's width and ending at its foot (IG
2399
- * 3.1): the size and the place the editor draws its band at and refuses a
2400
- * page by, decided there once. The layout draws it as the last page's
2401
- * footer (`definition.ts`), each part placed on its own.
2402
- */
2403
- /** Millimetres in points. */
2404
- const mm = (value) => value * 72 / 25.4;
2405
- /** The receipt is 62 mm wide, and the payment part starts there (IG 3.3). */
2406
- const RECEIPT_WIDTH = mm(62);
2407
- /**
2408
- * "Separate before paying in", above the line along the slip's top, outside
2409
- * the payment part, which a PDF's slip may print instead of a scissors
2410
- * symbol (IG 3.7, SG 4): 8 pt, the payment part's heading size, centred
2411
- * over the slip, its baseline 3 pt above the line. SIX gives neither.
2412
- */
2413
- const INSTRUCTION = {
2414
- size: 8,
2415
- gap: 3
2416
- };
2417
- /** How far above the slip its drawing starts: the top of the instruction's line. The body ends above it. */
2418
- const ABOVE_SLIP = INSTRUCTION.gap + LIBERATION_ASCENDER * INSTRUCTION.size;
2419
- /** The lines the slip is cut along (IG 3.7): solid, half a point. SIX gives no weight. */
2420
- const SEPARATION = .5;
2421
- /**
2422
- * The scissors symbol on the line between the receipt and the payment
2423
- * part. IG 3.7 asks that each line "bear the scissors symbol or
2424
- * alternatively the instruction ... above the line (outside the payment
2425
- * part)": the line across the paper has the instruction above it, and a
2426
- * line down the slip has no "above" outside the payment part, so it bears
2427
- * the symbol. SIX gives it no size or place. It is manuelbl's generator's
2428
- * (`BillLayout.drawBorder`, read on 17 October 2026): 3 mm tall, on the
2429
- * line from 5 mm below the slip's top, the line broken where it stands.
2430
- * 2.5 mm wide, so that it keeps to the 5 mm left unprinted on either side
2431
- * of the line (SG 6). Drawn here, since Liberation Sans has no glyph for
2432
- * U+2702, and the same in every language. In millimetres.
2433
- */
2434
- const SCISSORS = {
2435
- top: 5,
2436
- width: 2.5,
2437
- height: 3
2438
- };
2439
- /** A blank field's corner marks: 3 mm arms, 0.75 pt (IG 3.5.3, SG 7). */
2440
- const CORNER = {
2441
- arm: mm(3),
2442
- weight: .75
2443
- };
2444
- /** Between a debtor's heading's line and its blank field. */
2445
- const FIELD_GAP = 2;
2446
- /** The titles, "Receipt" and "Payment part": 11 pt bold (IG 3.5.1, 3.6.1). */
2447
- const TITLE = 11;
2448
- /** The receipt, 62 by 105 mm (SG 6): 5 mm margins, its title, 56 mm of information, 14 of amount, 18 of acceptance point. */
2449
- const RECEIPT = {
2450
- name: "the receipt",
2451
- lettering: {
2452
- heading: 6,
2453
- value: 8,
2454
- pitch: 9
2455
- },
2456
- title: {
2457
- x: mm(5),
2458
- top: mm(5),
2459
- heading: "receipt"
2460
- },
2461
- additionalInformation: false,
2462
- information: {
2463
- x: mm(5),
2464
- top: mm(12),
2465
- width: mm(52),
2466
- height: mm(56),
2467
- millimetres: 56
2468
- },
2469
- amount: {
2470
- x: mm(5),
2471
- top: mm(68),
2472
- indent: mm(12),
2473
- pitch: 11
2474
- },
2475
- amountField: {
2476
- x: mm(27),
2477
- width: mm(30),
2478
- height: mm(10),
2479
- onAmountLine: false
2480
- },
2481
- debtorField: {
2482
- width: mm(52),
2483
- height: mm(20)
2484
- }
2485
- };
2486
- /** The payment part, 148 by 105 mm (SG 6): the code's 46 mm and the amount's 22 mm beside 87 by 85 mm of information. */
2487
- const PAYMENT_PART = {
2488
- name: "the payment part",
2489
- lettering: {
2490
- heading: 8,
2491
- value: 10,
2492
- pitch: 11
2493
- },
2494
- title: {
2495
- x: RECEIPT_WIDTH + mm(5),
2496
- top: mm(5),
2497
- heading: "paymentPart"
2498
- },
2499
- additionalInformation: true,
2500
- information: {
2501
- x: RECEIPT_WIDTH + mm(56),
2502
- top: mm(5),
2503
- width: mm(87),
2504
- height: mm(85),
2505
- millimetres: 85
2506
- },
2507
- amount: {
2508
- x: RECEIPT_WIDTH + mm(5),
2509
- top: mm(68),
2510
- indent: mm(15),
2511
- pitch: 13
2512
- },
2513
- amountField: {
2514
- x: RECEIPT_WIDTH + mm(16),
2515
- width: mm(40),
2516
- height: mm(15),
2517
- onAmountLine: true
2518
- },
2519
- debtorField: {
2520
- width: mm(65),
2521
- height: mm(25)
2522
- }
2523
- };
2524
- /** The Swiss QR Code's place: 5 mm in, below the title section and 5 mm of quiet zone (IG 3.5.2, SG 6). */
2525
- const CODE = {
2526
- x: RECEIPT_WIDTH + mm(5),
2527
- top: mm(17)
2528
- };
2529
- /** The acceptance point, right-aligned to the receipt's text at the top of its section (IG 3.6.4, SG 6). */
2530
- const ACCEPTANCE = {
2531
- right: mm(57),
2532
- top: mm(82)
2533
- };
2534
- const ascender = (size) => LIBERATION_ASCENDER * size;
2535
- /** A circle about `x`, `y` of radius `r`, as an SVG path of four quarters, each ending at one of its extremes. */
2536
- function circle(x, y, r) {
2537
- const k = .5523 * r;
2538
- return `M${x + r} ${y}C${x + r} ${y + k} ${x + k} ${y + r} ${x} ${y + r}C${x - k} ${y + r} ${x - r} ${y + k} ${x - r} ${y}C${x - r} ${y - k} ${x - k} ${y - r} ${x} ${y - r}C${x + k} ${y - r} ${x + r} ${y - k} ${x + r} ${y}Z`;
2539
- }
2540
- /**
2541
- * The scissors, open, their points down the line they cut along, drawn in
2542
- * tenths of a millimetre across `SCISSORS`. A ring either side of the line
2543
- * at the top, 1.2 mm across and 0.2 mm thick, each touching the symbol's
2544
- * side, filled with its hole left out; and from each ring a blade, a wedge
2545
- * from the ring's side towards the line to a point 0.45 mm past it at the
2546
- * symbol's foot, the two crossing on the line. Drawn here after the symbol
2547
- * IG 3.7 prints, none of it taken from another generator's drawing.
2548
- */
2549
- function scissorsContent() {
2550
- const [across, tall] = [SCISSORS.width * 10, SCISSORS.height * 10];
2551
- const [line, ring, hole, past] = [
2552
- across / 2,
2553
- 6,
2554
- 4,
2555
- 4.5
2556
- ];
2557
- const sides = [-1, 1].map((sign) => {
2558
- const centre = line + sign * (line - ring);
2559
- const toward = (degrees) => {
2560
- const radians = degrees * Math.PI / 180;
2561
- return `${(centre - sign * ring * Math.cos(radians)).toFixed(3)} ${(ring + ring * Math.sin(radians)).toFixed(3)}`;
2562
- };
2563
- return {
2564
- rings: `${circle(centre, ring, ring)}${circle(centre, ring, hole)}`,
2565
- blade: `M${toward(30)}L${toward(75)}L${line - sign * past} ${tall}Z`
2566
- };
2567
- });
2568
- const [width, height] = [mm(SCISSORS.width), mm(SCISSORS.height)];
2569
- const blades = sides.map(({ blade }) => `<path d="${blade}" fill="#000000"/>`).join("");
2570
- return {
2571
- svg: `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="0 0 ${across} ${tall}"><path d="${sides.map(({ rings }) => rings).join("")}" fill="#000000" fill-rule="evenodd"/>${blades}</svg>`,
2572
- width,
2573
- height
2574
- };
2575
- }
2576
- /** One line of text in Liberation Sans, `lineHeight` times its line tall. */
2577
- function line(text, size, bold, lineHeight = 1) {
2578
- return {
2579
- text,
2580
- font: LIBERATION_SANS,
2581
- fontSize: size,
2582
- bold,
2583
- lineHeight
2584
- };
2585
- }
2586
- /** A blank field's four corners, each two arms of a polyline, stroked inside the box `width` by `height` from the canvas's corner. */
2587
- function corners(width, height) {
2588
- const [inset, arm] = [CORNER.weight / 2, CORNER.arm];
2589
- const corner = (points) => ({
2590
- type: "polyline",
2591
- points: points.map(([x, y]) => ({
2592
- x,
2593
- y
2594
- })),
2595
- lineWidth: CORNER.weight,
2596
- lineColor: "#000000"
2597
- });
2598
- const [left, top, right, bottom] = [
2599
- inset,
2600
- inset,
2601
- width - inset,
2602
- height - inset
2603
- ];
2604
- return [
2605
- corner([
2606
- [left, arm],
2607
- [left, top],
2608
- [arm, top]
2609
- ]),
2610
- corner([
2611
- [width - arm, top],
2612
- [right, top],
2613
- [right, arm]
2614
- ]),
2615
- corner([
2616
- [right, height - arm],
2617
- [right, bottom],
2618
- [width - arm, bottom]
2619
- ]),
2620
- corner([
2621
- [arm, bottom],
2622
- [left, bottom],
2623
- [left, height - arm]
2624
- ])
2625
- ];
2626
- }
2627
- /** The blocks a part's information holds, in SIX's order (IG 3.5.4, 3.6.2): the additional information in the payment part alone. */
2628
- function blocks(bill, part) {
2629
- const { headings } = bill;
2630
- return [
2631
- {
2632
- heading: headings.account,
2633
- values: [bill.account, ...bill.creditor]
2634
- },
2635
- ...bill.reference === null ? [] : [{
2636
- heading: headings.reference,
2637
- values: [bill.reference]
2638
- }],
2639
- ...part.additionalInformation && bill.additionalInformation.length > 0 ? [{
2640
- heading: headings.additionalInformation,
2641
- values: bill.additionalInformation
2642
- }] : [],
2643
- bill.debtor === null ? {
2644
- heading: headings.payableBy,
2645
- field: part.debtorField
2646
- } : {
2647
- heading: headings.payableBy,
2648
- values: bill.debtor
2649
- }
2650
- ];
2651
- }
2652
- /**
2653
- * A part's information, as one stack laid out from its section's top: the
2654
- * first heading's line at the top, every line's baseline `pitch` below the
2655
- * one before, and a blank line between blocks (SG 15). pdfmake sets each
2656
- * baseline its ascender below its line's top, so a heading's line is made
2657
- * shorter than the pitch by what a value's ascender is longer, and the
2658
- * space before a heading longer by as much.
2659
- */
2660
- function informationContent(bill, part) {
2661
- const { heading, value, pitch } = part.lettering;
2662
- const shift = ascender(value) - ascender(heading);
2663
- return blocks(bill, part).flatMap((block, index) => {
2664
- const title = {
2665
- ...line(block.heading, heading, true, (pitch - shift) / (LIBERATION_LINE * heading)),
2666
- margin: [
2667
- 0,
2668
- index === 0 ? 0 : pitch + shift,
2669
- 0,
2670
- 0
2671
- ]
2672
- };
2673
- if ("field" in block) return [title, {
2674
- canvas: corners(block.field.width, block.field.height),
2675
- margin: [
2676
- 0,
2677
- FIELD_GAP,
2678
- 0,
2679
- CORNER.weight / 2
2680
- ]
2681
- }];
2682
- return [title, ...block.values.map((text) => line(text, value, false, pitch / (LIBERATION_LINE * value)))];
2683
- });
2684
- }
2685
- /** `content` placed with its top left at `x`, `y` on the page, measured from the footer's top, `origin`, where pdfmake lays the footer out. */
2686
- function at(content, x, y, origin) {
2687
- return {
2688
- ...content,
2689
- absolutePosition: {
2690
- x,
2691
- y: y - origin
2692
- }
2693
- };
2694
- }
2695
- /** `content` laid out `width` wide where it is placed, on a page `paperWidth` wide. */
2696
- function within(content, x, width, paperWidth) {
2697
- return { stack: [{
2698
- stack: content,
2699
- margin: [
2700
- 0,
2701
- 0,
2702
- paperWidth - x - width,
2703
- 0
2704
- ]
2705
- }] };
2706
- }
2707
- /** A part's title, its amount section and its information, each placed on the page whose slip starts at `top`. */
2708
- function partContent(bill, part, top, origin, paperWidth) {
2709
- const { heading, value } = part.lettering;
2710
- const { amount } = part;
2711
- const headingTop = top + amount.top;
2712
- const amountTop = headingTop + ascender(heading) + amount.pitch - ascender(value);
2713
- const field = part.amountField;
2714
- return [
2715
- at(line(bill.headings[part.title.heading], TITLE, true), part.title.x, top + part.title.top, origin),
2716
- at(line(bill.headings.currency, heading, true), amount.x, headingTop, origin),
2717
- at(line(bill.currency, value, false), amount.x, amountTop, origin),
2718
- at(line(bill.headings.amount, heading, true), amount.x + amount.indent, headingTop, origin),
2719
- bill.amount === null ? at({ canvas: corners(field.width, field.height) }, field.x, field.onAmountLine ? amountTop : headingTop, origin) : at(line(bill.amount, value, false), amount.x + amount.indent, amountTop, origin),
2720
- at(within(informationContent(bill, part), part.information.x, part.information.width, paperWidth), part.information.x, top + part.information.top, origin)
2721
- ];
2722
- }
2723
- /**
2724
- * The slip, as the last page's footer lays it out, its top `top` points
2725
- * down a page `paperWidth` wide: the lines it is cut along, the
2726
- * instruction above the one across and the scissors on the one down, the
2727
- * receipt with its acceptance point, and the payment part with its code.
2728
- * Made anew for each layout, since pdfmake writes its positions into the
2729
- * content it lays out.
2730
- */
2731
- function slipContent({ bill, symbol }, top, origin, paperWidth) {
2732
- const down = (from, to) => ({
2733
- type: "line",
2734
- x1: RECEIPT_WIDTH,
2735
- y1: from,
2736
- x2: RECEIPT_WIDTH,
2737
- y2: to,
2738
- lineWidth: SEPARATION,
2739
- lineColor: "#000000"
2740
- });
2741
- const separation = { canvas: [
2742
- {
2743
- type: "line",
2744
- x1: 0,
2745
- y1: 0,
2746
- x2: QR_BILL_SIZE.width,
2747
- y2: 0,
2748
- lineWidth: SEPARATION,
2749
- lineColor: "#000000"
2750
- },
2751
- down(0, mm(SCISSORS.top)),
2752
- down(mm(SCISSORS.top + SCISSORS.height), QR_BILL_SIZE.height)
2753
- ] };
2754
- const instruction = {
2755
- ...line(bill.headings.separate, INSTRUCTION.size, false),
2756
- alignment: "center"
2757
- };
2758
- const acceptance = {
2759
- ...line(bill.headings.acceptancePoint, RECEIPT.lettering.heading, true),
2760
- alignment: "right"
2761
- };
2762
- return [
2763
- at(instruction, 0, top - ABOVE_SLIP, origin),
2764
- at(separation, 0, top, origin),
2765
- at(scissorsContent(), RECEIPT_WIDTH - mm(SCISSORS.width / 2), top + mm(SCISSORS.top), origin),
2766
- ...partContent(bill, RECEIPT, top, origin, paperWidth),
2767
- at(within([acceptance], RECEIPT.information.x, ACCEPTANCE.right - RECEIPT.information.x, paperWidth), RECEIPT.information.x, top + ACCEPTANCE.top, origin),
2768
- ...partContent(bill, PAYMENT_PART, top, origin, paperWidth),
2769
- at(swissCodeContent(symbol), CODE.x, top + CODE.top, origin)
2770
- ];
2771
- }
2772
- //#endregion
2773
- //#region src/definition.ts
2774
- /**
2775
- * The pdfmake document definitions a render hands pdfmake, built from the
2776
- * resolved document and what was measured: pure, the same in Node and in a
2777
- * browser, and the one place either entry's definitions come from. What
2778
- * runs them is the entry's own (`node.ts`, `browser.ts`).
2779
- *
2780
- * The page regions: pdfmake draws its header inside the top page margin and
2781
- * its footer inside the bottom one, and lays the body out between. So
2782
- * pdfmake's margins are the document's enlarged by each region's measured
2783
- * height and a 6pt gap, and each region is drawn at the document's own
2784
- * margin: the header from the top of the printable area down, the footer
2785
- * ending at its bottom. Nothing of the body can reach into either.
2786
- */
2787
- const DEFAULT_STYLE = {
2788
- font: ROBOTO,
2789
- fontSize: 10
2790
- };
2791
- /**
2792
- * The page header and footer that have blocks, each one item, with every
2793
- * page field printed as the page limit: as many digits as the field can
2794
- * have. A region that wraps only for some page numbers is measured at its
2795
- * widest, which is not the same thing, and is not refused.
2796
- */
2797
- function regionsMeasurement(document, checked, maxPages) {
2798
- const fields = {
2799
- pageNumber: maxPages,
2800
- pageCount: maxPages
2801
- };
2802
- const present = [document.pageHeader, document.pageFooter].filter((blocks) => blocks.length > 0);
2803
- const build = newBuild("measure", checked);
2804
- return {
2805
- present,
2806
- build,
2807
- items: present.map((blocks) => ({ stack: contentOf(blocks, build, checked.page.width, fields) }))
2808
- };
2809
- }
2810
- /** The body's tables and keep-together blocks, each one item laid out at the width it stands at. */
2811
- function bodyMeasurement(measured, checked) {
2812
- const build = newBuild("measure", checked);
2813
- return {
2814
- items: measured.map(({ block, width }) => ({
2815
- stack: contentOf([block], build, width),
2816
- margin: [
2817
- 0,
2818
- 0,
2819
- checked.page.width - width,
2820
- 0
2821
- ]
2822
- })),
2823
- build
2824
- };
2825
- }
2826
- /** Where the body starts and ends on every page, from the top of the paper: inside the margins and below and above the page regions. */
2827
- function bodyBounds(page, regions) {
2828
- return {
2829
- top: page.margins.top + regions.header,
2830
- bottom: page.paperHeight - page.margins.bottom - regions.footer
2831
- };
2832
- }
2833
- /**
2834
- * How much of the last page's body a QR-bill's slip takes: from where its
2835
- * drawing starts, the instruction above it, to the body's foot. Nothing if
2836
- * the body ends above the slip on every page.
2837
- */
2838
- function slipReservation(page, regions) {
2839
- return Math.max(0, bodyBounds(page, regions).bottom - (QR_BILL_TOP - ABOVE_SLIP));
2840
- }
2841
- /**
2842
- * The PDF's definition. pdfmake's own page limit, `maxPagesNumber`, cuts the
2843
- * document short; the renderer's throws out of the layout instead, from the
2844
- * function pdfmake calls for each page's background, as the page after the
2845
- * last one allowed is added. So no more than one page past the limit is ever
2846
- * laid out, and nothing is written.
2847
- *
2848
- * A QR-bill's slip is the last page's footer, in place of the page footer:
2849
- * pdfmake lays the footer out once every page is, knowing their count, and
2850
- * gives what is placed above the footer's top the room down to the paper's
2851
- * foot (`pdfmake.test.ts` holds both). The body keeps the slip's room at
2852
- * its end, a spacer as tall as `slipReservation`: where the last page has
2853
- * less room left, pdfmake moves to a new page and starts it without the
2854
- * space, and the slip has that page to itself.
2855
- *
2856
- * A document with an e-invoice is a PDF/A-3b, whose version and subset are
2857
- * the definition's (`PDF_A_3B`); its file and XMP are the final pass's hook
2858
- * (`render.ts`). Neither moves a line: the measuring passes, which have
2859
- * neither, lay the page out as this one does.
2860
- */
2861
- function layoutDefinition(document, checked, regions, plans, maxPages, bill) {
2862
- const page = checked.page;
2863
- const { margins } = page;
2864
- const { top: bodyTop, bottom: bodyBottom } = bodyBounds(page, regions);
2865
- const build = newBuild("render", checked, {
2866
- top: bodyTop,
2867
- bottom: bodyBottom
2868
- }, plans);
2869
- const region = (blocks, margin) => {
2870
- if (blocks.length === 0) return void 0;
2871
- return (pageNumber, pageCount) => ({
2872
- stack: contentOf(blocks, build, page.width, {
2873
- pageNumber,
2874
- pageCount
2875
- }),
2876
- margin
2877
- });
2878
- };
2879
- const header = region(document.pageHeader, [
2880
- margins.left,
2881
- margins.top,
2882
- margins.right,
2883
- 0
2884
- ]);
2885
- const footer = region(document.pageFooter, [
2886
- margins.left,
2887
- 6,
2888
- margins.right,
2889
- 0
2890
- ]);
2891
- header?.(1, 1, {
2892
- width: page.paperWidth,
2893
- height: page.paperHeight,
2894
- orientation: document.page.orientation
2895
- });
2896
- footer?.(1, 1, {
2897
- width: page.paperWidth,
2898
- height: page.paperHeight,
2899
- orientation: document.page.orientation
2900
- });
2901
- const slip = bill === void 0 ? void 0 : () => ({ stack: slipContent(bill, QR_BILL_TOP, bodyBottom, page.paperWidth) });
2902
- const last = slip === void 0 ? footer : (pageNumber, pageCount, size) => pageNumber === pageCount ? slip() : footer?.(pageNumber, pageCount, size);
2903
- const reserved = bill === void 0 ? [] : [{
2904
- stack: [],
2905
- margin: [
2906
- 0,
2907
- slipReservation(page, regions),
2908
- 0,
2909
- 0
2910
- ]
2911
- }];
2912
- return {
2913
- ...checked.eInvoice === void 0 ? {} : PDF_A_3B,
2914
- info: {
2915
- title: document.info.title,
2916
- creationDate: checked.creationDate
2917
- },
2918
- pageSize: {
2919
- width: page.paperWidth,
2920
- height: page.paperHeight
2921
- },
2922
- pageMargins: [
2923
- margins.left,
2924
- bodyTop,
2925
- margins.right,
2926
- page.paperHeight - bodyBottom
2927
- ],
2928
- defaultStyle: DEFAULT_STYLE,
2929
- content: [...contentOf(document.body, build, page.width), ...reserved],
2930
- images: build.images,
2931
- ...header === void 0 ? {} : { header },
2932
- ...last === void 0 ? {} : { footer: last },
2933
- background: (number) => {
2934
- if (number === 1) checkWords(build.words);
2935
- if (number > maxPages) throw new RenderRefusal("too-many-pages", `the report needs more than ${maxPages} pages`);
2936
- return null;
2937
- },
2938
- pageBreakBefore: (node, queries) => {
2939
- return (node.headlineLevel === void 0 ? void 0 : build.rules.get(node.headlineLevel))?.(node, queries) ?? false;
2940
- }
2941
- };
2942
- }
2943
- //#endregion
2944
- //#region src/measure.ts
2945
- /** Thrown out of pdfmake's layout with what was read; never seen outside `measure`. */
2946
- var Measurement = class {
2947
- tops;
2948
- constructor(tops) {
2949
- this.tops = tops;
2950
- }
2951
- };
2952
- /** Sentinels are marked with negative numbers, so that they never meet the marks content carries. */
2953
- const sentinel = (index) => ({
2954
- text: ".",
2955
- fontSize: 1,
2956
- headlineLevel: -1 - index
2957
- });
2958
- /** A sentinel's height exactly: one line of one-point Roboto, for a page that must hold its items and nothing more. */
2959
- const SENTINEL_LINE = LINE_FACTOR;
2960
- /**
2961
- * Lays `items` out on one page `height` tall, between those side margins,
2962
- * and measures them; `overflow` is what to throw when they do not fit on it.
2963
- * Before a line is laid out, the `words` of the items are held to their
2964
- * room, so that pdfmake never breaks one too wide for it.
2965
- */
2966
- async function measure(engine, page, items, resources, overflow, words) {
2967
- const definition = {
2968
- pageSize: {
2969
- width: page.width,
2970
- height: page.height
2971
- },
2972
- pageMargins: [
2973
- page.left,
2974
- 0,
2975
- page.right,
2976
- 0
2977
- ],
2978
- ...resources,
2979
- content: [
2980
- sentinel(0),
2981
- sentinel(1),
2982
- ...items.flatMap((item, index) => [item, sentinel(index + 2)])
2983
- ],
2984
- background: (number) => {
2985
- if (number === 1) checkWords(words);
2986
- if (number > 1) throw overflow();
2987
- return null;
2988
- },
2989
- pageBreakBefore: (node, queries) => {
2990
- const tops = /* @__PURE__ */ new Map();
2991
- for (const each of [node, ...queries.getFollowingNodesOnPage()]) if (each.headlineLevel !== void 0) tops.set(each.headlineLevel, each.startPosition.top);
2992
- throw new Measurement(tops);
2993
- }
2994
- };
2995
- let tops;
2996
- try {
2997
- await engine.run(definition);
2998
- throw new Error("pdfmake wrote a PDF instead of measuring");
2999
- } catch (error) {
3000
- if (!(error instanceof Measurement)) throw error;
3001
- tops = error.tops;
3002
- }
3003
- const top = (mark) => {
3004
- const found = tops.get(mark);
3005
- if (found === void 0) throw new Error(`pdfmake laid out no node marked ${mark}`);
3006
- return found;
3007
- };
3008
- const pitch = top(-2) - top(-1);
3009
- const ends = items.map((_, index) => top(-3 - index));
3010
- return {
3011
- heights: ends.map((end, index) => end - top(-2 - index) - pitch),
3012
- ends,
3013
- top
3014
- };
3015
- }
3016
- /**
3017
- * Each row's height, from the tops of the marks on their first cells: a
3018
- * row's top to the next one's is its height and the rule under it. The last
3019
- * row ends where the table does, which is where the sentinel after it
3020
- * starts, measured from the top of its cell, which stands `PADDING_Y` below
3021
- * the row's top.
3022
- */
3023
- function rowPitches(marks, top, tableEnd) {
3024
- return marks.map((mark, index) => {
3025
- const next = marks[index + 1];
3026
- return next === void 0 ? tableEnd - top(mark) + 2 : top(next) - top(mark);
3027
- });
3028
- }
3029
- /**
3030
- * How a table breaks across pages of a body `bodyHeight` tall, from its
3031
- * measured rows, the header row first:
3032
- *
3033
- * - rows are kept whole (`dontBreakRows`) only when every one fits on a
3034
- * page under the repeated header, and the first row of each group under
3035
- * its group header as well. pdfmake's option is the whole table's, so one
3036
- * row that does not lets every row of the table split. Split is what a row
3037
- * taller than the page needs, since pdfmake would otherwise not draw it,
3038
- * and what the first row of a group needs to start on its group header's
3039
- * page when the two cannot share one whole;
3040
- * - the header moves with the first row, or with the first two when the
3041
- * first is a group header, so that neither ends a page alone, and with
3042
- * every row of a block of rows kept together that starts among them --
3043
- * a one-line quotation's totals; not when they do not fit on a page
3044
- * together, for the same reason;
3045
- * - the rows kept together (`breaks.ts`) are the blocks that fit on a page
3046
- * under the header and start after the rows that move with it. A table
3047
- * whose rows may split keeps only its group headers with what they head.
3048
- */
3049
- function tablePlan(rows, bodyHeight) {
3050
- const [header, ...body] = rows;
3051
- const room = bodyHeight - RULE - (header?.pitch ?? 0) - 1;
3052
- const under = (index) => body[index - 1]?.kind === "groupHeader" ? body[index - 1].pitch : 0;
3053
- const dontBreakRows = body.every((row, index) => under(index) + row.pitch <= room);
3054
- const pitches = rows.map((row) => row.pitch);
3055
- const blocks = keepBlocks(rows.map((row) => row.kind), dontBreakRows);
3056
- const first = body[0]?.kind === "groupHeader" && body.length > 1 ? 2 : 1;
3057
- let lead = first;
3058
- for (const block of blocks) if (block.first <= lead) lead = Math.max(lead, block.last);
3059
- const fits = (count) => body.slice(0, count).reduce((sum, row) => sum + row.pitch, 0) <= room;
3060
- const keepWithHeaderRows = fits(lead) ? lead : fits(first) ? first : 0;
3061
- return {
3062
- dontBreakRows,
3063
- keepWithHeaderRows,
3064
- pitches,
3065
- blocks: keptBlocks(blocks, pitches, keepWithHeaderRows, room)
3066
- };
3067
- }
3068
- //#endregion
3069
- //#region src/render.ts
3070
- /**
3071
- * A resolved document rendered with pdfmake, refused rather than truncated,
3072
- * clipped or dropped: the renderer both entries share, given the one thing
3073
- * they do differently, the engine that runs a pdfmake definition with its
3074
- * fonts ([0005](../../../docs/decisions/0005-pdfmake-renders-reports-behind-one-adapter.md)).
3075
- *
3076
- * Three passes, each a pdfmake layout. The first measures the page header
3077
- * and footer, and the second the body's keep-together blocks and table rows
3078
- * (`measure.ts`), because pdfmake loses what does not fit where it must
3079
- * without saying so. The third is the PDF, laid out again by pdfmake for
3080
- * each page break a keep-with-next or table rule asks for. Before them the
3081
- * renderer refuses what it cannot draw (`check.ts`, and `bill.ts` for a
3082
- * QR-bill); between them it decides the page margins, refuses what cannot
3083
- * fit on any page or within the page limit (`bound.ts`), and chooses how
3084
- * each table breaks. A document with a QR-bill has two passes more, one for
3085
- * each part of its slip, which measure their information (`measureSlip`).
3086
- * A document with an e-invoice is drawn as a PDF/A-3b on the third pass,
3087
- * which alone embeds its XML (`pdfa.ts`).
3088
- */
3089
- async function render(engine, document, options) {
3090
- const { signal, maxPages } = options;
3091
- if (!Number.isSafeInteger(maxPages) || maxPages < 1) throw new RangeError(`maxPages must be a whole number of pages, at least 1; it is ${String(maxPages)}`);
3092
- stopIfCancelled(signal);
3093
- const checked = await checkDocument(document, await engine.glyphs(), maxPages);
3094
- const bill = document.paymentPart === void 0 ? void 0 : checkBill(document.paymentPart, document.page, await engine.billGlyphs());
3095
- if (checked.captioned) await engine.billGlyphs();
3096
- await stopIfCancelledSoon(signal);
3097
- const regions = await measureRegions(engine, document, checked, maxPages);
3098
- await stopIfCancelledSoon(signal);
3099
- const bodyHeight = checked.page.height - regions.header - regions.footer;
3100
- if (bodyHeight <= 0) throw new RenderRefusal("content-too-large", `the page header and footer leave no room for the body (${bodyHeight.toFixed(2)} pt)`);
3101
- if (bill !== void 0) await measureSlip(engine, bill, checked.page, document.page, regions);
3102
- refuseTall(checked.tall, bodyHeight);
3103
- refuseOversized(document.body, bodyHeight, maxPages, bill === void 0 ? 0 : slipReservation(checked.page, regions));
3104
- const plans = await measureBody(engine, checked, bodyHeight, maxPages);
3105
- await stopIfCancelledSoon(signal);
3106
- const finish = checked.eInvoice === void 0 ? void 0 : embedEInvoice(checked.eInvoice, checked.creationDate);
3107
- const pdf = await engine.run(layoutDefinition(document, checked, regions, plans, maxPages, bill), finish);
3108
- await stopIfCancelledSoon(signal);
3109
- return pdf;
3110
- }
3111
- /** How much taller than its section a slip's information may lay out and still fit: rounding, not layout. */
3112
- const SECTION_SLACK = .01;
3113
- /**
3114
- * Refuses a QR-bill's slip that cannot be drawn whole where SIX puts it: on
3115
- * a page whose top margin, with the header under it and the instruction to
3116
- * separate over the slip, reaches into it, by report-spec's rule
3117
- * (`refusePage`); or with information taller than its section (SG 6),
3118
- * which would run into the section below it or off the paper. Each part's
3119
- * information is laid out as the slip lays it out (`slip.ts`), on a sheet
3120
- * as tall as its section and the three sentinels around it: what does not
3121
- * fit on the sheet is taller than the section, and pdfmake's next page
3122
- * refuses it.
3123
- */
3124
- async function measureSlip(engine, bill, page, setup, regions) {
3125
- refusePage(setup, regions.header + ABOVE_SLIP);
3126
- for (const part of [PAYMENT_PART, RECEIPT]) {
3127
- const { width, height, millimetres } = part.information;
3128
- const refusal = () => new RenderRefusal("content-too-large", `${part.name}'s information is taller than its section: SIX gives it ${millimetres} mm (${height.toFixed(2)} pt)`, "paymentPart");
3129
- const item = {
3130
- stack: informationContent(bill.bill, part),
3131
- margin: [
3132
- 0,
3133
- 0,
3134
- page.paperWidth - width,
3135
- 0
3136
- ]
3137
- };
3138
- await measure(engine, {
3139
- width: page.paperWidth,
3140
- height: height + 3 * SENTINEL_LINE + SECTION_SLACK,
3141
- left: 0,
3142
- right: 0
3143
- }, [item], resources({}), refusal, []);
3144
- }
3145
- }
3146
- /**
3147
- * The page header's and footer's heights, measured once, on a page as tall
3148
- * as the printable area: two regions that do not fit on it leave no body.
3149
- */
3150
- async function measureRegions(engine, document, checked, maxPages) {
3151
- const { present, items, build } = regionsMeasurement(document, checked, maxPages);
3152
- if (present.length === 0) return {
3153
- header: 0,
3154
- footer: 0
3155
- };
3156
- const { page } = checked;
3157
- const { heights } = await measure(engine, {
3158
- width: page.paperWidth,
3159
- height: page.height + 2 * (items.length + 2),
3160
- left: page.margins.left,
3161
- right: page.margins.right
3162
- }, items, resources(build.images), () => new RenderRefusal("content-too-large", "the page header and footer are taller than the printable area"), build.words);
3163
- const space = (blocks) => blocks.length === 0 ? 0 : heights[present.indexOf(blocks)] + 6;
3164
- return {
3165
- header: space(document.pageHeader),
3166
- footer: space(document.pageFooter)
3167
- };
3168
- }
3169
- /**
3170
- * Measures the body's keep-together blocks and tables, refuses a block no
3171
- * page can hold, and plans how each table breaks. On a page as tall as the
3172
- * page limit's bodies and one more: content that does not fit on it needs
3173
- * more pages than the limit, whatever else the body holds, so it is refused
3174
- * here, after laying out at most that much of it.
3175
- *
3176
- * A block inside framed sections has less of each page than the body: their
3177
- * borders and padding above and below it, which is what `inset` holds.
3178
- */
3179
- async function measureBody(engine, checked, bodyHeight, maxPages) {
3180
- const { measured, page } = checked;
3181
- if (measured.length === 0) return /* @__PURE__ */ new Map();
3182
- const { items, build } = bodyMeasurement(measured, checked);
3183
- const { heights, top, ends } = await measure(engine, {
3184
- width: page.paperWidth,
3185
- height: (maxPages + 1) * bodyHeight + 2 * (items.length + 2),
3186
- left: page.margins.left,
3187
- right: page.margins.right
3188
- }, items, resources(build.images), () => new RenderRefusal("too-many-pages", `the report needs more than ${maxPages} pages`), build.words);
3189
- const plans = /* @__PURE__ */ new Map();
3190
- measured.forEach(({ block, at, inset }, index) => {
3191
- const room = bodyHeight - inset;
3192
- if (block.kind === "keepTogether" && heights[index] > room - 1) throw new RenderRefusal("content-too-large", `the keep-together block ${at} is ${heights[index].toFixed(2)} pt tall; a page's body is ${room.toFixed(2)} pt where it stands`, at);
3193
- if (block.kind === "table") {
3194
- const rows = build.measuredRows.get(block);
3195
- const pitches = rowPitches(rows.map((row) => row.mark), top, ends[index]);
3196
- plans.set(block, tablePlan(rows.map((row, at) => ({
3197
- kind: row.kind,
3198
- pitch: pitches[at]
3199
- })), room));
3200
- }
3201
- });
3202
- return plans;
3203
- }
3204
- function resources(images) {
3205
- return {
3206
- defaultStyle: DEFAULT_STYLE,
3207
- images
3208
- };
3209
- }
3210
- function stopIfCancelled(signal) {
3211
- if (signal?.aborted === true) throw new RenderRefusal("cancelled", "the render was cancelled");
3212
- }
3213
- /**
3214
- * `stopIfCancelled`, once the event loop has turned. Every await of a pass
3215
- * resolves without it turning -- pdfmake's work is synchronous and PDFKit's
3216
- * stream events come on the microtask queue -- so without this an abort
3217
- * from a timer arrived only once the PDF was written: a 417-page render
3218
- * resolved after 10.7 seconds with a PDF its caller had abandoned after 50
3219
- * milliseconds (2026-10-15).
3220
- */
3221
- async function stopIfCancelledSoon(signal) {
3222
- if (signal !== void 0) await new Promise((resolve) => setTimeout(resolve, 0));
3223
- stopIfCancelled(signal);
3224
- }
3225
- //#endregion
3226
- export { FACES as a, loadOnce as c, BILL_FACES as i, written as l, LIBERATION_SANS as n, glyphsOf as o, fromBase64 as r, glyphsOnce as s, render as t };
3227
-
3228
- //# sourceMappingURL=render-DkPoADDg.mjs.map