@aboutgeo/pdiiif 0.0.0-stage → 0.2.7

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 (69) hide show
  1. package/README.md +169 -2
  2. package/dist/__tests__/parser.test.d.ts +1 -0
  3. package/dist/__tests__/pdf.spec.d.ts +1 -0
  4. package/dist/__tests__/region.test.d.ts +1 -0
  5. package/dist/__tests__/setupJest.d.ts +0 -0
  6. package/dist/assets/optimization.worker-C8u4PFfM.js +886 -0
  7. package/dist/assets/optimization.worker-C8u4PFfM.js.map +1 -0
  8. package/dist/convert.d.ts +223 -0
  9. package/dist/download.d.ts +115 -0
  10. package/dist/iiif.d.ts +110 -0
  11. package/dist/index.cjs +65 -0
  12. package/dist/index.cjs.map +1 -0
  13. package/dist/index.d.ts +7 -0
  14. package/dist/index.mjs +11137 -0
  15. package/dist/index.mjs.map +1 -0
  16. package/dist/io.d.ts +75 -0
  17. package/dist/log.d.ts +21 -0
  18. package/dist/metrics.d.ts +10 -0
  19. package/dist/ocr.d.ts +36 -0
  20. package/dist/optimization.d.ts +48 -0
  21. package/dist/optimization.worker.d.ts +1 -0
  22. package/dist/pdf/annos-text.d.ts +19 -0
  23. package/dist/pdf/annos.d.ts +4 -0
  24. package/dist/pdf/common.d.ts +48 -0
  25. package/dist/pdf/generator.d.ts +197 -0
  26. package/dist/pdf/image.d.ts +34 -0
  27. package/dist/pdf/parser.d.ts +131 -0
  28. package/dist/pdf/pkzip.d.ts +23 -0
  29. package/dist/pdf/png.d.ts +34 -0
  30. package/dist/pdf/util.d.ts +18 -0
  31. package/dist/res/licenses.d.ts +7 -0
  32. package/dist/res/srgbColorspace.d.ts +2 -0
  33. package/dist/util.d.ts +8 -0
  34. package/dist/version.d.ts +2 -0
  35. package/package.json +149 -4
  36. package/src/__tests__/fixtures/deep_toc.json +2953 -0
  37. package/src/__tests__/fixtures/flat_toc.json +2917 -0
  38. package/src/__tests__/fixtures/physdim.json +294 -0
  39. package/src/__tests__/fixtures/region_target.json +58 -0
  40. package/src/__tests__/fixtures/wunder.jpg +0 -0
  41. package/src/__tests__/parser.test.ts +42 -0
  42. package/src/__tests__/pdf.spec.ts +216 -0
  43. package/src/__tests__/region.test.ts +194 -0
  44. package/src/__tests__/setupJest.ts +2 -0
  45. package/src/convert.ts +1098 -0
  46. package/src/download.ts +703 -0
  47. package/src/global.d.ts +10 -0
  48. package/src/iiif.ts +605 -0
  49. package/src/index.ts +7 -0
  50. package/src/io.ts +243 -0
  51. package/src/log.ts +51 -0
  52. package/src/metrics.ts +47 -0
  53. package/src/ocr.ts +176 -0
  54. package/src/optimization.ts +201 -0
  55. package/src/optimization.worker.ts +118 -0
  56. package/src/pdf/annos-text.ts +382 -0
  57. package/src/pdf/annos.ts +240 -0
  58. package/src/pdf/common.ts +158 -0
  59. package/src/pdf/generator.ts +1665 -0
  60. package/src/pdf/image.ts +340 -0
  61. package/src/pdf/parser.ts +811 -0
  62. package/src/pdf/pkzip.ts +228 -0
  63. package/src/pdf/png.ts +397 -0
  64. package/src/pdf/util.ts +111 -0
  65. package/src/res/licenses.ts +266 -0
  66. package/src/res/srgbColorspace.ts +405 -0
  67. package/src/types.d.ts +6 -0
  68. package/src/util.ts +55 -0
  69. package/src/version.ts +1 -0
@@ -0,0 +1,811 @@
1
+ import { Reader } from '../io.js';
2
+ import { PdfObject, PdfValue, PdfDictionary, PdfRef } from './common.js';
3
+ import { textDecoder, textEncoder } from './util.js';
4
+
5
+ // Polyfill Uint8Array.findLastIndex for older browsers
6
+ if (!Uint8Array.prototype.findLastIndex) {
7
+ Uint8Array.prototype.findLastIndex = function (
8
+ predicate: (value: number, index: number, obj: Uint8Array) => boolean
9
+ ): number {
10
+ let l = this.length;
11
+ while (l--) {
12
+ if (predicate(this[l], l, this)) return l;
13
+ }
14
+ return -1;
15
+ };
16
+ }
17
+
18
+ const ESCAPE_CHARS: Record<string, string> = {
19
+ n: '\n',
20
+ r: '\r',
21
+ t: '\t',
22
+ b: '\b',
23
+ f: '\f',
24
+ '(': '(',
25
+ ')': ')',
26
+ '\\': '\\',
27
+ };
28
+
29
+ // offset/nextFree|generation|inUse?
30
+ // ▼ ▼ ▼
31
+ type CrossRefEntry = [number, number, boolean];
32
+ interface CrossRefSubSection {
33
+ startNum: number;
34
+ numObjs: number;
35
+ entries: Array<CrossRefEntry>;
36
+ }
37
+
38
+ /** Parse a section of the x-ref table, yielding `CrossRefSubSection` objects as
39
+ * we encounter them.
40
+ *
41
+ * @param reader The reader to read from.
42
+ * @param offset The offset of the x-ref section in the file.
43
+ * @param length The length of the x-ref section.
44
+ */
45
+ async function* parseCrossRefSection(
46
+ reader: Reader,
47
+ offset: number,
48
+ length: number
49
+ ): AsyncGenerator<CrossRefSubSection> {
50
+ const buf = new Uint8Array(length);
51
+ offset += await reader.read(buf, 0, offset, buf.length);
52
+ if (!testForString(buf, 0, 'xref')) {
53
+ throw 'Invalid crossreference section, did not start with `xref` line.';
54
+ }
55
+ const trailerIdx = buf.findIndex((_x, idx) =>
56
+ testForString(buf, idx, 'trailer')
57
+ );
58
+ // Split into lines and skip first line (`xref`)
59
+ const parts = textDecoder
60
+ .decode(buf.subarray(0, trailerIdx))
61
+ .split(/[\r ]?\n/)
62
+ .slice(1);
63
+ let currentSection: CrossRefSubSection | undefined;
64
+ for (const part of parts) {
65
+ // Entries have length 18 (we stripped the newline already)
66
+ if (part.length === 18) {
67
+ if (!currentSection) {
68
+ throw 'Invalid crossreference section, entry outside of subsection.';
69
+ }
70
+ const entryParts = part.trim().split(' ');
71
+ currentSection.entries.push([
72
+ Number.parseInt(entryParts[0], 10),
73
+ Number.parseInt(entryParts[1], 10),
74
+ entryParts[2] === 'n',
75
+ ]);
76
+ } else {
77
+ if (currentSection) {
78
+ if (currentSection.numObjs !== currentSection.entries.length) {
79
+ throw `Invalid subsection, expected ${currentSection.numObjs} objects, found ${currentSection.entries.length}!`;
80
+ }
81
+ yield currentSection;
82
+ currentSection = undefined;
83
+ }
84
+ if (part.length === 0 || part.indexOf('trailer') >= 0) {
85
+ break;
86
+ }
87
+ const [startNum, numObjs] = part
88
+ .trimEnd()
89
+ .split(' ')
90
+ .map((p) => Number.parseInt(p, 10));
91
+ currentSection = {
92
+ startNum,
93
+ numObjs,
94
+ entries: [],
95
+ };
96
+ }
97
+ }
98
+ if (currentSection) {
99
+ yield currentSection;
100
+ }
101
+ const trailerBuf = buf.subarray(trailerIdx);
102
+ const trailerStartIdx = trailerBuf.findIndex((_x, idx) =>
103
+ testForString(trailerBuf, idx, '<<')
104
+ );
105
+ const trailerEndIdx = trailerBuf.findIndex((_x, idx) =>
106
+ testForString(trailerBuf, idx, '>>')
107
+ );
108
+
109
+ const trailerDict = new PdfValueParser(
110
+ trailerBuf.subarray(trailerStartIdx, trailerEndIdx + 2)
111
+ ).read() as PdfDictionary;
112
+ if (trailerDict.Prev) {
113
+ const previousXrefOffset = trailerDict.Prev as number;
114
+ yield* parseCrossRefSection(
115
+ reader,
116
+ previousXrefOffset,
117
+ offset - previousXrefOffset
118
+ );
119
+ }
120
+ }
121
+
122
+ /** Look for a string from a given location in a buffer. */
123
+ function testForString(
124
+ buf: Uint8Array,
125
+ offset: number,
126
+ value: string,
127
+ backwards = false
128
+ ): boolean {
129
+ if (backwards) {
130
+ for (let idx = value.length - 1; idx >= 0; idx--) {
131
+ if (buf[offset + idx] !== value.charCodeAt(idx)) {
132
+ return false;
133
+ }
134
+ }
135
+ } else {
136
+ for (let idx = 0; idx < value.length; idx++) {
137
+ if (buf[offset + idx] !== value.charCodeAt(idx)) {
138
+ return false;
139
+ }
140
+ }
141
+ }
142
+ return true;
143
+ }
144
+
145
+ /** Check if a string is the representation of an integer digit */
146
+ function isDigit(c: string): boolean {
147
+ return !isNaN(parseInt(c, 10));
148
+ }
149
+
150
+ /** Check if a character is a hexadecimal digit ([0-9a-fA-F]) */
151
+ function isHex(c: number): boolean {
152
+ return (
153
+ (c >= 0x30 && c <= 0x39) ||
154
+ (c >= 0x41 && c <= 0x46) ||
155
+ (c >= 0x61 && c <= 0x66)
156
+ );
157
+ }
158
+
159
+ /** Parse a PDF "value", which can be one of:
160
+ * - number (integer or float)
161
+ * - string
162
+ * - name (represented as a JS string starting with `/`)
163
+ * - boolean
164
+ * - null
165
+ * - date
166
+ * - XRef
167
+ * - Array
168
+ * - Dictionary
169
+ *
170
+ * API walkthrough:
171
+ * - `read()` is the main entry point, it will read the next value from the
172
+ * buffer and advance the cursor
173
+ * - `match*` methods check if the buffer at the current offset matches a
174
+ * certain type of value, either returning a boolean or the section of the
175
+ * buffer containing the value as a string.
176
+ * - `read*` methods read a value of a specific type from the buffer and
177
+ * advance the cursor
178
+ */
179
+ export class PdfValueParser {
180
+ start = 0;
181
+ current = 0;
182
+ private readonly buf: Uint8Array;
183
+
184
+ /** Construct a parser for a buffer containing one or more PDF values. */
185
+ constructor(buf: Uint8Array) {
186
+ this.buf = buf;
187
+ }
188
+
189
+ /** Get the buffer content at the current offset as a character. */
190
+ private getChar(): string {
191
+ return String.fromCharCode(this.buf[this.current]);
192
+ }
193
+
194
+ /** Compares the buffer contents at the current offset against a string value. */
195
+ private matchValue(value: string): boolean {
196
+ const valueRead = textDecoder.decode(
197
+ this.buf.subarray(
198
+ this.current,
199
+ this.current + textEncoder.encode(value).length
200
+ )
201
+ );
202
+ return valueRead === value;
203
+ }
204
+
205
+ /** Checks if the buffer at the current offset contains a number.
206
+ *
207
+ * See ISO32000-2:2020 section 7.3.3.
208
+ */
209
+ private matchInteger(resetAfter = true): string | undefined {
210
+ this.start = this.current;
211
+ let chr: string;
212
+ let isInt = true;
213
+ const chars: string[] = [];
214
+ while (
215
+ !this.matchWhiteSpace((chr = this.getChar())) &&
216
+ !this.matchDelimiter(chr)
217
+ ) {
218
+ if (chr === '+' || chr === '-') {
219
+ if (this.current - this.start > 0) {
220
+ isInt = false;
221
+ break;
222
+ }
223
+ } else if (!isDigit(chr)) {
224
+ isInt = false;
225
+ break;
226
+ }
227
+ this.current++;
228
+ chars.push(chr);
229
+ }
230
+ if (resetAfter) {
231
+ this.current = this.start;
232
+ }
233
+ return isInt ? chars.join('') : undefined;
234
+ }
235
+
236
+ /** Read a PDF value from the current offset, advancing the cursor. */
237
+ read(): PdfValue {
238
+ let c = this.getChar();
239
+ if (this.matchWhiteSpace(c)) {
240
+ this.skipWhiteSpace();
241
+ c = this.getChar();
242
+ }
243
+ switch (this.getChar()) {
244
+ case '[':
245
+ return this.readArray();
246
+ case '<':
247
+ return this.matchValue('<<') ? this.readDict() : this.readHexString();
248
+ case '(':
249
+ return this.readLiteralString();
250
+ case '/':
251
+ return this.readName();
252
+ case 't':
253
+ if (this.matchValue('true')) {
254
+ this.current += 'true'.length;
255
+ return true;
256
+ }
257
+ throw new Error('Unexpected character while parsing');
258
+ case 'f':
259
+ if (this.matchValue('false')) {
260
+ this.current += 'false'.length;
261
+ return false;
262
+ }
263
+ throw new Error('Unexpected character while parsing');
264
+ case 'n':
265
+ if (this.matchValue('null')) {
266
+ this.current += 'null'.length;
267
+ return null;
268
+ }
269
+ throw new Error('Unexpected character while parsing');
270
+ case '.':
271
+ return this.readRealNumber();
272
+ default:
273
+ if (this.matchIndirectObject()) {
274
+ return this.readIndirectObject();
275
+ }
276
+ if (this.matchRealNumber()) {
277
+ return this.readRealNumber();
278
+ }
279
+ if (this.matchInteger()) {
280
+ return this.readInteger();
281
+ }
282
+ throw new Error(
283
+ `Encountered unexpected character during parsing: '${c}'`
284
+ );
285
+ }
286
+ }
287
+
288
+ /** Check if the input string contains PDF whitespace.
289
+ *
290
+ * See ISO32000-2:2020 section 7.2.3, Table 1.
291
+ */
292
+ matchWhiteSpace(c: string): boolean {
293
+ return (
294
+ c === ' ' ||
295
+ c === '\x00' ||
296
+ c === '\n' ||
297
+ c === '\r' ||
298
+ c === '\r\n' ||
299
+ c == '\x0C'
300
+ );
301
+ }
302
+
303
+ /** Read an integer from the current offset. */
304
+ readInteger(): number {
305
+ const intStr = this.matchInteger(false);
306
+ if (intStr === undefined) {
307
+ throw new Error('Failed to read integer.');
308
+ }
309
+ return Number.parseInt(intStr, 10);
310
+ }
311
+
312
+ /** Read an indirect object from the current offset. */
313
+ readIndirectObject(): PdfRef {
314
+ const match = this.matchIndirectObject(false);
315
+ if (match === undefined) {
316
+ throw new Error('Failed to read indirect object');
317
+ }
318
+ return new PdfRef(Number.parseInt(match.split(' ')[0]));
319
+ }
320
+
321
+ /** Check if the buffer contains an indirect object at the current offset.
322
+ *
323
+ * See ISO32000-2:2020 section 7.3.10.
324
+ */
325
+ matchIndirectObject(resetAfter = true): string | undefined {
326
+ this.start = this.current;
327
+ let c = this.getChar();
328
+ const chars: string[] = [];
329
+ const matchNumber = (): boolean => {
330
+ if (!isDigit(c)) {
331
+ return false;
332
+ }
333
+ chars.push(c);
334
+ this.current++;
335
+ while (isDigit((c = this.getChar()))) {
336
+ chars.push(c);
337
+ this.current++;
338
+ }
339
+ return true;
340
+ };
341
+ const matchWhitespace = (): boolean => this.skipWhiteSpace();
342
+ // Using a closure makes resetting afterwards less verbose
343
+ const match = (): boolean => {
344
+ // Object number
345
+ if (!matchNumber()) {
346
+ return false;
347
+ }
348
+ if (!matchWhitespace()) {
349
+ return false;
350
+ }
351
+ chars.push(' ');
352
+ c = this.getChar();
353
+ // Generation number
354
+ if (!matchNumber()) {
355
+ return false;
356
+ }
357
+ if (!matchWhitespace()) {
358
+ return false;
359
+ }
360
+ chars.push(' ');
361
+ if (this.getChar() !== 'R') {
362
+ return false;
363
+ }
364
+ chars.push('R');
365
+ this.current++;
366
+ return true;
367
+ };
368
+ const doesMatch = match();
369
+ if (resetAfter) {
370
+ this.current = this.start;
371
+ }
372
+ if (doesMatch) {
373
+ return chars.join('');
374
+ }
375
+ }
376
+
377
+ /** Check if the buffer contains a real number at the current offset.
378
+ *
379
+ * See ISO32000-2:2020 section 7.3.3.
380
+ */
381
+ matchRealNumber(resetAfter = true): string | undefined {
382
+ this.start = this.current;
383
+ let isRealNumber = true;
384
+ let digitSeen = false;
385
+ let separatorSeen = false;
386
+ const chars: string[] = [];
387
+ let c: string;
388
+ // eslint-disable-next-line no-constant-condition
389
+ while (true) {
390
+ c = this.getChar();
391
+ if (c === '.') {
392
+ if (separatorSeen) {
393
+ isRealNumber = false;
394
+ break;
395
+ }
396
+ separatorSeen = true;
397
+ } else if (isDigit(c)) {
398
+ digitSeen = true;
399
+ } else if (c === '-' || c === '+') {
400
+ if (this.current - this.start > 0) {
401
+ break;
402
+ }
403
+ } else {
404
+ break;
405
+ }
406
+ chars.push(c);
407
+ this.current++;
408
+ }
409
+ if (resetAfter) {
410
+ this.current = this.start;
411
+ }
412
+ if (!isRealNumber) {
413
+ return undefined;
414
+ }
415
+ if (digitSeen && separatorSeen) {
416
+ return chars.join('');
417
+ }
418
+ return undefined;
419
+ }
420
+
421
+ /** Read a real number from the current offset. */
422
+ readRealNumber(): number {
423
+ const str = this.matchRealNumber(false);
424
+ if (!str) {
425
+ throw new Error('Could not read real number.');
426
+ }
427
+ return Number.parseFloat(str);
428
+ }
429
+
430
+ /** Skip a contiguous sequence of whitespae, advancing the cursor. */
431
+ skipWhiteSpace(): boolean {
432
+ let skipped = false;
433
+ while (!this.atEnd() && this.matchWhiteSpace(this.getChar())) {
434
+ this.current++;
435
+ skipped = true;
436
+ }
437
+ return skipped;
438
+ }
439
+
440
+ /** Check if we're at the end of the buffer. */
441
+ atEnd(): boolean {
442
+ return this.current >= this.buf.length;
443
+ }
444
+
445
+ /** Read a name from the current offset.
446
+ *
447
+ * See ISO32000-2:2020 section 7.3.5.
448
+ */
449
+ readName(): PdfValue {
450
+ const chars: string[] = ['/'];
451
+ this.current++;
452
+ let c: string;
453
+ while (
454
+ !this.matchWhiteSpace((c = this.getChar())) &&
455
+ !this.matchDelimiter(c)
456
+ ) {
457
+ if (c === '#') {
458
+ const a = this.buf[this.current++];
459
+ const b = this.buf[this.current++];
460
+ if (!isHex(a) || !isHex(b)) {
461
+ throw new Error('Illegal character escape in name.');
462
+ }
463
+ chars.push(
464
+ String.fromCharCode(
465
+ Number.parseInt(String.fromCharCode(a) + String.fromCharCode(b), 16)
466
+ )
467
+ );
468
+ } else {
469
+ chars.push(c);
470
+ this.current++;
471
+ }
472
+ }
473
+ return chars.join('');
474
+ }
475
+
476
+ /** Check if the current offset contains a delimiter.
477
+ *
478
+ * See ISO32000-2:2020 section 7.2.3, Table 2
479
+ */
480
+ matchDelimiter(c: string): boolean {
481
+ return '[]{}()<>/%'.indexOf(c) >= 0;
482
+ }
483
+
484
+ /** Read a hex string from the current offset.
485
+ *
486
+ * See ISO32000-2:2020 section 7.3.4.3
487
+ */
488
+ readHexString(): PdfValue {
489
+ this.current++;
490
+ const vals: Array<number> = [];
491
+ while (this.getChar() !== '>') {
492
+ const a = this.buf[this.current++];
493
+ const b = this.buf[this.current++];
494
+ if (!isHex(a) || !isHex(b)) {
495
+ throw new Error(`Invalid value in hex string: '${a}${b}`);
496
+ }
497
+ vals.push(
498
+ Number.parseInt(String.fromCharCode(a) + String.fromCharCode(b), 16)
499
+ );
500
+ }
501
+ this.current++;
502
+ return new Uint8Array(vals);
503
+ }
504
+
505
+ /** Read a literal string from the current offset.
506
+ *
507
+ * See ISO32000-2:2020 section 7.3.4.2
508
+ */
509
+ readLiteralString(): PdfValue {
510
+ this.current++;
511
+ const chars: string[] = [];
512
+ let openParens = 0;
513
+ let c: string;
514
+ // eslint-disable-next-line no-constant-condition
515
+ while (true) {
516
+ c = this.getChar();
517
+ if (c === '\\') {
518
+ this.current++;
519
+ c = this.getChar();
520
+ if (isDigit(c)) {
521
+ let cs = [c];
522
+ this.current++;
523
+ while (isDigit(this.getChar())) {
524
+ cs.push(this.getChar());
525
+ this.current++;
526
+ }
527
+ if (cs.length > 3) {
528
+ this.current -= cs.length - 3;
529
+ cs = cs.slice(0, 3);
530
+ }
531
+ this.current--;
532
+ c = String.fromCharCode(Number.parseInt(cs.join(''), 8));
533
+ } else {
534
+ c = ESCAPE_CHARS[c];
535
+ if (c === undefined) {
536
+ throw new Error(
537
+ `Illegal escape sequence in string literal: '\\${c}`
538
+ );
539
+ }
540
+ }
541
+ } else if (c === '(') {
542
+ openParens++;
543
+ } else if (c === ')') {
544
+ openParens--;
545
+ if (openParens < 0) {
546
+ this.current++;
547
+ return chars.join('');
548
+ }
549
+ }
550
+ chars.push(c);
551
+ this.current++;
552
+ }
553
+ }
554
+
555
+ /** Read a dictionary from the current offset.
556
+ *
557
+ * See ISO32000-2:2020 section 7.3.7
558
+ */
559
+ readDict(): PdfValue {
560
+ this.current += 2;
561
+ const obj: Record<string, PdfValue> = {};
562
+ this.skipWhiteSpace();
563
+ while (this.getChar() !== '>') {
564
+ const name = this.read();
565
+ if (typeof name !== 'string' || !name.startsWith('/')) {
566
+ throw new Error(`Dictionary keys must be name objects, got '${name}`);
567
+ }
568
+ this.skipWhiteSpace();
569
+ const val = this.read();
570
+ if (val !== null) {
571
+ obj[name.substring(1)] = val;
572
+ }
573
+ this.skipWhiteSpace();
574
+ }
575
+ this.current += 2;
576
+ return obj;
577
+ }
578
+
579
+ /** Read an array from the current offset.
580
+ *
581
+ * See ISO32000-2:2020 section 7.3.6
582
+ */
583
+ readArray(): Array<PdfValue> {
584
+ this.current++;
585
+ const arr: Array<PdfValue> = [];
586
+ while (this.getChar() !== ']') {
587
+ arr.push(this.read());
588
+ this.skipWhiteSpace();
589
+ }
590
+ this.current++;
591
+ return arr;
592
+ }
593
+ }
594
+
595
+ /** Minimalist low-level PDF parser operating on a Reader object.
596
+ *
597
+ * Currently only supports discovering page objects and annotation objects, as well
598
+ * as obtaining arbitrary objects given the object number and generation.
599
+ */
600
+ export class PdfParser {
601
+ private reader: Reader;
602
+ private objectOffsets: Array<number>;
603
+ private sortedOffsets: Array<number>;
604
+ pdfSize: any;
605
+ objGenerations: number[];
606
+ infoNum: number;
607
+ catalogNum: number;
608
+
609
+ /** Construct a new parser from a Reader.
610
+ *
611
+ * Used instead of the constructor to allow for async initialization.
612
+ */
613
+ static async parse(reader: Reader): Promise<PdfParser> {
614
+ const trailerBuf = new Uint8Array(1024);
615
+ const pdfSize = await reader.size();
616
+ const bufStart = pdfSize - trailerBuf.length;
617
+ await reader.read(trailerBuf, 0, bufStart, trailerBuf.length);
618
+ const eofIdx =
619
+ trailerBuf.length - (trailerBuf[trailerBuf.length - 1] === 0x46 ? 5 : 6);
620
+ if (!testForString(trailerBuf, eofIdx, '%%EOF')) {
621
+ throw 'Invalid PDF, missing EOF comment at end of file';
622
+ }
623
+ const startXrefPos = trailerBuf.findLastIndex((_x, idx) =>
624
+ testForString(trailerBuf, idx, 'startxref')
625
+ );
626
+ if (startXrefPos < 0) {
627
+ throw 'Invalid PDF, missing startxref marker in file trailer.';
628
+ }
629
+ const objGenerations: Array<number> = [];
630
+ const objsDeleted: Array<boolean> = [];
631
+ const objOffsets: Array<number> = [];
632
+ const xrefStartOffset = Number.parseInt(
633
+ textDecoder.decode(trailerBuf.subarray(startXrefPos + 9, eofIdx)).trim(),
634
+ 10
635
+ );
636
+ const dictEnd =
637
+ trailerBuf.findLastIndex((_x, idx) =>
638
+ testForString(trailerBuf, idx, '>>')
639
+ ) + 2;
640
+ const dictStart = trailerBuf.findLastIndex((_x, idx) =>
641
+ testForString(trailerBuf, idx, '<<')
642
+ );
643
+ const trailerDict = new PdfValueParser(
644
+ trailerBuf.subarray(dictStart, dictEnd)
645
+ ).read() as PdfDictionary;
646
+ for await (const { startNum, entries } of parseCrossRefSection(
647
+ reader,
648
+ xrefStartOffset,
649
+ bufStart + dictEnd - xrefStartOffset
650
+ )) {
651
+ for (const [idx, [offset, gen, inUse]] of entries.entries()) {
652
+ const objNum = idx + startNum;
653
+ if ((objGenerations[objNum] ?? -1) > gen) {
654
+ // Outdated entry, don't consider
655
+ continue;
656
+ }
657
+ objGenerations[objNum] = gen;
658
+ if (inUse) {
659
+ objOffsets[objNum] = offset;
660
+ objsDeleted[objNum] = false;
661
+ } else {
662
+ objOffsets[objNum] = -1;
663
+ objsDeleted[objNum] = true;
664
+ }
665
+ }
666
+ }
667
+ if (objOffsets.length !== trailerDict.Size) {
668
+ throw `Trailer dictionary has different number of objects than crossreference tables, ${objOffsets.length} vs. ${trailerDict.Size}`;
669
+ }
670
+ return new PdfParser(reader, objOffsets, objGenerations, trailerDict);
671
+ }
672
+
673
+ /** Private constructor, use factory method above. */
674
+ private constructor(
675
+ reader: Reader,
676
+ objOffsets: Array<number>,
677
+ objGenerations: Array<number>,
678
+ trailerDict: PdfDictionary
679
+ ) {
680
+ this.reader = reader;
681
+ this.objectOffsets = objOffsets;
682
+ this.sortedOffsets = [...objOffsets].sort((a, b) => a - b);
683
+ this.objGenerations = objGenerations;
684
+ this.catalogNum = (trailerDict.Root as PdfRef).refObj;
685
+ this.infoNum = (trailerDict.Info as PdfRef).refObj;
686
+ }
687
+
688
+ /** Retrieve the catalog dictionary. */
689
+ async catalog(): Promise<PdfDictionary> {
690
+ const obj = await this.getObject(this.catalogNum);
691
+ if (!obj) {
692
+ throw `Document has no catalog object (num as per trailer: ${this.catalogNum}!`;
693
+ }
694
+ return obj.data as PdfDictionary;
695
+ }
696
+
697
+ /** Retrieve the info dictionary. */
698
+ async info(): Promise<PdfDictionary> {
699
+ const obj = await this.getObject(this.infoNum);
700
+ if (!obj) {
701
+ throw `Document has no info object (num as per trailer: ${this.infoNum}!`;
702
+ }
703
+ return obj.data as PdfDictionary;
704
+ }
705
+
706
+ /** Yield all pages referenced in the given page dictionary. */
707
+ async *_pagesFromPagesObj(
708
+ pagesObj: PdfDictionary
709
+ ): AsyncGenerator<PdfObject> {
710
+ for (const pageRef of pagesObj.Kids as Array<PdfRef>) {
711
+ const page = await this.getObject(pageRef.refObj, true);
712
+ if (!page) {
713
+ throw `Could not find Page object with number ${pageRef.refObj}`;
714
+ }
715
+ const pageDict = page.data as PdfDictionary;
716
+ if (pageDict.Type === '/Pages') {
717
+ yield* this._pagesFromPagesObj(pageDict);
718
+ } else {
719
+ yield page;
720
+ }
721
+ }
722
+ }
723
+
724
+ /** Yield all pages in the PDF. */
725
+ async *pages(): AsyncGenerator<PdfObject> {
726
+ const catalog = await this.catalog();
727
+ const pagesRef = catalog.Pages as PdfRef;
728
+ const pagesRoot = await this.getObject(pagesRef.refObj);
729
+ if (!pagesRoot) {
730
+ throw `Could not find Pages object with number ${pagesRef.refObj}`;
731
+ }
732
+ const pagesDict = pagesRoot.data as PdfDictionary;
733
+ yield* this._pagesFromPagesObj(pagesDict);
734
+ }
735
+
736
+ /** Yield all annotations for the given page dictionary. */
737
+ async *annotations(pageDict: PdfDictionary): AsyncGenerator<PdfDictionary> {
738
+ const annots = pageDict.Annots;
739
+ if (!annots) {
740
+ return;
741
+ }
742
+ for (const annoRef of annots as Array<PdfRef>) {
743
+ const anno = await this.getObject(annoRef.refObj);
744
+ if (!anno) {
745
+ throw `Could not find Annotation object with number ${annoRef.refObj}`;
746
+ }
747
+ yield anno.data as PdfDictionary;
748
+ }
749
+ }
750
+
751
+ /** Resolve a PDF reference to the corresponding object. */
752
+ resolveRef(ref: PdfRef): Promise<PdfObject | undefined> {
753
+ return this.getObject(ref.refObj, true);
754
+ }
755
+
756
+ /** Get an object from the PDF from its number. */
757
+ async getObject(
758
+ num: number,
759
+ withStream = false
760
+ ): Promise<PdfObject | undefined> {
761
+ const offset = this.objectOffsets[num];
762
+ if (!offset) {
763
+ return;
764
+ }
765
+ if (!this.pdfSize) {
766
+ this.pdfSize = await this.reader.size();
767
+ }
768
+ const nextOffset =
769
+ this.sortedOffsets[this.sortedOffsets.indexOf(offset) + 1] ??
770
+ this.pdfSize;
771
+ const buf = new Uint8Array(nextOffset - offset);
772
+ await this.reader.read(buf, 0, offset, buf.length);
773
+ const objEndIdx = buf.findIndex((_x, idx) =>
774
+ testForString(buf, idx, 'endobj')
775
+ );
776
+ let streamIdx = buf.findIndex((_x, idx) =>
777
+ testForString(buf, idx, 'stream')
778
+ );
779
+ if (streamIdx >= 0) {
780
+ streamIdx += 'stream'.length;
781
+ if (buf[streamIdx] === '\r'.charCodeAt(0)) {
782
+ streamIdx += 2;
783
+ } else {
784
+ streamIdx += 1;
785
+ }
786
+ }
787
+ const objSig = `${num} ${this.objGenerations[num]} obj`;
788
+ const objParser = new PdfValueParser(
789
+ buf.subarray(objSig.length, streamIdx < 0 ? objEndIdx : streamIdx)
790
+ );
791
+ const data = objParser.read();
792
+ if (typeof data !== 'object' || data === null) {
793
+ throw new Error('Illegal PDF object, does not start with a dictionary.');
794
+ }
795
+ let stream: Uint8Array | undefined;
796
+ if (withStream && streamIdx > 0) {
797
+ const streamLength = (data as PdfDictionary).Length as number | undefined;
798
+ if (streamLength === undefined) {
799
+ throw new Error(
800
+ 'Illegal stream object, missing Length entry in object dictionary.'
801
+ );
802
+ }
803
+ stream = buf.subarray(streamIdx, streamIdx + streamLength);
804
+ }
805
+ return {
806
+ num,
807
+ data,
808
+ stream,
809
+ };
810
+ }
811
+ }