@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
package/dist/io.d.ts ADDED
@@ -0,0 +1,75 @@
1
+ import { Writable as NodeWritable } from 'stream';
2
+ import { default as nodeFs } from 'fs';
3
+
4
+ /** Base interface to be implemented by all readers. */
5
+ export interface Reader {
6
+ read(dst: Uint8Array, offset: number, position: number, length: number): Promise<number>;
7
+ size(): Promise<number>;
8
+ }
9
+ /** Base interface to be implemented by all writers. */
10
+ export interface Writer {
11
+ /** Write a chunk to the writer */
12
+ write(buffer: Uint8Array | string): Promise<void>;
13
+ /** Close the writer */
14
+ close(): Promise<void>;
15
+ /** Wait for the next drainage/flush event */
16
+ waitForDrain(): Promise<void>;
17
+ }
18
+ /** Reader implementation using the Web `File` API. */
19
+ export declare class WebReader implements Reader {
20
+ private file;
21
+ constructor(file: File);
22
+ read(dst: Uint8Array, offset: number, position: number, length: number): Promise<number>;
23
+ size(): Promise<number>;
24
+ }
25
+ /** Wraps a writer and counts the bytes written to it. */
26
+ export declare class CountingWriter implements Writer {
27
+ private _writer;
28
+ bytesWritten: number;
29
+ constructor(writer: Writer);
30
+ write(buffer: string | Uint8Array): Promise<void>;
31
+ close(): Promise<void>;
32
+ waitForDrain(): Promise<void>;
33
+ }
34
+ /** A Writer implemented using the `File System Access API` available in
35
+ * recent Chrome, Edge and Opera browsers. */
36
+ export declare class WebWriter implements Writer {
37
+ private _writer;
38
+ constructor(stream: WritableStream);
39
+ write(buffer: string | Uint8Array): Promise<void>;
40
+ waitForDrain(): Promise<void>;
41
+ close(): Promise<void>;
42
+ }
43
+ /** Writer implementation using the `Blob` API available in all browsers. */
44
+ export declare class BlobWriter implements Writer {
45
+ private _parts;
46
+ private _blob?;
47
+ constructor();
48
+ write(buffer: string | Uint8Array): Promise<void>;
49
+ waitForDrain(): Promise<void>;
50
+ close(): Promise<void>;
51
+ get blob(): Blob;
52
+ }
53
+ /** Reader implentation using the node.js filesystem API. */
54
+ export declare class NodeReader implements Reader {
55
+ private fileHandle;
56
+ constructor(handle: nodeFs.promises.FileHandle);
57
+ read(dst: Uint8Array, offset: number, position: number, length: number): Promise<number>;
58
+ size(): Promise<number>;
59
+ }
60
+ /** Writer implementation using the node.js filesystem API. */
61
+ export declare class NodeWriter implements Writer {
62
+ _writable: NodeWritable;
63
+ _drainWaiters: Array<() => void>;
64
+ constructor(writable: NodeWritable);
65
+ write(buffer: string | Uint8Array): Promise<void>;
66
+ waitForDrain(): Promise<void>;
67
+ close(): Promise<void>;
68
+ }
69
+ /** Very basic Reader implementation using an Array. */
70
+ export declare class ArrayReader implements Reader {
71
+ _buf: Uint8Array;
72
+ constructor(buf: Uint8Array);
73
+ read(dst: Uint8Array, offset: number, position: number, length: number): Promise<number>;
74
+ size(): Promise<number>;
75
+ }
package/dist/log.d.ts ADDED
@@ -0,0 +1,21 @@
1
+ type LogLevel = 'debug' | 'info' | 'warn' | 'error';
2
+ export interface Logger {
3
+ setLevel(level: LogLevel): void;
4
+ debug(message: string, ...args: any[]): void;
5
+ info(message: string, ...args: any[]): void;
6
+ warn(message: string, ...args: any[]): void;
7
+ error(message: string, ...args: any[]): void;
8
+ }
9
+ /** Simple logger that simply outputs to the console */
10
+ export declare class ConsoleLogger implements Logger {
11
+ private level;
12
+ constructor(level?: LogLevel);
13
+ setLevel(level: LogLevel): void;
14
+ debug(message: string, ...args: any[]): void;
15
+ info(message: string, ...args: any[]): void;
16
+ warn(message: string, ...args: any[]): void;
17
+ error(message: string, ...args: any[]): void;
18
+ }
19
+ declare let logger: Logger;
20
+ export declare function setLogger(newLogger: Logger): void;
21
+ export { logger as default };
@@ -0,0 +1,10 @@
1
+ import { Histogram } from 'prom-client';
2
+
3
+ type Metrics = {
4
+ pageGenerationDuration: Histogram<string>;
5
+ imageFetchDuration: Histogram<string>;
6
+ imageInfoDuration: Histogram<string>;
7
+ ocrFetchDuration: Histogram<string>;
8
+ } | undefined;
9
+ declare let metrics: Metrics;
10
+ export default metrics;
package/dist/ocr.d.ts ADDED
@@ -0,0 +1,36 @@
1
+ import { Annotation } from '@iiif/presentation-3';
2
+ import { AnnotationNormalized, CanvasNormalized } from '@iiif/presentation-3-normalized';
3
+ import { OcrPage, Dimensions } from 'ocr-parser';
4
+ import { ExternalWebResourceWithProfile } from './iiif.js';
5
+
6
+ export type OcrPageWithMarkup = OcrPage & {
7
+ id: string;
8
+ markup: string;
9
+ mimeType: string;
10
+ };
11
+ /**
12
+ * Parse an OCR document (currently hOCR or ALTO)
13
+ *
14
+ * @param {string} ocrText ALTO or hOCR markup
15
+ * @param {object} referenceSize Reference size to scale coordinates to
16
+ * @returns {OcrPage} the parsed OCR page
17
+ */
18
+ export declare function parseOcr(id: string, ocrText: string, referenceSize: Dimensions): Promise<OcrPageWithMarkup | null>;
19
+ /** Parse OCR data from IIIF annotations.
20
+ *
21
+ * Annotations should be pre-filtered so that they all refer to a single canvas/page.
22
+ * Annotations should only contain a single text granularity, that is either line or word.
23
+ *
24
+ * @param {object} annos IIIF annotations with a plaintext body and line or word granularity
25
+ * @param {Dimensions} imgSize Reference width and height of the rendered target image
26
+ * @returns {OcrPage} parsed OCR boxes
27
+ */
28
+ export declare function parseIiifAnnotations(annos: Array<Annotation>, imgSize: Dimensions): OcrPage;
29
+ /** Fetch external annotation resource JSON */
30
+ export declare function fetchAnnotationResource(url: string): Promise<any>;
31
+ /** Retrieve a supported OCR references from a Canvas' `seeAlso` or `rendering`, if present.
32
+ *
33
+ * 'Supported' currently means external ALTO or hOCR markup.
34
+ */
35
+ export declare function getOcrReferences(canvas: CanvasNormalized): ExternalWebResourceWithProfile | undefined;
36
+ export declare function fetchAndParseText(canvas: CanvasNormalized, annotations?: AnnotationNormalized[]): Promise<OcrPageWithMarkup | undefined>;
@@ -0,0 +1,48 @@
1
+ import { EncodeOptions } from '@jsquash/jpeg/meta';
2
+
3
+ export type InitializationRequest = {
4
+ mozjpegWasm: Uint8Array;
5
+ };
6
+ export type TaskDescription<I> = {
7
+ id: string;
8
+ data: I;
9
+ };
10
+ export type WorkerMessage<I, O> = {
11
+ input: {
12
+ id: string;
13
+ data: I;
14
+ };
15
+ result: O;
16
+ };
17
+ export type WorkerTask<I, O> = {
18
+ resolve: (value: O) => void;
19
+ reject: (reason: any) => void;
20
+ task: TaskDescription<I>;
21
+ };
22
+ export type MozJPEGParams = {
23
+ method: 'mozjpeg';
24
+ quality: number;
25
+ } & Partial<EncodeOptions>;
26
+ export type BrowserEncoderParams = {
27
+ method: 'browser';
28
+ quality: number;
29
+ };
30
+ export type OptimizationParams = MozJPEGParams | BrowserEncoderParams;
31
+ export type OptimizationRequest = {
32
+ imageData: Uint8Array;
33
+ imageFormat: 'image/jpeg' | 'image/png';
34
+ } & OptimizationParams;
35
+ export type OptimizedImage = {
36
+ jpegData: Uint8Array;
37
+ sizeFactor: number;
38
+ };
39
+ export declare class OptimizationError extends Error {
40
+ taskId: string;
41
+ cause?: unknown;
42
+ constructor(message: string, taskId: string, cause?: unknown);
43
+ }
44
+ export declare const MOZJPEG_DEFAULT_PARAMS: EncodeOptions;
45
+ export declare function startWorkerPool(size?: number): void;
46
+ export declare function stopWorkerPool(): void;
47
+ export declare function initialize(wasmLoader: () => Promise<Uint8Array>): Promise<void>;
48
+ export declare function optimizeImage(params: OptimizationRequest): Promise<OptimizedImage>;
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,19 @@
1
+ import { Annotation } from '../iiif.js';
2
+
3
+ export type AnnotationFont = 'Helvetica' | 'Times-Roman' | 'Courier';
4
+ export declare function annotationFontResourceName(font: AnnotationFont, bold: boolean, italic: boolean): string;
5
+ export declare function annotationFontFaces(font: AnnotationFont): Array<{
6
+ resourceName: string;
7
+ baseFont: string;
8
+ }>;
9
+ export interface AnnotationTextRun {
10
+ text: string;
11
+ bold: boolean;
12
+ italic: boolean;
13
+ underline: boolean;
14
+ color?: [number, number, number];
15
+ lineBreak?: boolean;
16
+ }
17
+ export declare function htmlToAnnotationText(html: string): Promise<AnnotationTextRun[]>;
18
+ /** Create page-content instructions for an annotation rendered as visible text. */
19
+ export declare function exportPdfText(anno: Annotation, unitScale: number, pageHeight: number, pageWidth: number, font: AnnotationFont): Promise<string[]>;
@@ -0,0 +1,4 @@
1
+ import { PdfDictionary } from './common.js';
2
+ import { Annotation } from '../iiif.js';
3
+
4
+ export declare function exportPdfAnnotation(anno: Annotation, unitScale: number, pageHeight: number): Promise<Array<PdfDictionary>>;
@@ -0,0 +1,48 @@
1
+ export interface Metadata {
2
+ Producer?: string;
3
+ Creator?: string;
4
+ CreationDate?: Date;
5
+ Title?: string;
6
+ Author?: string;
7
+ Keywords?: string;
8
+ ModDate?: Date;
9
+ }
10
+ export interface PdfObject {
11
+ num: number;
12
+ data?: PdfValue;
13
+ stream?: Uint8Array | string;
14
+ }
15
+ export declare class PdfRef {
16
+ refObj: number;
17
+ constructor(num: number);
18
+ }
19
+ export type PdfPrimitive = string | number | boolean | Uint8Array | null | Date | PdfRef;
20
+ export interface PdfDictionary {
21
+ [member: string]: PdfPrimitive | PdfArray | PdfDictionary;
22
+ }
23
+ export type PdfArray = Array<PdfPrimitive | PdfArray | PdfDictionary>;
24
+ export type PdfValue = PdfPrimitive | PdfDictionary | PdfArray | null;
25
+ export interface PdfAnnotation {
26
+ Type: 'Annot';
27
+ Subtype: string;
28
+ Rect: [number, number, number, number];
29
+ Contents: string | undefined;
30
+ P?: PdfRef;
31
+ NM?: string;
32
+ M?: Date;
33
+ F?: number;
34
+ AP?: PdfDictionary;
35
+ AS?: string;
36
+ Border?: [number, number, number] | [number, number, number, number];
37
+ C?: [] | [number] | [number, number, number] | [number, number, number, number];
38
+ }
39
+ export interface StructTreeEntry {
40
+ type: 'Sect' | 'P' | 'Span';
41
+ children: Array<StructTreeEntry>;
42
+ pageObjNum: number;
43
+ mcs: Array<number>;
44
+ }
45
+ export declare function makeRef(target: number | PdfObject): PdfRef;
46
+ /** Convert a JS UTF8 string to a UTF16 Big Endian string */
47
+ export declare function toUTF16BE(str: string, includeBom?: boolean): Uint8Array;
48
+ export declare function serialize(value: PdfValue, dictIndent?: number): string;
@@ -0,0 +1,197 @@
1
+ import { Manifest } from '@iiif/presentation-3';
2
+ import { Manifest as ManifestV2 } from '@iiif/presentation-2';
3
+ import { OcrLine } from 'ocr-parser';
4
+ import { Metadata, PdfObject, PdfRef, PdfValue, StructTreeEntry } from './common.js';
5
+ import { TocItem } from './util.js';
6
+ import { Writer } from '../io.js';
7
+ import { OcrPageWithMarkup } from '../ocr.js';
8
+ import { CanvasImage, ImageFetchFailure, StartCanvasInfo } from '../download.js';
9
+ import { Annotation, CanvasInfo } from '../iiif.js';
10
+ import { AnnotationFont } from './annos-text.js';
11
+ import { OptimizationParams } from '../optimization.js';
12
+
13
+ export type GeneratorParams = {
14
+ writer: Writer;
15
+ metadata: Metadata;
16
+ canvasInfos: CanvasInfo[];
17
+ langPref: readonly string[];
18
+ pageLabels?: string[];
19
+ outline: TocItem[];
20
+ hasText?: boolean;
21
+ annotationsAsText?: boolean;
22
+ annotationFont?: AnnotationFont;
23
+ readingDirection?: 'right-to-left' | 'left-to-right';
24
+ initialCanvas?: StartCanvasInfo;
25
+ manifestJson?: Manifest | ManifestV2;
26
+ zipPolyglot?: boolean;
27
+ zipBaseDir?: string;
28
+ optimization?: OptimizationParams;
29
+ };
30
+ /** Streaming PDF generator based on a IIIF manifest.
31
+ *
32
+ * This class is responsible for generating a PDF document based on a IIIF manifest.
33
+ * It is designed to be used in a streaming fashion, i.e. it can start writing the PDF
34
+ * before all the resources have been loaded and thus does not require a huge amount
35
+ * of memory. On the flipside, this makes the code a lot more complex, since we need
36
+ * to keep track of the PDF's internal state and write objects in the correct order.
37
+ * Another complication is that we want to write out the catalog and page tree first
38
+ * to allow viewers to quickly display the first page, which requires a bunch of
39
+ * complicated pre-allocation of objects.
40
+ *
41
+ * FIXME: Can't we just write the pages first and then the catalog and page tree at
42
+ * the end of the file? Would make things *A LOT* easier and less complex and
43
+ * error-prone.
44
+ */
45
+ export default class PDFGenerator {
46
+ _offset: number;
47
+ _objects: Array<PdfObject>;
48
+ _nextObjNo: number;
49
+ _objRefs: Record<string, PdfRef>;
50
+ _offsets: number[];
51
+ _writer: Writer | undefined;
52
+ _pagesStarted: boolean;
53
+ _canvasInfos: Array<CanvasInfo>;
54
+ _firstPageObjectNum: number | undefined;
55
+ _pageLabels?: string[];
56
+ _numCoverPages: number;
57
+ _outline: TocItem[];
58
+ _hasText: boolean;
59
+ _strucTree: StructTreeEntry[];
60
+ _pageMCIds: Map<number, Array<number>>;
61
+ _nextStructParentId: number;
62
+ _pageParentIds: Map<number, number>;
63
+ _langPref: readonly string[];
64
+ _initialCanvas?: StartCanvasInfo;
65
+ private _polyglot;
66
+ private _manifestJson?;
67
+ private _zipCatalog?;
68
+ private _zipBaseDir?;
69
+ private _readingDirection;
70
+ private _annotationsAsText;
71
+ private _annotationFont;
72
+ private _deferredReferences;
73
+ /** Just basic setup of state, real setup is done in setup()
74
+ method since we need to call a bunch of async stuff */
75
+ constructor({ writer, metadata, canvasInfos, langPref, pageLabels, outline, readingDirection, hasText, annotationsAsText, annotationFont, initialCanvas, manifestJson, zipPolyglot, zipBaseDir, }: GeneratorParams);
76
+ /** Set up the basic PDF document, creating neccessary objects. */
77
+ setup(): Promise<void>;
78
+ /** Set up neccessary fonts for the hidden text layer. */
79
+ _setupHiddenTextFont(): Promise<void>;
80
+ /** Register embedded OCR files in the PDF's catalog object. */
81
+ _registerEmbeddedFilesInCatalog(): void;
82
+ /** Create a PdfRef whose value is deferred, i.e. will be set at a later stage.
83
+ *
84
+ * Useful for bidirectional references.
85
+ *
86
+ * Prevents serialization of objects containing this reference as long as the
87
+ * value is not set.
88
+ *
89
+ * @param key A unique key to identify the reference
90
+ */
91
+ _makeDeferredReference(key: string): PdfRef;
92
+ /** Add items to the PDF's outline, based on the passed TocItem tree.
93
+ *
94
+ * @param itm The item we want to add to the outline
95
+ * @param parent The parent outline item
96
+ * @param prev The preceding sibling outline item, if present
97
+ * @returns A tuple containing the object reference of the added outline item and the number
98
+ * of children outline items that were created
99
+ */
100
+ _addOutline(itm: TocItem, parent: PdfObject, prev?: PdfObject): [PdfObject, number];
101
+ /** Add a new object to the PDF document.
102
+ *
103
+ * @param val A PDF value, can be any of the supported types.
104
+ * @param refName An optional name to reference the object by.
105
+ * @param stream An optional stream to attach to the object, value must be adictionary in this case
106
+ * @returns The created object
107
+ */
108
+ _addObject(val: PdfValue, refName?: string, stream?: Uint8Array | string): PdfObject;
109
+ /** Clone an object from a foreign PDF into the current PDF, adjusting
110
+ * the encountered indirect object references.
111
+ *
112
+ * @param parser PdfParser instance for the PDF the object is from
113
+ * @param obj The object to transplant into our document
114
+ * @param seenObjects A map of object numbers to known references, used to avoid
115
+ * infinite recursion
116
+ * @returns A reference to the transplanted object
117
+ */
118
+ private _transplantObject;
119
+ /** Insert cover pages from another PDF into our document. */
120
+ insertCoverPages(pdfData: ArrayBuffer): Promise<void>;
121
+ /** Embed a file resource in the PDF.
122
+ *
123
+ * @param filename The filename for the embedded resource
124
+ * @param description A description of the file
125
+ * @param mimeType The MIME type of the file
126
+ * @param data The data to embed
127
+ */
128
+ private _embedResource;
129
+ /** Embed the IIIF Manifest JSON in the PDF.
130
+ *
131
+ * @param manifestJson The IIIF (v2 or v3) Manifest to embed
132
+ */
133
+ private _embedManifest;
134
+ /** Once all setup is complete and we begin rendering pages into the document,
135
+ * we need to finalize the PDF header with the remaining information.
136
+ */
137
+ finalizePdfHeader(): Promise<void>;
138
+ /** Render a new page, based on a IIIF canvas, its associated annotations and OCR text.
139
+ *
140
+ * @param canvasId The ID of the canvas to render
141
+ * @param width The width of the canvas in pixels
142
+ * @param height The height of the canvas in pixels
143
+ * @param images The images to render on the canvas
144
+ * @param annotations The annotations to render on the canvas
145
+ * @param ocrText The OCR text to render on the canvas
146
+ * @param ppi The resolution of the canvas in pixels per inch, used to determine the physical
147
+ * size of the PDF page. Assumes 300ppi by default.
148
+ */
149
+ renderPage(canvasId: string, { width: canvasWidth, height: canvasHeight, }: {
150
+ width: number;
151
+ height: number;
152
+ }, images: (CanvasImage | ImageFetchFailure)[], annotations: Annotation[], ocrText?: OcrPageWithMarkup, ppi?: number): Promise<void>;
153
+ /** Get PDF instructions to render a hidden text layer with the page's OCR.
154
+ *
155
+ * This owes *a lot* to Tesseract's PDF renderer[1] and the IA's `pdf-tools`[2]
156
+ * that ported it to Python. Accordingly, the license of this method is Apache 2.0.
157
+ *
158
+ * [1] https://github.com/tesseract-ocr/tesseract/blob/5.0.0-beta-20210916/src/api/pdfrenderer.cpp
159
+ * [2] https://github.com/internetarchive/archive-pdf-tools/blob/master/internetarchivepdf/pdfrenderer.py
160
+ *
161
+ * Apache License
162
+ * Version 2.0, January 2004
163
+ * http://www.apache.org/licenses/
164
+ */
165
+ _renderOcrText(ocr: OcrPageWithMarkup, unitScale: number): string;
166
+ /** Get PDF instructions to render a single line of OCR text. */
167
+ renderOcrLine(line: OcrLine, lineIdx: number, unitScale: number, pageHeight: number, pageObjNum: number): string[];
168
+ /** How many bytes have we written to the output so far? */
169
+ get bytesWritten(): number;
170
+ /** Number of objects needed to render all canvases */
171
+ get totalCanvasObjects(): number;
172
+ /** How many objects are needed to render the canvas at the given index? */
173
+ getObjectsPerCanvas(canvasIdx: number): number;
174
+ /** Get the object number for the canvas at the given index. */
175
+ getCanvasObjectNumber(canvasIdx: number): number;
176
+ /** Flush remaining data to output. */
177
+ _flush(): Promise<void>;
178
+ /** Get the serialized size in bytes of a PDF object. */
179
+ _getSerializedSize({ num, data, stream }: PdfObject, untilStreamStart?: boolean): number;
180
+ /** Serialize a PDF object to the output. */
181
+ _serializeObject(obj: PdfObject): Promise<void>;
182
+ /** Write data to the output. */
183
+ _write(data: Uint8Array | string): Promise<void>;
184
+ /** Write the PDF objects required for the structure tree */
185
+ _writeStructureTree(): Promise<void>;
186
+ /** Finish writing the PDF and close the writer.
187
+ *
188
+ * Writes XRef table, trailer and EOF marker to the output.
189
+ * Also adds ZIP central directory if polyglot PDF is enabled.
190
+ */
191
+ end(): Promise<void>;
192
+ /** Insert a 'dummy' PDF object that isn't referenced anywhere, but which
193
+ * contains the data neccessary to expose the following object's data as a
194
+ * file in the ZIP archive.
195
+ */
196
+ private _insertZipHeaderDummyObject;
197
+ }
@@ -0,0 +1,34 @@
1
+ import { PdfObject } from './common.js';
2
+ import { default as PNG } from './png.js';
3
+
4
+ declare abstract class PdfImage {
5
+ static open(data: Uint8Array): PdfImage;
6
+ abstract toObjects(startNum: number, isOptional?: boolean, optionalTitle?: string, optionalDefaultState?: boolean): Array<PdfObject>;
7
+ }
8
+ export declare class JPEGImage extends PdfImage {
9
+ static MARKERS: number[];
10
+ static COLOR_SPACE_MAP: {
11
+ 1: string;
12
+ 3: string;
13
+ 4: string;
14
+ };
15
+ data: Uint8Array;
16
+ bits: number;
17
+ width: number;
18
+ height: number;
19
+ colorSpace: string;
20
+ constructor(data: Uint8Array);
21
+ toObjects(startNum: number): Array<PdfObject>;
22
+ }
23
+ export declare class PNGImage extends PdfImage {
24
+ label: string | undefined;
25
+ image: PNG;
26
+ width: number;
27
+ height: number;
28
+ imgData: Uint8Array;
29
+ constructor(data: Uint8Array, label?: string);
30
+ toObjects(startNum: number): Array<PdfObject>;
31
+ splitAlphaChannel(objNum: number): [Uint8Array, PdfObject];
32
+ loadIndexedAlphaChannel(objNum: number): PdfObject;
33
+ }
34
+ export default PdfImage;
@@ -0,0 +1,131 @@
1
+ import { Reader } from '../io.js';
2
+ import { PdfObject, PdfValue, PdfDictionary, PdfRef } from './common.js';
3
+
4
+ /** Parse a PDF "value", which can be one of:
5
+ * - number (integer or float)
6
+ * - string
7
+ * - name (represented as a JS string starting with `/`)
8
+ * - boolean
9
+ * - null
10
+ * - date
11
+ * - XRef
12
+ * - Array
13
+ * - Dictionary
14
+ *
15
+ * API walkthrough:
16
+ * - `read()` is the main entry point, it will read the next value from the
17
+ * buffer and advance the cursor
18
+ * - `match*` methods check if the buffer at the current offset matches a
19
+ * certain type of value, either returning a boolean or the section of the
20
+ * buffer containing the value as a string.
21
+ * - `read*` methods read a value of a specific type from the buffer and
22
+ * advance the cursor
23
+ */
24
+ export declare class PdfValueParser {
25
+ start: number;
26
+ current: number;
27
+ private readonly buf;
28
+ /** Construct a parser for a buffer containing one or more PDF values. */
29
+ constructor(buf: Uint8Array);
30
+ /** Get the buffer content at the current offset as a character. */
31
+ private getChar;
32
+ /** Compares the buffer contents at the current offset against a string value. */
33
+ private matchValue;
34
+ /** Checks if the buffer at the current offset contains a number.
35
+ *
36
+ * See ISO32000-2:2020 section 7.3.3.
37
+ */
38
+ private matchInteger;
39
+ /** Read a PDF value from the current offset, advancing the cursor. */
40
+ read(): PdfValue;
41
+ /** Check if the input string contains PDF whitespace.
42
+ *
43
+ * See ISO32000-2:2020 section 7.2.3, Table 1.
44
+ */
45
+ matchWhiteSpace(c: string): boolean;
46
+ /** Read an integer from the current offset. */
47
+ readInteger(): number;
48
+ /** Read an indirect object from the current offset. */
49
+ readIndirectObject(): PdfRef;
50
+ /** Check if the buffer contains an indirect object at the current offset.
51
+ *
52
+ * See ISO32000-2:2020 section 7.3.10.
53
+ */
54
+ matchIndirectObject(resetAfter?: boolean): string | undefined;
55
+ /** Check if the buffer contains a real number at the current offset.
56
+ *
57
+ * See ISO32000-2:2020 section 7.3.3.
58
+ */
59
+ matchRealNumber(resetAfter?: boolean): string | undefined;
60
+ /** Read a real number from the current offset. */
61
+ readRealNumber(): number;
62
+ /** Skip a contiguous sequence of whitespae, advancing the cursor. */
63
+ skipWhiteSpace(): boolean;
64
+ /** Check if we're at the end of the buffer. */
65
+ atEnd(): boolean;
66
+ /** Read a name from the current offset.
67
+ *
68
+ * See ISO32000-2:2020 section 7.3.5.
69
+ */
70
+ readName(): PdfValue;
71
+ /** Check if the current offset contains a delimiter.
72
+ *
73
+ * See ISO32000-2:2020 section 7.2.3, Table 2
74
+ */
75
+ matchDelimiter(c: string): boolean;
76
+ /** Read a hex string from the current offset.
77
+ *
78
+ * See ISO32000-2:2020 section 7.3.4.3
79
+ */
80
+ readHexString(): PdfValue;
81
+ /** Read a literal string from the current offset.
82
+ *
83
+ * See ISO32000-2:2020 section 7.3.4.2
84
+ */
85
+ readLiteralString(): PdfValue;
86
+ /** Read a dictionary from the current offset.
87
+ *
88
+ * See ISO32000-2:2020 section 7.3.7
89
+ */
90
+ readDict(): PdfValue;
91
+ /** Read an array from the current offset.
92
+ *
93
+ * See ISO32000-2:2020 section 7.3.6
94
+ */
95
+ readArray(): Array<PdfValue>;
96
+ }
97
+ /** Minimalist low-level PDF parser operating on a Reader object.
98
+ *
99
+ * Currently only supports discovering page objects and annotation objects, as well
100
+ * as obtaining arbitrary objects given the object number and generation.
101
+ */
102
+ export declare class PdfParser {
103
+ private reader;
104
+ private objectOffsets;
105
+ private sortedOffsets;
106
+ pdfSize: any;
107
+ objGenerations: number[];
108
+ infoNum: number;
109
+ catalogNum: number;
110
+ /** Construct a new parser from a Reader.
111
+ *
112
+ * Used instead of the constructor to allow for async initialization.
113
+ */
114
+ static parse(reader: Reader): Promise<PdfParser>;
115
+ /** Private constructor, use factory method above. */
116
+ private constructor();
117
+ /** Retrieve the catalog dictionary. */
118
+ catalog(): Promise<PdfDictionary>;
119
+ /** Retrieve the info dictionary. */
120
+ info(): Promise<PdfDictionary>;
121
+ /** Yield all pages referenced in the given page dictionary. */
122
+ _pagesFromPagesObj(pagesObj: PdfDictionary): AsyncGenerator<PdfObject>;
123
+ /** Yield all pages in the PDF. */
124
+ pages(): AsyncGenerator<PdfObject>;
125
+ /** Yield all annotations for the given page dictionary. */
126
+ annotations(pageDict: PdfDictionary): AsyncGenerator<PdfDictionary>;
127
+ /** Resolve a PDF reference to the corresponding object. */
128
+ resolveRef(ref: PdfRef): Promise<PdfObject | undefined>;
129
+ /** Get an object from the PDF from its number. */
130
+ getObject(num: number, withStream?: boolean): Promise<PdfObject | undefined>;
131
+ }
@@ -0,0 +1,23 @@
1
+ export type LocalHeaderParams = {
2
+ creationDate?: Date;
3
+ filename: string;
4
+ data: Uint8Array;
5
+ compressedData?: Uint8Array;
6
+ extraDataLength: number;
7
+ };
8
+ export type CentralDirectoryFileSpec = {
9
+ localHeaderOffset: number;
10
+ deflated: boolean;
11
+ creationDate: Date;
12
+ crc32: number;
13
+ dataLength: number;
14
+ compressedDataLength: number;
15
+ filename: string;
16
+ };
17
+ export type CentralFileDirectorySpec = {
18
+ files: CentralDirectoryFileSpec[];
19
+ trailingLength: number;
20
+ offset: number;
21
+ };
22
+ export declare function buildLocalZipHeader({ creationDate, filename, data, compressedData, extraDataLength, }: LocalHeaderParams): Uint8Array;
23
+ export declare function buildCentralFileDirectory({ files, trailingLength, offset }: CentralFileDirectorySpec): Uint8Array;