@patrickdk77/xfa-flatten 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/LICENSE +21 -0
  2. package/LICENSE-APACHE-2.0 +202 -0
  3. package/NOTICE +14 -0
  4. package/README.md +112 -2
  5. package/dist/barcode-paint.d.ts +11 -0
  6. package/dist/barcode-paint.js +135 -0
  7. package/dist/barcode.d.ts +45 -0
  8. package/dist/barcode.js +750 -0
  9. package/dist/canvas.d.ts +59 -0
  10. package/dist/canvas.js +179 -0
  11. package/dist/cli.d.ts +2 -0
  12. package/dist/cli.js +34 -0
  13. package/dist/css.d.ts +48 -0
  14. package/dist/css.js +288 -0
  15. package/dist/deadline.d.ts +6 -0
  16. package/dist/deadline.js +18 -0
  17. package/dist/filters.d.ts +21 -0
  18. package/dist/filters.js +296 -0
  19. package/dist/flatten.d.ts +25 -0
  20. package/dist/flatten.js +319 -0
  21. package/dist/font-metrics.d.ts +9 -0
  22. package/dist/font-metrics.js +215 -0
  23. package/dist/fonts.d.ts +36 -0
  24. package/dist/fonts.js +144 -0
  25. package/dist/images.d.ts +23 -0
  26. package/dist/images.js +519 -0
  27. package/dist/index.d.ts +2 -0
  28. package/dist/index.js +5 -0
  29. package/dist/index.mjs +3 -0
  30. package/dist/layout.d.ts +64 -0
  31. package/dist/layout.js +779 -0
  32. package/dist/limits.d.ts +2 -0
  33. package/dist/limits.js +6 -0
  34. package/dist/locale.d.ts +29 -0
  35. package/dist/locale.js +97 -0
  36. package/dist/paint.d.ts +15 -0
  37. package/dist/paint.js +533 -0
  38. package/dist/pdf-crypt.d.ts +35 -0
  39. package/dist/pdf-crypt.js +261 -0
  40. package/dist/pdf-read.d.ts +140 -0
  41. package/dist/pdf-read.js +1026 -0
  42. package/dist/pdf417-table.d.ts +2 -0
  43. package/dist/pdf417-table.js +146 -0
  44. package/dist/pdfjs-repair.d.ts +13 -0
  45. package/dist/pdfjs-repair.js +257 -0
  46. package/dist/pdfjs.d.ts +16 -0
  47. package/dist/pdfjs.js +62 -0
  48. package/dist/picture.d.ts +40 -0
  49. package/dist/picture.js +678 -0
  50. package/dist/saslprep.d.ts +11 -0
  51. package/dist/saslprep.js +178 -0
  52. package/dist/style.d.ts +29 -0
  53. package/dist/style.js +178 -0
  54. package/dist/text.d.ts +44 -0
  55. package/dist/text.js +199 -0
  56. package/dist/tiff.d.ts +3 -0
  57. package/dist/tiff.js +270 -0
  58. package/dist/tree.d.ts +23 -0
  59. package/dist/tree.js +54 -0
  60. package/dist/types.d.ts +31 -0
  61. package/dist/types.js +2 -0
  62. package/dist/writer.d.ts +38 -0
  63. package/dist/writer.js +145 -0
  64. package/dist/xfa-apply.d.ts +49 -0
  65. package/dist/xfa-apply.js +617 -0
  66. package/dist/xfa-model.d.ts +42 -0
  67. package/dist/xfa-model.js +227 -0
  68. package/dist/xfa-paint.d.ts +24 -0
  69. package/dist/xfa-paint.js +275 -0
  70. package/dist/xfa-spec.d.ts +47 -0
  71. package/dist/xfa-spec.js +3 -0
  72. package/dist/xml.d.ts +30 -0
  73. package/dist/xml.js +211 -0
  74. package/package.json +83 -4
@@ -0,0 +1,2 @@
1
+ /** The most pixels a decoded image may have (PNG, GIF, BMP and TIFF): 50 million. */
2
+ export declare const MAX_PIXELS = 50000000;
package/dist/limits.js ADDED
@@ -0,0 +1,6 @@
1
+ "use strict";
2
+ // Size limits shared by the image decoders.
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ exports.MAX_PIXELS = void 0;
5
+ /** The most pixels a decoded image may have (PNG, GIF, BMP and TIFF): 50 million. */
6
+ exports.MAX_PIXELS = 50_000_000;
@@ -0,0 +1,29 @@
1
+ import { type XmlNode } from './xml';
2
+ export interface LocaleInfo {
3
+ name: string;
4
+ months: string[];
5
+ monthsAbbr: string[];
6
+ days: string[];
7
+ daysAbbr: string[];
8
+ meridiem: [string, string];
9
+ eras: [string, string];
10
+ datePatterns: Record<string, string>;
11
+ timePatterns: Record<string, string>;
12
+ numberPatterns: Record<string, string>;
13
+ decimal: string;
14
+ grouping: string;
15
+ percent: string;
16
+ minus: string;
17
+ zero: string;
18
+ currencySymbol: string;
19
+ currencyIso: string;
20
+ currencyDecimal: string;
21
+ }
22
+ export declare const EN_US: LocaleInfo;
23
+ /** Looks locales up by name in a localeSet packet, falling back to the language alone, then en_US. */
24
+ export declare class Locales {
25
+ private readonly localeSet;
26
+ private readonly cache;
27
+ constructor(localeSet: XmlNode | null);
28
+ get(name: string): LocaleInfo;
29
+ }
package/dist/locale.js ADDED
@@ -0,0 +1,97 @@
1
+ "use strict";
2
+ // Locale data for picture clauses: month and day names, meridiem and era names, date, time and number patterns,
3
+ // number symbols and currency symbols. The form's localeSet packet supplies them; en_US is the fallback.
4
+ Object.defineProperty(exports, "__esModule", { value: true });
5
+ exports.Locales = exports.EN_US = void 0;
6
+ const xml_1 = require("./xml");
7
+ exports.EN_US = {
8
+ name: 'en_US',
9
+ months: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
10
+ monthsAbbr: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
11
+ days: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
12
+ daysAbbr: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
13
+ meridiem: ['AM', 'PM'],
14
+ eras: ['BC', 'AD'],
15
+ datePatterns: { full: 'EEEE, MMMM D, YYYY', long: 'MMMM D, YYYY', med: 'MMM D, YYYY', short: 'M/D/YY' },
16
+ timePatterns: { full: 'h:MM:SS A Z', long: 'h:MM:SS A Z', med: 'h:MM:SS A', short: 'h:MM A' },
17
+ numberPatterns: { numeric: 'z,zz9.zzz', currency: '$z,zz9.99|($z,zz9.99)', percent: 'z,zz9%' },
18
+ decimal: '.',
19
+ grouping: ',',
20
+ percent: '%',
21
+ minus: '-',
22
+ zero: '0',
23
+ currencySymbol: '$',
24
+ currencyIso: 'USD',
25
+ currencyDecimal: '.',
26
+ };
27
+ function names(cal, local, item, abbr) {
28
+ for (const list of (0, xml_1.children)(cal, local)) {
29
+ if ((list.attrs.abbr === '1') !== abbr)
30
+ continue;
31
+ const out = (0, xml_1.children)(list, item).map(n => (0, xml_1.textOf)(n));
32
+ if (out.length)
33
+ return out;
34
+ }
35
+ return null;
36
+ }
37
+ function named(parent, item) {
38
+ const out = {};
39
+ for (const n of (0, xml_1.children)(parent, item))
40
+ if (n.attrs.name)
41
+ out[n.attrs.name] = (0, xml_1.textOf)(n);
42
+ return out;
43
+ }
44
+ function fromXml(name, loc) {
45
+ const cal = (0, xml_1.child)(loc, 'calendarSymbols');
46
+ const mer = names(cal, 'meridiemNames', 'meridiem', false);
47
+ const era = names(cal, 'eraNames', 'era', false);
48
+ const syms = named((0, xml_1.child)(loc, 'numberSymbols'), 'numberSymbol');
49
+ const cur = named((0, xml_1.child)(loc, 'currencySymbols'), 'currencySymbol');
50
+ const dp = named((0, xml_1.child)(loc, 'datePatterns'), 'datePattern');
51
+ const tp = named((0, xml_1.child)(loc, 'timePatterns'), 'timePattern');
52
+ const np = named((0, xml_1.child)(loc, 'numberPatterns'), 'numberPattern');
53
+ return {
54
+ name,
55
+ months: names(cal, 'monthNames', 'month', false) ?? exports.EN_US.months,
56
+ monthsAbbr: names(cal, 'monthNames', 'month', true) ?? exports.EN_US.monthsAbbr,
57
+ days: names(cal, 'dayNames', 'day', false) ?? exports.EN_US.days,
58
+ daysAbbr: names(cal, 'dayNames', 'day', true) ?? exports.EN_US.daysAbbr,
59
+ meridiem: mer && mer.length >= 2 ? [mer[0], mer[1]] : exports.EN_US.meridiem,
60
+ eras: era && era.length >= 2 ? [era[0], era[1]] : exports.EN_US.eras,
61
+ datePatterns: { ...exports.EN_US.datePatterns, ...dp },
62
+ timePatterns: { ...exports.EN_US.timePatterns, ...tp },
63
+ numberPatterns: { ...exports.EN_US.numberPatterns, ...np },
64
+ decimal: syms.decimal ?? exports.EN_US.decimal,
65
+ grouping: syms.grouping ?? exports.EN_US.grouping,
66
+ percent: syms.percent ?? exports.EN_US.percent,
67
+ minus: syms.minus ?? exports.EN_US.minus,
68
+ zero: syms.zero ?? exports.EN_US.zero,
69
+ currencySymbol: cur.symbol ?? exports.EN_US.currencySymbol,
70
+ currencyIso: cur.isoname ?? exports.EN_US.currencyIso,
71
+ currencyDecimal: cur.decimal ?? exports.EN_US.currencyDecimal,
72
+ };
73
+ }
74
+ /** Looks locales up by name in a localeSet packet, falling back to the language alone, then en_US. */
75
+ class Locales {
76
+ localeSet;
77
+ cache = new Map();
78
+ constructor(localeSet) {
79
+ this.localeSet = localeSet;
80
+ }
81
+ get(name) {
82
+ const key = name.replace('-', '_');
83
+ const hit = this.cache.get(key);
84
+ if (hit)
85
+ return hit;
86
+ let found = exports.EN_US;
87
+ const list = (0, xml_1.children)(this.localeSet, 'locale');
88
+ const exact = list.find(l => (l.attrs.name ?? '').replace('-', '_') === key);
89
+ const lang = list.find(l => (l.attrs.name ?? '').split(/[_-]/)[0] === key.split('_')[0]);
90
+ const pick = exact ?? lang;
91
+ if (pick)
92
+ found = fromXml(pick.attrs.name ?? key, pick);
93
+ this.cache.set(key, found);
94
+ return found;
95
+ }
96
+ }
97
+ exports.Locales = Locales;
@@ -0,0 +1,15 @@
1
+ import type { Canvas } from './canvas';
2
+ import { type Box } from './layout';
3
+ export interface PaintEnv {
4
+ image(src: string): {
5
+ key: string;
6
+ width: number;
7
+ height: number;
8
+ } | null;
9
+ note(kind: string, detail: string): void;
10
+ unencodable(chars: string[]): void;
11
+ /** Called once per box; throws to stop painting (the caller's deadline). */
12
+ check?(): void;
13
+ }
14
+ /** Paints a box and its descendants. ox, oy is the parent's border box origin. */
15
+ export declare function paintBox(box: Box, canvas: Canvas, ox: number, oy: number, env: PaintEnv): void;
package/dist/paint.js ADDED
@@ -0,0 +1,533 @@
1
+ "use strict";
2
+ // Paints laid-out boxes onto a page canvas: backgrounds, borders, text, field values, check marks, SVG shapes
3
+ // and images.
4
+ Object.defineProperty(exports, "__esModule", { value: true });
5
+ exports.paintBox = paintBox;
6
+ const barcode_paint_1 = require("./barcode-paint");
7
+ const css_1 = require("./css");
8
+ const fonts_1 = require("./fonts");
9
+ const layout_1 = require("./layout");
10
+ const text_1 = require("./text");
11
+ const tree_1 = require("./tree");
12
+ const xfa_paint_1 = require("./xfa-paint");
13
+ const KAPPA = 0.5522847498;
14
+ function rectPoints(x, y, w, h) {
15
+ return [x, y, x + w, y, x + w, y + h, x, y + h];
16
+ }
17
+ function f(n) {
18
+ if (!Number.isFinite(n))
19
+ return '0';
20
+ const s = n.toFixed(3).replace(/0+$/, '').replace(/\.$/, '');
21
+ return s === '-0' ? '0' : s;
22
+ }
23
+ function rectPath(x, y, w, h, r = 0) {
24
+ if (r <= 0)
25
+ return `${f(x)} ${f(y)} ${f(w)} ${f(h)} re`;
26
+ const rr = Math.min(r, w / 2, h / 2);
27
+ const k = rr * KAPPA;
28
+ return [
29
+ `${f(x + rr)} ${f(y)} m`,
30
+ `${f(x + w - rr)} ${f(y)} l`,
31
+ `${f(x + w - rr + k)} ${f(y)} ${f(x + w)} ${f(y + rr - k)} ${f(x + w)} ${f(y + rr)} c`,
32
+ `${f(x + w)} ${f(y + h - rr)} l`,
33
+ `${f(x + w)} ${f(y + h - rr + k)} ${f(x + w - rr + k)} ${f(y + h)} ${f(x + w - rr)} ${f(y + h)} c`,
34
+ `${f(x + rr)} ${f(y + h)} l`,
35
+ `${f(x + rr - k)} ${f(y + h)} ${f(x)} ${f(y + h - rr + k)} ${f(x)} ${f(y + h - rr)} c`,
36
+ `${f(x)} ${f(y + rr)} l`,
37
+ `${f(x)} ${f(y + rr - k)} ${f(x + rr - k)} ${f(y)} ${f(x + rr)} ${f(y)} c h`,
38
+ ].join(' ');
39
+ }
40
+ function ellipsePath(cx, cy, rx, ry) {
41
+ const kx = rx * KAPPA;
42
+ const ky = ry * KAPPA;
43
+ return [
44
+ `${f(cx + rx)} ${f(cy)} m`,
45
+ `${f(cx + rx)} ${f(cy + ky)} ${f(cx + kx)} ${f(cy + ry)} ${f(cx)} ${f(cy + ry)} c`,
46
+ `${f(cx - kx)} ${f(cy + ry)} ${f(cx - rx)} ${f(cy + ky)} ${f(cx - rx)} ${f(cy)} c`,
47
+ `${f(cx - rx)} ${f(cy - ky)} ${f(cx - kx)} ${f(cy - ry)} ${f(cx)} ${f(cy - ry)} c`,
48
+ `${f(cx + kx)} ${f(cy - ry)} ${f(cx + rx)} ${f(cy - ky)} ${f(cx + rx)} ${f(cy)} c h`,
49
+ ].join(' ');
50
+ }
51
+ function averageColor(colors) {
52
+ const n = colors.length || 1;
53
+ let r = 0;
54
+ let g = 0;
55
+ let b = 0;
56
+ for (const c of colors) {
57
+ r += c[0];
58
+ g += c[1];
59
+ b += c[2];
60
+ }
61
+ return [r / n, g / n, b / n];
62
+ }
63
+ /** Fills a path with a paint: a flat color or a shading clipped to the path. */
64
+ function fillWith(canvas, paint, ops, points, x, y, w, h, env) {
65
+ if (paint.kind === 'color') {
66
+ canvas.fillPath(ops, points, paint.color);
67
+ return;
68
+ }
69
+ if (paint.kind === 'repeating' || paint.colors.length < 2) {
70
+ if (paint.kind === 'repeating')
71
+ env.note('pattern-approximated', 'A repeating gradient was drawn as its average color.');
72
+ canvas.fillPath(ops, points, averageColor(paint.colors));
73
+ return;
74
+ }
75
+ const first = paint.colors[0];
76
+ const last = paint.colors[paint.colors.length - 1];
77
+ let spec;
78
+ if (paint.kind === 'linear') {
79
+ const rad = (paint.angle * Math.PI) / 180;
80
+ const dx = Math.sin(rad);
81
+ const dy = -Math.cos(rad);
82
+ const half = Math.abs((w / 2) * dx) + Math.abs((h / 2) * dy);
83
+ const cx = x + w / 2;
84
+ const cy = y + h / 2;
85
+ spec = { type: 2, coords: [cx - dx * half, cy - dy * half, cx + dx * half, cy + dy * half], colors: [first, last] };
86
+ }
87
+ else {
88
+ const cx = x + w / 2;
89
+ const cy = y + h / 2;
90
+ spec = { type: 3, coords: [cx, cy, 0, cx, cy, Math.hypot(w / 2, h / 2)], colors: [first, last] };
91
+ }
92
+ canvas.shade(ops, points, spec);
93
+ }
94
+ function paintBackground(box, canvas, x, y, env) {
95
+ const paint = (0, css_1.parsePaint)(box.style.backgroundColor) ?? (0, css_1.parsePaint)(box.style.background);
96
+ if (!paint)
97
+ return;
98
+ const xb = box.node.xborder;
99
+ if (xb?.corners.some(c => c.radius > 0 && (c.join === 'round' || c.inverted))) {
100
+ const o = (0, xfa_paint_1.outlinePath)(xb, x, y, box.w, box.h);
101
+ fillWith(canvas, paint, o.ops, rectPoints(x, y, box.w, box.h), x, y, box.w, box.h, env);
102
+ return;
103
+ }
104
+ const radius = (0, css_1.parseLength)(box.style.borderRadius)?.px ?? 0;
105
+ fillWith(canvas, paint, rectPath(x, y, box.w, box.h, radius), rectPoints(x, y, box.w, box.h), x, y, box.w, box.h, env);
106
+ }
107
+ function borderColors(box) {
108
+ const raw = box.style.borderColor;
109
+ const parts = raw === undefined ? [] : String(raw).trim().split(/\s+/);
110
+ const base = box.inh.color;
111
+ const list = parts.length === 0 ? [base] : parts.map(p => (0, css_1.parseColor)(p) ?? base);
112
+ const four = list.length === 1 ? [list[0], list[0], list[0], list[0]] : list.length === 2 ? [list[0], list[1], list[0], list[1]] : list.length === 3 ? [list[0], list[1], list[2], list[1]] : list.slice(0, 4);
113
+ return four;
114
+ }
115
+ function paintBorders(box, canvas, x, y) {
116
+ const xb = box.node.xborder;
117
+ if (xb) {
118
+ (0, xfa_paint_1.paintXfaBorder)(canvas, xb, x, y, box.w, box.h);
119
+ return;
120
+ }
121
+ const [bt, br, bb, bl] = box.border;
122
+ if (bt + br + bb + bl <= 0)
123
+ return;
124
+ const styles = (0, layout_1.borderStyles)(box.style);
125
+ const colors = borderColors(box);
126
+ const w = box.w;
127
+ const h = box.h;
128
+ const radius = (0, css_1.parseLength)(box.style.borderRadius)?.px ?? 0;
129
+ const uniform = bt === br && br === bb && bb === bl && styles.every(s => s === styles[0]) && colors.every(c => c.join() === colors[0].join());
130
+ if (radius > 0 && uniform) {
131
+ const half = bt / 2;
132
+ canvas.strokePath(rectPath(x + half, y + half, w - bt, h - bt, Math.max(0, radius - half)), rectPoints(x, y, w, h), colors[0], bt, dashFor(styles[0], bt));
133
+ return;
134
+ }
135
+ // Each side is a trapezoid, mitered at the corners, as a browser draws solid borders.
136
+ const outer = [x, y, x + w, y, x + w, y + h, x, y + h];
137
+ const inner = [x + bl, y + bt, x + w - br, y + bt, x + w - br, y + h - bb, x + bl, y + h - bb];
138
+ const widths = [bt, br, bb, bl];
139
+ for (let side = 0; side < 4; side++) {
140
+ if (widths[side] <= 0)
141
+ continue;
142
+ const a = side;
143
+ const b = (side + 1) % 4;
144
+ const st = styles[side];
145
+ const dash = dashFor(st, widths[side]);
146
+ if (dash) {
147
+ // Dashed and dotted sides are stroked along their center line.
148
+ const half = widths[side] / 2;
149
+ const lines = [
150
+ [x, y + half, x + w, y + half],
151
+ [x + w - half, y, x + w - half, y + h],
152
+ [x + w, y + h - half, x, y + h - half],
153
+ [x + half, y + h, x + half, y],
154
+ ][side];
155
+ canvas.strokePath(`${f(lines[0])} ${f(lines[1])} m ${f(lines[2])} ${f(lines[3])} l`, lines, colors[side], widths[side], dash, st === 'dotted' ? 1 : 0);
156
+ continue;
157
+ }
158
+ const pts = [outer[a * 2], outer[a * 2 + 1], outer[b * 2], outer[b * 2 + 1], inner[b * 2], inner[b * 2 + 1], inner[a * 2], inner[a * 2 + 1]];
159
+ canvas.fillPolygon(pts, sideColor(colors[side], st, side));
160
+ }
161
+ }
162
+ /** Shades inset, outset, groove and ridge sides the way browsers do: darker on one pair of sides. */
163
+ function sideColor(c, style, side) {
164
+ const topLeft = side === 0 || side === 3;
165
+ let dark = false;
166
+ if (style === 'inset' || style === 'groove')
167
+ dark = topLeft;
168
+ else if (style === 'outset' || style === 'ridge')
169
+ dark = !topLeft;
170
+ else
171
+ return c;
172
+ if (!dark)
173
+ return c;
174
+ const isBlack = c[0] + c[1] + c[2] < 0.05;
175
+ if (isBlack)
176
+ return c;
177
+ return [c[0] * 0.6, c[1] * 0.6, c[2] * 0.6];
178
+ }
179
+ function dashFor(style, width) {
180
+ if (style === 'dashed')
181
+ return [Math.max(2, width * 3), Math.max(2, width * 3)];
182
+ if (style === 'dotted')
183
+ return [0, Math.max(1, width * 2)];
184
+ return null;
185
+ }
186
+ function drawLines(lines, canvas, cx, cy, env) {
187
+ for (const line of lines) {
188
+ for (const fr of line.frags) {
189
+ if (fr.inh.hidden)
190
+ continue;
191
+ const { bytes, unencodable } = (0, fonts_1.encodeWinAnsi)(fr.text);
192
+ if (unencodable.length)
193
+ env.unencodable(unencodable);
194
+ const baseline = cy + line.top + line.baseline - fr.raise;
195
+ const x = cx + fr.x;
196
+ if (bytes.some(b => b !== 0x20)) {
197
+ canvas.text(fr.font, fr.inh.size, x, baseline, bytes, fr.inh.color, {
198
+ charSpacing: fr.inh.letterSpacing,
199
+ wordSpacing: (0, text_1.justifySpacing)(fr),
200
+ hScale: fr.hScale,
201
+ width: fr.width,
202
+ });
203
+ }
204
+ decorate(canvas, fr.font, fr.inh.size, x, baseline, fr.width, fr.inh.color, fr.inh.underline, fr.inh.through);
205
+ }
206
+ }
207
+ }
208
+ function decorate(canvas, font, size, x, baseline, width, color, underline, through) {
209
+ if (!underline && !through)
210
+ return;
211
+ const m = (0, fonts_1.metricsOf)(font);
212
+ const thick = Math.max(0.5, (m.underlineThickness * size) / 1000);
213
+ if (underline)
214
+ canvas.fillRect(x, baseline - (m.underlinePosition * size) / 1000 - thick / 2, width, thick, color);
215
+ if (through)
216
+ canvas.fillRect(x, baseline - size * 0.3 - thick / 2, width, thick, color);
217
+ }
218
+ /** Draws one line of text in a field, vertically centered in the content box and clipped to it. */
219
+ function drawFieldLine(box, text, canvas, x, y, extraIndent, env) {
220
+ if (text === '')
221
+ return;
222
+ const cx = x + box.border[3] + box.padding[3] + extraIndent;
223
+ const cy = y + box.border[0] + box.padding[0];
224
+ const cw = box.w - box.border[1] - box.border[3] - box.padding[1] - box.padding[3] - extraIndent;
225
+ const ch = box.h - box.border[0] - box.border[2] - box.padding[0] - box.padding[2];
226
+ const font = (0, fonts_1.pickFont)({ family: box.inh.family, bold: box.inh.bold, italic: box.inh.italic });
227
+ const { bytes, unencodable } = (0, fonts_1.encodeWinAnsi)(text.replace(/[\r\n]+/g, ' '));
228
+ if (unencodable.length)
229
+ env.unencodable(unencodable);
230
+ const size = box.inh.size;
231
+ const lm = (0, fonts_1.lineMetrics)(font);
232
+ const textH = (lm.ascent + lm.descent) * size;
233
+ const baseline = cy + (ch - textH) / 2 + lm.ascent * size;
234
+ const scale = (0, fonts_1.familyScale)(box.inh.family, box.inh.bold);
235
+ const width = (metricsWidth(font, bytes) * size * scale) / 1000 + box.inh.letterSpacing * bytes.length;
236
+ let tx = cx;
237
+ const align = box.inh.textAlign;
238
+ if (align === 'center')
239
+ tx = cx + (cw - width) / 2;
240
+ else if (align === 'right' || align === 'end')
241
+ tx = cx + cw - width;
242
+ canvas.save();
243
+ canvas.clipRect(x + box.border[3], y + box.border[0], box.w - box.border[1] - box.border[3], box.h - box.border[0] - box.border[2]);
244
+ canvas.text(font, size, tx, baseline, bytes, box.inh.color, { charSpacing: box.inh.letterSpacing, hScale: scale * 100, width });
245
+ decorate(canvas, font, size, tx, baseline, width, box.inh.color, box.inh.underline, box.inh.through);
246
+ canvas.restore();
247
+ }
248
+ function metricsWidth(font, bytes) {
249
+ const widths = (0, fonts_1.metricsOf)(font).widths;
250
+ let t = 0;
251
+ for (const b of bytes)
252
+ t += widths[b] ?? 0;
253
+ return t;
254
+ }
255
+ function drawCheck(box, canvas, x, y) {
256
+ const radio = (0, tree_1.attrString)(box.node, 'type') === 'radio';
257
+ const checked = box.node.attrs.checked === true || box.node.attrs.checked === 'true';
258
+ const size = Math.min(box.w, box.h);
259
+ if (size <= 0)
260
+ return;
261
+ const bx = x + (box.w - size) / 2;
262
+ const by = y + (box.h - size) / 2;
263
+ const line = Math.max(0.5, size / 20);
264
+ if (radio) {
265
+ const r = size / 2 - line / 2;
266
+ canvas.strokePath(ellipsePath(bx + size / 2, by + size / 2, r, r), rectPoints(bx, by, size, size), [0, 0, 0], line, null);
267
+ if (checked)
268
+ canvas.fillPath(ellipsePath(bx + size / 2, by + size / 2, size / 4, size / 4), rectPoints(bx, by, size, size), [0, 0, 0]);
269
+ return;
270
+ }
271
+ canvas.strokePath(rectPath(bx + line / 2, by + line / 2, size - line, size - line), rectPoints(bx, by, size, size), [0, 0, 0], line, null);
272
+ if (checked) {
273
+ // ZapfDingbats code 0x34 is a check mark, 846 units wide.
274
+ const markSize = size * 0.8;
275
+ const markW = (846 * markSize) / 1000;
276
+ canvas.text('ZapfDingbats', markSize, bx + (size - markW) / 2, by + size / 2 + markSize * 0.35, [0x34], box.inh.color, { width: markW });
277
+ }
278
+ }
279
+ function svgLength(v, ref) {
280
+ if (typeof v === 'number')
281
+ return v;
282
+ if (typeof v === 'string')
283
+ return (0, css_1.resolveLength)((0, css_1.parseLength)(v), ref) ?? 0;
284
+ return 0;
285
+ }
286
+ function paintSvg(box, canvas, x, y, env) {
287
+ const w = box.w;
288
+ const h = box.h;
289
+ const vb = (0, tree_1.attrString)(box.node, 'viewBox')
290
+ ?.split(/[\s,]+/)
291
+ .map(Number);
292
+ const sx = vb && vb.length === 4 && vb[2] > 0 ? w / vb[2] : 1;
293
+ const sy = vb && vb.length === 4 && vb[3] > 0 ? h / vb[3] : 1;
294
+ for (const shape of box.node.children) {
295
+ const st = shape.style;
296
+ const strokeColor = (0, css_1.parseColor)(st.stroke);
297
+ const strokeW = (0, css_1.parseLength)(st.strokeWidth)?.px ?? 1;
298
+ const fill = (0, css_1.parsePaint)(st.fill);
299
+ const a = shape.attrs;
300
+ switch (shape.name) {
301
+ case 'line': {
302
+ const pts = [x + svgLength(a.x1, w), y + svgLength(a.y1, h), x + svgLength(a.x2, w), y + svgLength(a.y2, h)];
303
+ if (strokeColor)
304
+ canvas.strokePath(`${f(pts[0])} ${f(pts[1])} m ${f(pts[2])} ${f(pts[3])} l`, pts, strokeColor, strokeW, null);
305
+ break;
306
+ }
307
+ case 'rect': {
308
+ const rx = x + svgLength(a.x, w);
309
+ const ry = y + svgLength(a.y, h);
310
+ const rw = svgLength(a.width, w);
311
+ const rh = svgLength(a.height, h);
312
+ const rr = svgLength(a.rx, w);
313
+ if (fill)
314
+ fillWith(canvas, fill, rectPath(rx, ry, rw, rh, rr), rectPoints(rx, ry, rw, rh), rx, ry, rw, rh, env);
315
+ if (strokeColor)
316
+ canvas.strokePath(rectPath(rx, ry, rw, rh, rr), rectPoints(rx - strokeW / 2, ry - strokeW / 2, rw + strokeW, rh + strokeW), strokeColor, strokeW, null);
317
+ break;
318
+ }
319
+ case 'ellipse': {
320
+ const cx = x + svgLength(a.cx, w);
321
+ const cy = y + svgLength(a.cy, h);
322
+ const rx = svgLength(a.rx, w);
323
+ const ry = svgLength(a.ry, h);
324
+ const ops = ellipsePath(cx, cy, rx, ry);
325
+ if (fill)
326
+ fillWith(canvas, fill, ops, rectPoints(cx - rx, cy - ry, 2 * rx, 2 * ry), cx - rx, cy - ry, 2 * rx, 2 * ry, env);
327
+ if (strokeColor)
328
+ canvas.strokePath(ops, rectPoints(cx - rx, cy - ry, 2 * rx, 2 * ry), strokeColor, strokeW, null);
329
+ break;
330
+ }
331
+ case 'path': {
332
+ const d = (0, tree_1.attrString)(shape, 'd') ?? '';
333
+ const built = pathOps(d, x, y, sx, sy);
334
+ if (!built) {
335
+ env.note('svg-path', 'An SVG path with commands other than M, L, A and Z was not drawn.');
336
+ break;
337
+ }
338
+ if (fill)
339
+ canvas.fillPath(built.ops, built.points, fill.kind === 'color' ? fill.color : averageColor(fill.colors));
340
+ if (strokeColor)
341
+ canvas.strokePath(built.ops, built.points, strokeColor, strokeW, null);
342
+ break;
343
+ }
344
+ default:
345
+ break;
346
+ }
347
+ }
348
+ }
349
+ /** Converts an SVG path of M, L, A and Z commands, in a scaled viewBox, to PDF path operators. */
350
+ function pathOps(d, ox, oy, sx, sy) {
351
+ const tokens = d.match(/[A-Za-z]|-?(?:\d+\.?\d*|\.\d+)(?:e-?\d+)?/g) ?? [];
352
+ const ops = [];
353
+ const points = [];
354
+ let i = 0;
355
+ let cx = 0;
356
+ let cy = 0;
357
+ const num = () => Number(tokens[i++]);
358
+ const P = (px, py) => {
359
+ const X = ox + px * sx;
360
+ const Y = oy + py * sy;
361
+ points.push(X, Y);
362
+ return `${f(X)} ${f(Y)}`;
363
+ };
364
+ while (i < tokens.length) {
365
+ const cmd = tokens[i++];
366
+ if (cmd === 'M' || cmd === 'L') {
367
+ cx = num();
368
+ cy = num();
369
+ ops.push(`${P(cx, cy)} ${cmd === 'M' ? 'm' : 'l'}`);
370
+ }
371
+ else if (cmd === 'A') {
372
+ const rx = Math.abs(num());
373
+ const ry = Math.abs(num());
374
+ const rot = num();
375
+ const large = num();
376
+ const sweep = num();
377
+ const x2 = num();
378
+ const y2 = num();
379
+ for (const c of arcToBeziers(cx, cy, rx, ry, rot, large !== 0, sweep !== 0, x2, y2)) {
380
+ ops.push(`${P(c[0], c[1])} ${P(c[2], c[3])} ${P(c[4], c[5])} c`);
381
+ }
382
+ cx = x2;
383
+ cy = y2;
384
+ }
385
+ else if (cmd === 'Z' || cmd === 'z') {
386
+ ops.push('h');
387
+ }
388
+ else {
389
+ return null;
390
+ }
391
+ }
392
+ return { ops: ops.join(' '), points };
393
+ }
394
+ /** SVG endpoint arc to cubic Bezier segments (SVG 1.1 appendix F.6). */
395
+ function arcToBeziers(x1, y1, rxIn, ryIn, rotDeg, large, sweep, x2, y2) {
396
+ if (rxIn === 0 || ryIn === 0)
397
+ return [[x1, y1, x2, y2, x2, y2]];
398
+ const phi = (rotDeg * Math.PI) / 180;
399
+ const cos = Math.cos(phi);
400
+ const sin = Math.sin(phi);
401
+ const dx = (x1 - x2) / 2;
402
+ const dy = (y1 - y2) / 2;
403
+ const x1p = cos * dx + sin * dy;
404
+ const y1p = -sin * dx + cos * dy;
405
+ let rx = rxIn;
406
+ let ry = ryIn;
407
+ const lambda = (x1p * x1p) / (rx * rx) + (y1p * y1p) / (ry * ry);
408
+ if (lambda > 1) {
409
+ rx *= Math.sqrt(lambda);
410
+ ry *= Math.sqrt(lambda);
411
+ }
412
+ const num = rx * rx * ry * ry - rx * rx * y1p * y1p - ry * ry * x1p * x1p;
413
+ const den = rx * rx * y1p * y1p + ry * ry * x1p * x1p;
414
+ let coef = Math.sqrt(Math.max(0, num / den));
415
+ if (large === sweep)
416
+ coef = -coef;
417
+ const cxp = (coef * rx * y1p) / ry;
418
+ const cyp = (-coef * ry * x1p) / rx;
419
+ const ccx = cos * cxp - sin * cyp + (x1 + x2) / 2;
420
+ const ccy = sin * cxp + cos * cyp + (y1 + y2) / 2;
421
+ const angle = (ux, uy, vx, vy) => {
422
+ const a = Math.atan2(ux * vy - uy * vx, ux * vx + uy * vy);
423
+ return a;
424
+ };
425
+ const t1 = angle(1, 0, (x1p - cxp) / rx, (y1p - cyp) / ry);
426
+ let dt = angle((x1p - cxp) / rx, (y1p - cyp) / ry, (-x1p - cxp) / rx, (-y1p - cyp) / ry);
427
+ if (!sweep && dt > 0)
428
+ dt -= 2 * Math.PI;
429
+ else if (sweep && dt < 0)
430
+ dt += 2 * Math.PI;
431
+ const segs = Math.ceil(Math.abs(dt) / (Math.PI / 2));
432
+ const out = [];
433
+ const step = dt / segs;
434
+ const k = (4 / 3) * Math.tan(step / 4);
435
+ const pt = (t) => [ccx + rx * Math.cos(t) * cos - ry * Math.sin(t) * sin, ccy + rx * Math.cos(t) * sin + ry * Math.sin(t) * cos];
436
+ const der = (t) => [-rx * Math.sin(t) * cos - ry * Math.cos(t) * sin, -rx * Math.sin(t) * sin + ry * Math.cos(t) * cos];
437
+ for (let s = 0; s < segs; s++) {
438
+ const a = t1 + s * step;
439
+ const b = a + step;
440
+ const p0 = pt(a);
441
+ const p3 = pt(b);
442
+ const d0 = der(a);
443
+ const d3 = der(b);
444
+ out.push([p0[0] + k * d0[0], p0[1] + k * d0[1], p3[0] - k * d3[0], p3[1] - k * d3[1], p3[0], p3[1]]);
445
+ }
446
+ return out;
447
+ }
448
+ function paintImage(box, canvas, x, y, env) {
449
+ const src = (0, tree_1.attrString)(box.node, 'src') ?? '';
450
+ if (box.w <= 0 || box.h <= 0)
451
+ return;
452
+ const img = env.image(src);
453
+ if (!img)
454
+ return;
455
+ const fit = String(box.style.objectFit ?? 'fill');
456
+ let w = box.w;
457
+ let h = box.h;
458
+ if (fit === 'contain' && img.width > 0 && img.height > 0) {
459
+ const scale = Math.min(box.w / img.width, box.h / img.height);
460
+ w = img.width * scale;
461
+ h = img.height * scale;
462
+ }
463
+ canvas.image(img.key, 0, x, y, w, h);
464
+ }
465
+ function isPositioned(b) {
466
+ return b.positioned || b.transform !== null;
467
+ }
468
+ /** Paints a box and its descendants. ox, oy is the parent's border box origin. */
469
+ function paintBox(box, canvas, ox, oy, env) {
470
+ env.check?.();
471
+ let x = ox + box.x;
472
+ let y = oy + box.y;
473
+ const transformed = box.transform !== null;
474
+ if (box.transform) {
475
+ canvas.save();
476
+ canvas.transform([1, 0, 0, 1, x, y]);
477
+ canvas.transform(box.transform);
478
+ x = 0;
479
+ y = 0;
480
+ }
481
+ const node = box.node;
482
+ if (!box.inh.hidden && !node.classes.includes('xfaLink')) {
483
+ paintBackground(box, canvas, x, y, env);
484
+ paintBorders(box, canvas, x, y);
485
+ const cx = x + box.border[3] + box.padding[3];
486
+ const cy = y + box.border[0] + box.padding[0];
487
+ if (box.lines) {
488
+ if (node.name === 'textarea') {
489
+ canvas.save();
490
+ canvas.clipRect(x + box.border[3], y + box.border[0], box.w - box.border[1] - box.border[3], box.h - box.border[0] - box.border[2]);
491
+ drawLines(box.lines, canvas, cx, cy, env);
492
+ canvas.restore();
493
+ }
494
+ else
495
+ drawLines(box.lines, canvas, cx, cy, env);
496
+ }
497
+ if (node.name === 'input') {
498
+ const type = (0, tree_1.attrString)(node, 'type') ?? 'text';
499
+ if ((type === 'checkbox' || type === 'radio') && node.check)
500
+ (0, xfa_paint_1.paintCheck)(canvas, node.check, x, y, box.w, box.h, box.inh.color);
501
+ else if (type === 'checkbox' || type === 'radio')
502
+ drawCheck(box, canvas, x, y);
503
+ else
504
+ drawFieldLine(box, (0, tree_1.attrString)(node, 'value') ?? '', canvas, x, y, 0, env);
505
+ }
506
+ else if (node.name === 'select') {
507
+ drawFieldLine(box, (0, layout_1.selectedText)(node), canvas, x, y, 1, env);
508
+ }
509
+ else if (node.name === 'svg') {
510
+ paintSvg(box, canvas, x, y, env);
511
+ }
512
+ else if (node.name === 'img') {
513
+ paintImage(box, canvas, x, y, env);
514
+ }
515
+ if (node.barcode)
516
+ (0, barcode_paint_1.paintBarcode)(canvas, node.barcode, x + box.border[3] + box.padding[3], y + box.border[0] + box.padding[0], box.w - box.border[1] - box.border[3] - box.padding[1] - box.padding[3], box.h - box.border[0] - box.border[2] - box.padding[0] - box.padding[2], box.inh.color, env);
517
+ }
518
+ const clip = box.clip;
519
+ if (clip) {
520
+ canvas.save();
521
+ canvas.clipRect(x + box.border[3], y + box.border[0], box.w - box.border[1] - box.border[3], box.h - box.border[0] - box.border[2]);
522
+ }
523
+ for (const kid of box.kids)
524
+ if (!isPositioned(kid))
525
+ paintBox(kid, canvas, x, y, env);
526
+ for (const kid of box.kids)
527
+ if (isPositioned(kid))
528
+ paintBox(kid, canvas, x, y, env);
529
+ if (clip)
530
+ canvas.restore();
531
+ if (transformed)
532
+ canvas.restore();
533
+ }