@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.
- package/LICENSE +21 -0
- package/LICENSE-APACHE-2.0 +202 -0
- package/NOTICE +14 -0
- package/README.md +112 -2
- package/dist/barcode-paint.d.ts +11 -0
- package/dist/barcode-paint.js +135 -0
- package/dist/barcode.d.ts +45 -0
- package/dist/barcode.js +750 -0
- package/dist/canvas.d.ts +59 -0
- package/dist/canvas.js +179 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +34 -0
- package/dist/css.d.ts +48 -0
- package/dist/css.js +288 -0
- package/dist/deadline.d.ts +6 -0
- package/dist/deadline.js +18 -0
- package/dist/filters.d.ts +21 -0
- package/dist/filters.js +296 -0
- package/dist/flatten.d.ts +25 -0
- package/dist/flatten.js +319 -0
- package/dist/font-metrics.d.ts +9 -0
- package/dist/font-metrics.js +215 -0
- package/dist/fonts.d.ts +36 -0
- package/dist/fonts.js +144 -0
- package/dist/images.d.ts +23 -0
- package/dist/images.js +519 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +5 -0
- package/dist/index.mjs +3 -0
- package/dist/layout.d.ts +64 -0
- package/dist/layout.js +779 -0
- package/dist/limits.d.ts +2 -0
- package/dist/limits.js +6 -0
- package/dist/locale.d.ts +29 -0
- package/dist/locale.js +97 -0
- package/dist/paint.d.ts +15 -0
- package/dist/paint.js +533 -0
- package/dist/pdf-crypt.d.ts +35 -0
- package/dist/pdf-crypt.js +261 -0
- package/dist/pdf-read.d.ts +140 -0
- package/dist/pdf-read.js +1026 -0
- package/dist/pdf417-table.d.ts +2 -0
- package/dist/pdf417-table.js +146 -0
- package/dist/pdfjs-repair.d.ts +13 -0
- package/dist/pdfjs-repair.js +257 -0
- package/dist/pdfjs.d.ts +16 -0
- package/dist/pdfjs.js +62 -0
- package/dist/picture.d.ts +40 -0
- package/dist/picture.js +678 -0
- package/dist/saslprep.d.ts +11 -0
- package/dist/saslprep.js +178 -0
- package/dist/style.d.ts +29 -0
- package/dist/style.js +178 -0
- package/dist/text.d.ts +44 -0
- package/dist/text.js +199 -0
- package/dist/tiff.d.ts +3 -0
- package/dist/tiff.js +270 -0
- package/dist/tree.d.ts +23 -0
- package/dist/tree.js +54 -0
- package/dist/types.d.ts +31 -0
- package/dist/types.js +2 -0
- package/dist/writer.d.ts +38 -0
- package/dist/writer.js +145 -0
- package/dist/xfa-apply.d.ts +49 -0
- package/dist/xfa-apply.js +617 -0
- package/dist/xfa-model.d.ts +42 -0
- package/dist/xfa-model.js +227 -0
- package/dist/xfa-paint.d.ts +24 -0
- package/dist/xfa-paint.js +275 -0
- package/dist/xfa-spec.d.ts +47 -0
- package/dist/xfa-spec.js +3 -0
- package/dist/xml.d.ts +30 -0
- package/dist/xml.js +211 -0
- package/package.json +83 -4
package/dist/filters.js
ADDED
|
@@ -0,0 +1,296 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
// Stream filters the XFA packet reader needs: Flate (with PNG and TIFF predictors), LZW, ASCIIHex, ASCII85 and
|
|
3
|
+
// RunLength. TIFF image decoding uses the same LZW and predictor code.
|
|
4
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
5
|
+
exports.OutputLimitError = void 0;
|
|
6
|
+
exports.inflate = inflate;
|
|
7
|
+
exports.lzwDecode = lzwDecode;
|
|
8
|
+
exports.asciiHexDecode = asciiHexDecode;
|
|
9
|
+
exports.ascii85Decode = ascii85Decode;
|
|
10
|
+
exports.runLengthDecode = runLengthDecode;
|
|
11
|
+
exports.pngUnpredict = pngUnpredict;
|
|
12
|
+
exports.tiffUnpredict = tiffUnpredict;
|
|
13
|
+
const node_zlib_1 = require("node:zlib");
|
|
14
|
+
/** Thrown when a decoder's output would pass the limit its caller set. */
|
|
15
|
+
class OutputLimitError extends Error {
|
|
16
|
+
constructor(limit) {
|
|
17
|
+
super(`decoded data is larger than ${limit} bytes`);
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
exports.OutputLimitError = OutputLimitError;
|
|
21
|
+
/** The largest output a decoder gives when its caller sets no limit: 1 GiB less one byte, under Node's buffer limit. */
|
|
22
|
+
const NO_LIMIT = 2 ** 30 - 1;
|
|
23
|
+
/** zlib reports output past maxOutputLength as a RangeError (ERR_BUFFER_TOO_LARGE). */
|
|
24
|
+
function isSizeError(e) {
|
|
25
|
+
return e instanceof RangeError;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Inflates zlib data, tolerating a truncated or unterminated stream, then raw deflate data. Output past `limit` bytes
|
|
29
|
+
* throws OutputLimitError instead of being allocated.
|
|
30
|
+
*/
|
|
31
|
+
function inflate(data, limit = NO_LIMIT) {
|
|
32
|
+
const opts = { finishFlush: node_zlib_1.constants.Z_SYNC_FLUSH, maxOutputLength: Math.max(1, limit) };
|
|
33
|
+
const attempt = (run) => {
|
|
34
|
+
try {
|
|
35
|
+
return run();
|
|
36
|
+
}
|
|
37
|
+
catch (e) {
|
|
38
|
+
if (isSizeError(e))
|
|
39
|
+
throw new OutputLimitError(limit);
|
|
40
|
+
throw e;
|
|
41
|
+
}
|
|
42
|
+
};
|
|
43
|
+
try {
|
|
44
|
+
return attempt(() => (0, node_zlib_1.inflateSync)(data, opts));
|
|
45
|
+
}
|
|
46
|
+
catch (e) {
|
|
47
|
+
if (e instanceof OutputLimitError)
|
|
48
|
+
throw e;
|
|
49
|
+
try {
|
|
50
|
+
return attempt(() => (0, node_zlib_1.inflateRawSync)(data, opts));
|
|
51
|
+
}
|
|
52
|
+
catch (e2) {
|
|
53
|
+
if (e2 instanceof OutputLimitError)
|
|
54
|
+
throw e2;
|
|
55
|
+
return attempt(() => (0, node_zlib_1.inflateRawSync)(data.subarray(2), opts));
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
/** A byte buffer that grows by doubling and refuses to pass a limit. */
|
|
60
|
+
class Output {
|
|
61
|
+
limit;
|
|
62
|
+
buf = new Uint8Array(1024);
|
|
63
|
+
length = 0;
|
|
64
|
+
constructor(limit) {
|
|
65
|
+
this.limit = limit;
|
|
66
|
+
}
|
|
67
|
+
push(v) {
|
|
68
|
+
if (this.length >= this.limit)
|
|
69
|
+
throw new OutputLimitError(this.limit);
|
|
70
|
+
if (this.length >= this.buf.length) {
|
|
71
|
+
const next = new Uint8Array(Math.min(this.limit, this.buf.length * 2));
|
|
72
|
+
next.set(this.buf);
|
|
73
|
+
this.buf = next;
|
|
74
|
+
}
|
|
75
|
+
this.buf[this.length++] = v;
|
|
76
|
+
}
|
|
77
|
+
bytes() {
|
|
78
|
+
return this.buf.slice(0, this.length);
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* LZW as PDF and TIFF use it: MSB-first codes of 9 to 12 bits, 256 clears, 257 ends. earlyChange 1 widens the code
|
|
83
|
+
* one entry early, as PDF's default and TIFF do.
|
|
84
|
+
*/
|
|
85
|
+
function lzwDecode(data, earlyChange = 1, limit = NO_LIMIT) {
|
|
86
|
+
const out = new Output(limit);
|
|
87
|
+
const prefix = new Int32Array(4096);
|
|
88
|
+
const suffix = new Uint8Array(4096);
|
|
89
|
+
const length = new Int32Array(4096);
|
|
90
|
+
for (let i = 0; i < 256; i++) {
|
|
91
|
+
prefix[i] = -1;
|
|
92
|
+
suffix[i] = i;
|
|
93
|
+
length[i] = 1;
|
|
94
|
+
}
|
|
95
|
+
let next = 258;
|
|
96
|
+
let width = 9;
|
|
97
|
+
let prev = -1;
|
|
98
|
+
let bitBuf = 0;
|
|
99
|
+
let bitCount = 0;
|
|
100
|
+
let pos = 0;
|
|
101
|
+
const stack = new Uint8Array(4096);
|
|
102
|
+
const emit = (code) => {
|
|
103
|
+
let n = 0;
|
|
104
|
+
let c = code;
|
|
105
|
+
while (c >= 0 && n < 4096) {
|
|
106
|
+
stack[n++] = suffix[c];
|
|
107
|
+
c = prefix[c];
|
|
108
|
+
}
|
|
109
|
+
for (let i = n - 1; i >= 0; i--)
|
|
110
|
+
out.push(stack[i]);
|
|
111
|
+
return stack[n - 1];
|
|
112
|
+
};
|
|
113
|
+
while (true) {
|
|
114
|
+
while (bitCount < width) {
|
|
115
|
+
if (pos >= data.length)
|
|
116
|
+
return out.bytes();
|
|
117
|
+
bitBuf = ((bitBuf << 8) | data[pos++]) >>> 0;
|
|
118
|
+
bitCount += 8;
|
|
119
|
+
}
|
|
120
|
+
const code = (bitBuf >>> (bitCount - width)) & ((1 << width) - 1);
|
|
121
|
+
bitCount -= width;
|
|
122
|
+
bitBuf &= (1 << bitCount) - 1;
|
|
123
|
+
if (code === 256) {
|
|
124
|
+
next = 258;
|
|
125
|
+
width = 9;
|
|
126
|
+
prev = -1;
|
|
127
|
+
continue;
|
|
128
|
+
}
|
|
129
|
+
if (code === 257)
|
|
130
|
+
break;
|
|
131
|
+
if (prev < 0) {
|
|
132
|
+
if (code > 255)
|
|
133
|
+
break;
|
|
134
|
+
out.push(code);
|
|
135
|
+
prev = code;
|
|
136
|
+
continue;
|
|
137
|
+
}
|
|
138
|
+
let first;
|
|
139
|
+
if (code < next) {
|
|
140
|
+
first = emit(code);
|
|
141
|
+
}
|
|
142
|
+
else if (code === next) {
|
|
143
|
+
first = emit(prev);
|
|
144
|
+
out.push(first);
|
|
145
|
+
}
|
|
146
|
+
else
|
|
147
|
+
break;
|
|
148
|
+
if (next < 4096) {
|
|
149
|
+
prefix[next] = prev;
|
|
150
|
+
suffix[next] = first;
|
|
151
|
+
length[next] = length[prev] + 1;
|
|
152
|
+
next++;
|
|
153
|
+
}
|
|
154
|
+
prev = code;
|
|
155
|
+
if (next + earlyChange >= 1 << width && width < 12)
|
|
156
|
+
width++;
|
|
157
|
+
}
|
|
158
|
+
return out.bytes();
|
|
159
|
+
}
|
|
160
|
+
function asciiHexDecode(data) {
|
|
161
|
+
const out = [];
|
|
162
|
+
let hi = -1;
|
|
163
|
+
for (const b of data) {
|
|
164
|
+
if (b === 0x3e)
|
|
165
|
+
break;
|
|
166
|
+
let v = -1;
|
|
167
|
+
if (b >= 0x30 && b <= 0x39)
|
|
168
|
+
v = b - 0x30;
|
|
169
|
+
else if (b >= 0x41 && b <= 0x46)
|
|
170
|
+
v = b - 0x37;
|
|
171
|
+
else if (b >= 0x61 && b <= 0x66)
|
|
172
|
+
v = b - 0x57;
|
|
173
|
+
if (v < 0)
|
|
174
|
+
continue;
|
|
175
|
+
if (hi < 0)
|
|
176
|
+
hi = v;
|
|
177
|
+
else {
|
|
178
|
+
out.push((hi << 4) | v);
|
|
179
|
+
hi = -1;
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
if (hi >= 0)
|
|
183
|
+
out.push(hi << 4);
|
|
184
|
+
return Uint8Array.from(out);
|
|
185
|
+
}
|
|
186
|
+
function ascii85Decode(data) {
|
|
187
|
+
const out = [];
|
|
188
|
+
const group = [];
|
|
189
|
+
const flush = (n) => {
|
|
190
|
+
let v = 0;
|
|
191
|
+
for (let i = 0; i < 5; i++)
|
|
192
|
+
v = v * 85 + (i < group.length ? group[i] : 84);
|
|
193
|
+
const bytes = [(v >>> 24) & 255, (v >>> 16) & 255, (v >>> 8) & 255, v & 255];
|
|
194
|
+
for (let i = 0; i < n; i++)
|
|
195
|
+
out.push(bytes[i]);
|
|
196
|
+
group.length = 0;
|
|
197
|
+
};
|
|
198
|
+
for (const b of data) {
|
|
199
|
+
if (b === 0x7e)
|
|
200
|
+
break;
|
|
201
|
+
if (b === 0x7a && group.length === 0) {
|
|
202
|
+
out.push(0, 0, 0, 0);
|
|
203
|
+
continue;
|
|
204
|
+
}
|
|
205
|
+
if (b < 0x21 || b > 0x75)
|
|
206
|
+
continue;
|
|
207
|
+
group.push(b - 0x21);
|
|
208
|
+
if (group.length === 5)
|
|
209
|
+
flush(4);
|
|
210
|
+
}
|
|
211
|
+
if (group.length > 1)
|
|
212
|
+
flush(group.length - 1);
|
|
213
|
+
return Uint8Array.from(out);
|
|
214
|
+
}
|
|
215
|
+
function runLengthDecode(data, limit = NO_LIMIT) {
|
|
216
|
+
const out = new Output(limit);
|
|
217
|
+
let i = 0;
|
|
218
|
+
while (i < data.length) {
|
|
219
|
+
const n = data[i++];
|
|
220
|
+
if (n === 128)
|
|
221
|
+
break;
|
|
222
|
+
if (n < 128) {
|
|
223
|
+
for (let k = 0; k <= n && i < data.length; k++)
|
|
224
|
+
out.push(data[i++]);
|
|
225
|
+
}
|
|
226
|
+
else {
|
|
227
|
+
const b = data[i++] ?? 0;
|
|
228
|
+
for (let k = 0; k < 257 - n; k++)
|
|
229
|
+
out.push(b);
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
return out.bytes();
|
|
233
|
+
}
|
|
234
|
+
/** Undoes PNG row predictors (predictor 10 to 15) on rows of `columns` samples. */
|
|
235
|
+
function pngUnpredict(data, columns, colors, bits) {
|
|
236
|
+
const bpp = Math.max(1, Math.ceil((colors * bits) / 8));
|
|
237
|
+
const rowLen = Math.ceil((columns * colors * bits) / 8);
|
|
238
|
+
const rows = Math.floor(data.length / (rowLen + 1));
|
|
239
|
+
const out = new Uint8Array(rows * rowLen);
|
|
240
|
+
for (let r = 0; r < rows; r++) {
|
|
241
|
+
const type = data[r * (rowLen + 1)];
|
|
242
|
+
const src = r * (rowLen + 1) + 1;
|
|
243
|
+
const dst = r * rowLen;
|
|
244
|
+
for (let i = 0; i < rowLen; i++) {
|
|
245
|
+
const raw = data[src + i];
|
|
246
|
+
const left = i >= bpp ? out[dst + i - bpp] : 0;
|
|
247
|
+
const up = r > 0 ? out[dst - rowLen + i] : 0;
|
|
248
|
+
const ul = r > 0 && i >= bpp ? out[dst - rowLen + i - bpp] : 0;
|
|
249
|
+
let v = raw;
|
|
250
|
+
if (type === 1)
|
|
251
|
+
v = raw + left;
|
|
252
|
+
else if (type === 2)
|
|
253
|
+
v = raw + up;
|
|
254
|
+
else if (type === 3)
|
|
255
|
+
v = raw + ((left + up) >> 1);
|
|
256
|
+
else if (type === 4) {
|
|
257
|
+
const p = left + up - ul;
|
|
258
|
+
const pa = Math.abs(p - left);
|
|
259
|
+
const pb = Math.abs(p - up);
|
|
260
|
+
const pc = Math.abs(p - ul);
|
|
261
|
+
v = raw + (pa <= pb && pa <= pc ? left : pb <= pc ? up : ul);
|
|
262
|
+
}
|
|
263
|
+
out[dst + i] = v & 255;
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
return out;
|
|
267
|
+
}
|
|
268
|
+
/** Undoes TIFF predictor 2 (horizontal differencing) in place, for 8 and 16 bit samples. */
|
|
269
|
+
function tiffUnpredict(data, columns, colors, bits, littleEndian = false) {
|
|
270
|
+
if (bits === 8) {
|
|
271
|
+
const rowLen = columns * colors;
|
|
272
|
+
for (let r = 0; r + rowLen <= data.length; r += rowLen) {
|
|
273
|
+
for (let i = colors; i < rowLen; i++)
|
|
274
|
+
data[r + i] = (data[r + i] + data[r + i - colors]) & 255;
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
else if (bits === 16) {
|
|
278
|
+
const rowLen = columns * colors * 2;
|
|
279
|
+
const rd = (o) => (littleEndian ? data[o] | (data[o + 1] << 8) : (data[o] << 8) | data[o + 1]);
|
|
280
|
+
const wr = (o, v) => {
|
|
281
|
+
if (littleEndian) {
|
|
282
|
+
data[o] = v & 255;
|
|
283
|
+
data[o + 1] = (v >> 8) & 255;
|
|
284
|
+
}
|
|
285
|
+
else {
|
|
286
|
+
data[o] = (v >> 8) & 255;
|
|
287
|
+
data[o + 1] = v & 255;
|
|
288
|
+
}
|
|
289
|
+
};
|
|
290
|
+
for (let r = 0; r + rowLen <= data.length; r += rowLen) {
|
|
291
|
+
for (let i = colors * 2; i < rowLen; i += 2)
|
|
292
|
+
wr(r + i, (rd(r + i) + rd(r + i - colors * 2)) & 0xffff);
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
return data;
|
|
296
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { type Overflow } from './canvas';
|
|
2
|
+
import type { FlattenOptions, FlattenResult } from './types';
|
|
3
|
+
import { type FieldValueStat } from './xfa-apply';
|
|
4
|
+
/** Internal statistics for the corpus checks. */
|
|
5
|
+
export interface FlattenStats {
|
|
6
|
+
overflow: Overflow;
|
|
7
|
+
/** Whether the template packets were read. */
|
|
8
|
+
template: boolean;
|
|
9
|
+
/** HTML containers matched to a template element, and those that were not. */
|
|
10
|
+
mapped: number;
|
|
11
|
+
unmapped: number;
|
|
12
|
+
fields: FieldValueStat[];
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* The passwords to try, as pdf-defuse takes them: each one given, in order, then the empty password last, so a password
|
|
16
|
+
* meant for other files cannot lock out one that opens without a password.
|
|
17
|
+
*/
|
|
18
|
+
export declare function passwordList(password: string | readonly string[] | undefined): string[];
|
|
19
|
+
/** Flattens and also returns internal statistics; flattenXfa is the public entry point. */
|
|
20
|
+
export declare function flattenWithStats(bytes: Uint8Array, options?: FlattenOptions): Promise<{
|
|
21
|
+
result: FlattenResult;
|
|
22
|
+
stats: FlattenStats;
|
|
23
|
+
}>;
|
|
24
|
+
/** Flattens a dynamic XFA form PDF into a plain PDF. */
|
|
25
|
+
export declare function flattenXfa(bytes: Uint8Array, options?: FlattenOptions): Promise<FlattenResult>;
|
package/dist/flatten.js
ADDED
|
@@ -0,0 +1,319 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
// flattenXfa: lays a dynamic XFA form out with pdf.js and writes its pages as a plain PDF.
|
|
3
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
4
|
+
exports.passwordList = passwordList;
|
|
5
|
+
exports.flattenWithStats = flattenWithStats;
|
|
6
|
+
exports.flattenXfa = flattenXfa;
|
|
7
|
+
const node_buffer_1 = require("node:buffer");
|
|
8
|
+
const canvas_1 = require("./canvas");
|
|
9
|
+
const deadline_1 = require("./deadline");
|
|
10
|
+
const images_1 = require("./images");
|
|
11
|
+
const layout_1 = require("./layout");
|
|
12
|
+
const paint_1 = require("./paint");
|
|
13
|
+
const pdf_read_1 = require("./pdf-read");
|
|
14
|
+
const pdfjs_1 = require("./pdfjs");
|
|
15
|
+
const pdfjs_repair_1 = require("./pdfjs-repair");
|
|
16
|
+
const style_1 = require("./style");
|
|
17
|
+
const tree_1 = require("./tree");
|
|
18
|
+
const writer_1 = require("./writer");
|
|
19
|
+
const xfa_apply_1 = require("./xfa-apply");
|
|
20
|
+
const xfa_model_1 = require("./xfa-model");
|
|
21
|
+
const xfa_paint_1 = require("./xfa-paint");
|
|
22
|
+
/** Script notes per event kind before the rest are counted in one note. */
|
|
23
|
+
const SCRIPT_NOTE_CAP = 25;
|
|
24
|
+
/** ToUnicode for the ZapfDingbats check marks, so text extraction reads them. */
|
|
25
|
+
const CHECK_MARK_CMAP = [
|
|
26
|
+
'/CIDInit /ProcSet findresource begin',
|
|
27
|
+
'12 dict begin',
|
|
28
|
+
'begincmap',
|
|
29
|
+
'/CIDSystemInfo << /Registry (Adobe) /Ordering (UCS) /Supplement 0 >> def',
|
|
30
|
+
'/CMapName /Adobe-Identity-UCS def',
|
|
31
|
+
'/CMapType 2 def',
|
|
32
|
+
'1 begincodespacerange',
|
|
33
|
+
'<00> <FF>',
|
|
34
|
+
'endcodespacerange',
|
|
35
|
+
`${xfa_paint_1.MARK_UNICODE.length} beginbfchar`,
|
|
36
|
+
...xfa_paint_1.MARK_UNICODE.map(([c, u]) => `<${c.toString(16).padStart(2, '0').toUpperCase()}> <${u.toString(16).padStart(4, '0').toUpperCase()}>`),
|
|
37
|
+
'endbfchar',
|
|
38
|
+
'endcmap',
|
|
39
|
+
'CMapName currentdict /CMap defineresource pop',
|
|
40
|
+
'end',
|
|
41
|
+
'end',
|
|
42
|
+
].join('\n');
|
|
43
|
+
class Notes {
|
|
44
|
+
list = [];
|
|
45
|
+
seen = new Set();
|
|
46
|
+
add(kind, location, detail) {
|
|
47
|
+
const k = `${kind}\u0000${location}\u0000${detail}`;
|
|
48
|
+
if (this.seen.has(k))
|
|
49
|
+
return;
|
|
50
|
+
this.seen.add(k);
|
|
51
|
+
this.list.push({ kind, location, detail });
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
function collectImages(node, out) {
|
|
55
|
+
if (node.name === 'img' && typeof node.attrs.src === 'string')
|
|
56
|
+
out.add(node.attrs.src);
|
|
57
|
+
for (const k of node.children)
|
|
58
|
+
collectImages(k, out);
|
|
59
|
+
}
|
|
60
|
+
async function decodeImages(root, notes, deadline) {
|
|
61
|
+
const srcs = new Set();
|
|
62
|
+
collectImages(root, srcs);
|
|
63
|
+
const out = new Map();
|
|
64
|
+
let n = 0;
|
|
65
|
+
for (const src of srcs) {
|
|
66
|
+
(0, deadline_1.checkDeadline)(deadline);
|
|
67
|
+
const blob = src.startsWith('blob:') ? (0, node_buffer_1.resolveObjectURL)(src) : undefined;
|
|
68
|
+
if (!blob) {
|
|
69
|
+
notes.add('image-source', 'document', 'An image whose data pdf.js did not hand over was not drawn.');
|
|
70
|
+
continue;
|
|
71
|
+
}
|
|
72
|
+
const bytes = new Uint8Array(await blob.arrayBuffer());
|
|
73
|
+
URL.revokeObjectURL(src);
|
|
74
|
+
const result = (0, images_1.decodeImage)(bytes);
|
|
75
|
+
if (!result.ok) {
|
|
76
|
+
notes.add('image-format', 'document', `An image was not drawn: ${result.reason}.`);
|
|
77
|
+
continue;
|
|
78
|
+
}
|
|
79
|
+
n++;
|
|
80
|
+
out.set(src, { key: `Im${n}`, image: result.image, ref: null });
|
|
81
|
+
}
|
|
82
|
+
return out;
|
|
83
|
+
}
|
|
84
|
+
function writeImage(writer, img) {
|
|
85
|
+
const dict = {
|
|
86
|
+
Type: new writer_1.Name('XObject'),
|
|
87
|
+
Subtype: new writer_1.Name('Image'),
|
|
88
|
+
Width: img.width,
|
|
89
|
+
Height: img.height,
|
|
90
|
+
ColorSpace: new writer_1.Name(img.colorSpace),
|
|
91
|
+
BitsPerComponent: 8,
|
|
92
|
+
};
|
|
93
|
+
if (img.decode)
|
|
94
|
+
dict.Decode = img.decode;
|
|
95
|
+
if (img.alpha) {
|
|
96
|
+
dict.SMask = writer.addStream({ Type: new writer_1.Name('XObject'), Subtype: new writer_1.Name('Image'), Width: img.width, Height: img.height, ColorSpace: new writer_1.Name('DeviceGray'), BitsPerComponent: 8 }, img.alpha);
|
|
97
|
+
}
|
|
98
|
+
if (img.dct)
|
|
99
|
+
return writer.addStream({ ...dict, Filter: new writer_1.Name('DCTDecode') }, img.data, false);
|
|
100
|
+
return writer.addStream(dict, img.data);
|
|
101
|
+
}
|
|
102
|
+
function pageNodes(root) {
|
|
103
|
+
if (root.classes.includes('xfaPage'))
|
|
104
|
+
return [root];
|
|
105
|
+
return root.children.filter(c => c.classes.includes('xfaPage'));
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* The passwords to try, as pdf-defuse takes them: each one given, in order, then the empty password last, so a password
|
|
109
|
+
* meant for other files cannot lock out one that opens without a password.
|
|
110
|
+
*/
|
|
111
|
+
function passwordList(password) {
|
|
112
|
+
const given = typeof password === 'string' ? [password] : (password ?? []);
|
|
113
|
+
return [...new Set([...given, ''])];
|
|
114
|
+
}
|
|
115
|
+
/** Reads the template and applies it to pdf.js's tree; notes the scripts that did not run. */
|
|
116
|
+
function applyXfa(bytes, passwords, root, notes, stats, deadline) {
|
|
117
|
+
const model = (0, xfa_model_1.loadModel)(bytes, passwords, deadline);
|
|
118
|
+
if (!model) {
|
|
119
|
+
notes.add('template-unread', 'document', 'The XFA template could not be read, so picture clauses, check marks, edge styles and barcodes were drawn as pdf.js gives them.');
|
|
120
|
+
return;
|
|
121
|
+
}
|
|
122
|
+
stats.template = true;
|
|
123
|
+
const applied = (0, xfa_apply_1.applyTemplate)(model, root, { deadline, note: (kind, location, detail) => notes.add(kind, location, detail) });
|
|
124
|
+
stats.mapped = applied.mapped;
|
|
125
|
+
stats.unmapped = applied.unmapped;
|
|
126
|
+
stats.fields = applied.fields;
|
|
127
|
+
for (const img of (0, xfa_apply_1.hrefImages)(model)) {
|
|
128
|
+
notes.add('image-href', img.location, `An image given only as a path to a file (${img.href.slice(0, 80)}) was not drawn; the PDF does not carry the file.`);
|
|
129
|
+
}
|
|
130
|
+
const perKind = new Map();
|
|
131
|
+
for (const s of (0, xfa_apply_1.openScripts)(model)) {
|
|
132
|
+
const n = (perKind.get(s.kind) ?? 0) + 1;
|
|
133
|
+
perKind.set(s.kind, n);
|
|
134
|
+
const article = /^[aeiou]/.test(s.kind) ? 'An' : 'A';
|
|
135
|
+
if (n <= SCRIPT_NOTE_CAP)
|
|
136
|
+
notes.add('script-not-run', s.location, `${article} ${s.kind} script did not run; what it would change on the form is not shown.`);
|
|
137
|
+
}
|
|
138
|
+
for (const [kind, n] of perKind) {
|
|
139
|
+
if (n > SCRIPT_NOTE_CAP)
|
|
140
|
+
notes.add('script-not-run', 'document', `${n - SCRIPT_NOTE_CAP} more ${kind} scripts did not run (${n} in all).`);
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
/** xfaProblem, giving no cause once the deadline has passed. */
|
|
144
|
+
function problemOf(bytes, passwords, deadline) {
|
|
145
|
+
try {
|
|
146
|
+
return (0, pdfjs_repair_1.xfaProblem)(bytes, passwords, deadline);
|
|
147
|
+
}
|
|
148
|
+
catch (e) {
|
|
149
|
+
if (e instanceof deadline_1.DeadlineError)
|
|
150
|
+
return null;
|
|
151
|
+
throw e;
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
/** Flattens and also returns internal statistics; flattenXfa is the public entry point. */
|
|
155
|
+
async function flattenWithStats(bytes, options = {}) {
|
|
156
|
+
const notes = new Notes();
|
|
157
|
+
const stats = { overflow: { count: 0, worst: 0 }, template: false, mapped: 0, unmapped: 0, fields: [] };
|
|
158
|
+
const { deadline } = options;
|
|
159
|
+
const passwords = passwordList(options.password);
|
|
160
|
+
let doc;
|
|
161
|
+
// The bytes pdf.js laid out: the caller's, or the repaired copy made for pdf.js alone. The template is read from the
|
|
162
|
+
// same bytes, so the two agree.
|
|
163
|
+
let layoutBytes = bytes;
|
|
164
|
+
try {
|
|
165
|
+
(0, deadline_1.checkDeadline)(deadline);
|
|
166
|
+
const inspected = (0, pdf_read_1.inspectPdf)(bytes, passwords, deadline);
|
|
167
|
+
if (inspected.oversize) {
|
|
168
|
+
notes.add('too-large', 'document', `The form's XFA decodes to more than ${pdf_read_1.XFA_LIMIT / 1048576} MiB (or one of its streams to more than ${pdf_read_1.DECODE_LIMIT / 1048576} MiB), so it was not laid out.`);
|
|
169
|
+
return { result: { status: 'failed', notes: notes.list }, stats };
|
|
170
|
+
}
|
|
171
|
+
if (inspected.overBudget) {
|
|
172
|
+
notes.add('too-complex', 'document', 'The PDF is damaged in a way that makes reading it take far longer than its size warrants, so it was not laid out.');
|
|
173
|
+
return { result: { status: 'failed', notes: notes.list }, stats };
|
|
174
|
+
}
|
|
175
|
+
const opened = inspected.password;
|
|
176
|
+
const pdfjsPasswords = opened === null ? passwords : [...new Set([opened, ...passwords])];
|
|
177
|
+
try {
|
|
178
|
+
doc = await (0, pdfjs_1.openXfa)(bytes, pdfjsPasswords);
|
|
179
|
+
}
|
|
180
|
+
catch (e) {
|
|
181
|
+
if ((0, pdfjs_1.isPasswordError)(e))
|
|
182
|
+
throw e;
|
|
183
|
+
(0, deadline_1.checkDeadline)(deadline);
|
|
184
|
+
const repair = (0, pdfjs_repair_1.repairForPdfjs)(bytes, passwords, deadline);
|
|
185
|
+
if (!repair)
|
|
186
|
+
throw e;
|
|
187
|
+
try {
|
|
188
|
+
doc = await (0, pdfjs_1.openXfa)(repair.bytes, pdfjsPasswords);
|
|
189
|
+
}
|
|
190
|
+
catch {
|
|
191
|
+
throw e;
|
|
192
|
+
}
|
|
193
|
+
layoutBytes = repair.bytes;
|
|
194
|
+
for (const fix of repair.fixes)
|
|
195
|
+
notes.add('layout-repair', 'document', fix);
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
catch (e) {
|
|
199
|
+
if (e instanceof deadline_1.DeadlineError)
|
|
200
|
+
notes.add('deadline', 'document', 'The deadline passed before the form was laid out.');
|
|
201
|
+
else {
|
|
202
|
+
const msg = e instanceof Error ? e.message : String(e);
|
|
203
|
+
const cause = (0, pdfjs_1.isPasswordError)(e) ? null : problemOf(bytes, passwords, deadline);
|
|
204
|
+
notes.add('layout-error', 'document', `pdf.js could not open or lay out the form: ${msg}${cause ? `. ${cause}` : ''}`);
|
|
205
|
+
}
|
|
206
|
+
return { result: { status: 'failed', notes: notes.list }, stats };
|
|
207
|
+
}
|
|
208
|
+
try {
|
|
209
|
+
if (!doc.pureXfa)
|
|
210
|
+
return { result: { status: 'unchanged', notes: notes.list }, stats };
|
|
211
|
+
const root = (0, tree_1.toTree)(doc.html);
|
|
212
|
+
const pages = root ? pageNodes(root) : [];
|
|
213
|
+
if (!root || pages.length === 0) {
|
|
214
|
+
notes.add('layout-error', 'document', 'pdf.js returned no pages for the form.');
|
|
215
|
+
return { result: { status: 'failed', notes: notes.list }, stats };
|
|
216
|
+
}
|
|
217
|
+
(0, deadline_1.checkDeadline)(deadline);
|
|
218
|
+
applyXfa(layoutBytes, passwords, root, notes, stats, deadline);
|
|
219
|
+
(0, deadline_1.checkDeadline)(deadline);
|
|
220
|
+
const writer = new writer_1.PdfWriter();
|
|
221
|
+
const catalog = writer.reserve();
|
|
222
|
+
const pagesRef = writer.reserve();
|
|
223
|
+
const images = await decodeImages(root, notes, deadline);
|
|
224
|
+
const check = () => (0, deadline_1.checkDeadline)(deadline);
|
|
225
|
+
const fontRefs = new Map();
|
|
226
|
+
const pageRefs = [];
|
|
227
|
+
for (let i = 0; i < pages.length; i++) {
|
|
228
|
+
(0, deadline_1.checkDeadline)(deadline);
|
|
229
|
+
const location = `page ${i + 1}`;
|
|
230
|
+
const size = doc.pages[i] ?? { width: 612, height: 792 };
|
|
231
|
+
const pageBox = (0, layout_1.layoutBox)(pages[i], root, style_1.ROOT_INHERITED, { cw: size.width, ch: size.height, forcedW: size.width, forcedH: size.height }, { env: { imageSize: src => images.get(src)?.image ?? null, check } });
|
|
232
|
+
pageBox.x = 0;
|
|
233
|
+
pageBox.y = 0;
|
|
234
|
+
(0, layout_1.reflowPage)(pageBox);
|
|
235
|
+
const canvas = new canvas_1.Canvas(size.width, size.height);
|
|
236
|
+
canvas.clipRect(0, 0, size.width, size.height, false);
|
|
237
|
+
const unencodable = new Set();
|
|
238
|
+
(0, paint_1.paintBox)(pageBox, canvas, 0, 0, {
|
|
239
|
+
image: src => {
|
|
240
|
+
const img = images.get(src);
|
|
241
|
+
if (!img)
|
|
242
|
+
return null;
|
|
243
|
+
img.ref ??= writeImage(writer, img.image);
|
|
244
|
+
return { key: img.key, width: img.image.width, height: img.image.height };
|
|
245
|
+
},
|
|
246
|
+
note: (kind, detail) => notes.add(kind, location, detail),
|
|
247
|
+
check,
|
|
248
|
+
unencodable: chars => {
|
|
249
|
+
for (const c of chars)
|
|
250
|
+
unencodable.add(c);
|
|
251
|
+
},
|
|
252
|
+
});
|
|
253
|
+
if (unencodable.size > 0) {
|
|
254
|
+
const list = [...unencodable].map(c => `U+${(c.codePointAt(0) ?? 0).toString(16).toUpperCase().padStart(4, '0')}`).join(' ');
|
|
255
|
+
notes.add('unencodable-text', location, `Characters the standard fonts cannot show were drawn as '?' or without their accent: ${list}.`);
|
|
256
|
+
}
|
|
257
|
+
stats.overflow.count += canvas.overflow.count;
|
|
258
|
+
stats.overflow.worst = Math.max(stats.overflow.worst, canvas.overflow.worst);
|
|
259
|
+
const fontDict = {};
|
|
260
|
+
for (const font of canvas.fonts) {
|
|
261
|
+
let ref = fontRefs.get(font);
|
|
262
|
+
if (!ref) {
|
|
263
|
+
const dict = { Type: new writer_1.Name('Font'), Subtype: new writer_1.Name('Type1'), BaseFont: new writer_1.Name(font) };
|
|
264
|
+
if (font !== 'ZapfDingbats')
|
|
265
|
+
dict.Encoding = new writer_1.Name('WinAnsiEncoding');
|
|
266
|
+
else
|
|
267
|
+
dict.ToUnicode = writer.addStream({}, Buffer.from(CHECK_MARK_CMAP, 'latin1'));
|
|
268
|
+
ref = writer.add(dict);
|
|
269
|
+
fontRefs.set(font, ref);
|
|
270
|
+
}
|
|
271
|
+
fontDict[(0, canvas_1.fontKey)(font)] = ref;
|
|
272
|
+
}
|
|
273
|
+
const xobjects = {};
|
|
274
|
+
for (const key of canvas.images.keys()) {
|
|
275
|
+
for (const img of images.values())
|
|
276
|
+
if (img.key === key && img.ref)
|
|
277
|
+
xobjects[key] = img.ref;
|
|
278
|
+
}
|
|
279
|
+
const shadings = {};
|
|
280
|
+
canvas.shadings.forEach((sh, k) => {
|
|
281
|
+
shadings[`Sh${k + 1}`] = writer.add({
|
|
282
|
+
ShadingType: sh.type,
|
|
283
|
+
ColorSpace: new writer_1.Name('DeviceRGB'),
|
|
284
|
+
Coords: sh.coords,
|
|
285
|
+
Function: { FunctionType: 2, Domain: [0, 1], C0: [...sh.colors[0]], C1: [...sh.colors[1]], N: 1 },
|
|
286
|
+
Extend: [true, true],
|
|
287
|
+
});
|
|
288
|
+
});
|
|
289
|
+
const resources = {};
|
|
290
|
+
if (Object.keys(fontDict).length)
|
|
291
|
+
resources.Font = fontDict;
|
|
292
|
+
if (Object.keys(xobjects).length)
|
|
293
|
+
resources.XObject = xobjects;
|
|
294
|
+
if (Object.keys(shadings).length)
|
|
295
|
+
resources.Shading = shadings;
|
|
296
|
+
const contents = writer.addStream({}, canvas.content());
|
|
297
|
+
pageRefs.push(writer.add({ Type: new writer_1.Name('Page'), Parent: pagesRef, MediaBox: [0, 0, size.width, size.height], Resources: resources, Contents: contents }));
|
|
298
|
+
}
|
|
299
|
+
writer.set(pagesRef, { Type: new writer_1.Name('Pages'), Kids: pageRefs, Count: pageRefs.length });
|
|
300
|
+
writer.set(catalog, { Type: new writer_1.Name('Catalog'), Pages: pagesRef });
|
|
301
|
+
const info = writer.add({ Producer: 'xfa-flatten' });
|
|
302
|
+
const out = writer.finish(catalog, info);
|
|
303
|
+
return { result: { status: 'flattened', bytes: out, pages: pageRefs.length, notes: notes.list }, stats };
|
|
304
|
+
}
|
|
305
|
+
catch (e) {
|
|
306
|
+
if (e instanceof deadline_1.DeadlineError)
|
|
307
|
+
notes.add('deadline', 'document', 'The deadline passed before the form was drawn.');
|
|
308
|
+
else
|
|
309
|
+
notes.add('render-error', 'document', `The form could not be drawn: ${e instanceof Error ? e.message : String(e)}`);
|
|
310
|
+
return { result: { status: 'failed', notes: notes.list }, stats };
|
|
311
|
+
}
|
|
312
|
+
finally {
|
|
313
|
+
await doc.close().catch(() => undefined);
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
/** Flattens a dynamic XFA form PDF into a plain PDF. */
|
|
317
|
+
async function flattenXfa(bytes, options = {}) {
|
|
318
|
+
return (await flattenWithStats(bytes, options)).result;
|
|
319
|
+
}
|