UNPKG

21.1 kBTypeScriptView Raw
1// Type definitions for PDF.js v2.7
2// Project: https://github.com/mozilla/pdf.js
3// Definitions by: Josh Baldwin <https://github.com/jbaldwin>
4// Dmitrii Sorin <https://github.com/1999>
5// Kamil Socha <https://github.com/ksocha>
6// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
7// TypeScript Version: 3.0
8
9// <reference lib="dom"/>
10
11declare const version: string;
12
13declare const GlobalWorkerOptions: GlobalWorkerOptions;
14
15interface GlobalWorkerOptions {
16 workerSrc: string;
17 workerPort: PDFWorker | null;
18}
19
20interface PDFTreeNode {
21 title: string;
22 bold: boolean;
23 italic: boolean;
24 color: number[]; // [r,g,b]
25 dest: any;
26 items: PDFTreeNode[];
27}
28
29interface PDFInfo {
30 PDFFormatVersion: string;
31 IsAcroFormPresent: boolean;
32 IsXFAPresent: boolean;
33 [key: string]: any; // return type is string, typescript chokes
34}
35
36interface PDFMetadata {
37 parse(): void;
38 get(name: string): string;
39 has(name: string): boolean;
40}
41
42interface PDFDataRangeTransportListener {
43 (loaded: number, total: number): void;
44}
45
46declare enum VerbosityLevel {
47 ERRORS = 0,
48 WARNINGS = 1,
49 INFOS = 5,
50}
51
52declare class PDFDataRangeTransport {
53 constructor(length: number, initialData: Uint8Array | BufferSource, progressiveDone?: boolean);
54 addRangeListener(listener: PDFDataRangeTransportListener): void;
55 addProgressListener(listener: PDFDataRangeTransportListener): void;
56 addProgressiveReadListener(listener: PDFDataRangeTransportListener): void;
57 addProgressiveDoneListener(listener: PDFDataRangeTransportListener): void;
58 onDataRange(begin: number, chunk: unknown): void;
59 onDataProgress(loaded: number, total: number): void;
60 onDataProgressiveRead(chunk: unknown): void;
61 onDataProgressiveDone(): void;
62 transportReady(): void;
63 requestDataRange(begin: number, end: number): void;
64 abort(): void;
65}
66
67interface PDFWorkerParameters {
68 name?: string;
69 port?: any;
70 verbosity?: VerbosityLevel;
71}
72
73declare class PDFWorker {
74 constructor(params?: PDFWorkerParameters);
75 readonly promise: Promise<unknown>;
76 readonly port: any | null;
77 readonly messageHandler: unknown | null;
78 destroy(): void;
79 static fromPort(params?: PDFWorkerParameters): PDFWorker;
80 static getWorkerSrc(): string;
81}
82declare enum CMapCompressionType {
83 NONE = 0,
84 BINARY = 1,
85 STREAM = 2,
86}
87interface CMapReaderFactory {
88 new (params: { baseUrl: string; isCompressed: boolean }): CMapReader;
89}
90interface CMapReader {
91 fetch(params: {
92 name: string;
93 }): Promise<{
94 cMapData: any;
95 compressionType: CMapCompressionType;
96 }>;
97}
98interface PDFSource {
99 /** The URL of the PDF. */
100 url?: string;
101 /**
102 * Binary PDF data. Use typed arrays
103 * (Uint8Array) to improve the memory usage. If PDF data is BASE64-encoded,
104 * use atob() to convert it to a binary string first.
105 */
106 data?: Uint8Array | BufferSource | string;
107 /**
108 * Basic authentication headers.
109 */
110 httpHeaders?: {
111 [key: string]: string;
112 };
113 /**
114 * For decrypting password-protected PDFs.
115 */
116 password?: string;
117 /**
118 * Indicates whether or not cross-site
119 * Access-Control requests should be made using credentials such as cookies
120 * or authorization headers. The default is false.
121 */
122 withCredentials?: boolean;
123 /*
124 * A typed array with the first portion or
125 * all of the pdf data. Used by the extension since some data is already
126 * loaded before the switch to range requests. */
127 initialData?: Uint8Array | BufferSource;
128 /*
129 * The PDF file length. It's used for progress
130 * reports and range requests operations.
131 */
132 length?: number;
133 /** range */
134 range?: PDFDataRangeTransport;
135 /**
136 * Optional parameter to specify
137 * maximum number of bytes fetched per range request. The default value is
138 * 2^16 = 65536. */
139 rangeChunkSize?: number;
140 /**
141 * The worker that will be used for
142 * the loading and parsing of the PDF data.
143 */
144 worker?: PDFWorker;
145 /**
146 * Controls the logging level; the
147 * constants from {VerbosityLevel} should be used.
148 */
149 verbosity?: number;
150 /**
151 * The base URL of the document,
152 * used when attempting to recover valid absolute URLs for annotations, and
153 * outline items, that (incorrectly) only specify relative URLs.
154 */
155 docBaseUrl?: string;
156 /**
157 * Strategy for
158 * decoding certain (simple) JPEG images in the browser. This is useful for
159 * environments without DOM image and canvas support, such as e.g. Node.js.
160 * Valid values are 'decode', 'display' or 'none'; where 'decode' is intended
161 * for browsers with full image/canvas support, 'display' for environments
162 * with limited image support through stubs (useful for SVG conversion),
163 * and 'none' where JPEG images will be decoded entirely by PDF.js.
164 * The default value is 'decode'.
165 */
166 nativeImageDecoderSupport?: 'decode' | 'display' | 'none';
167 /**
168 * The URL where the predefined
169 * Adobe CMaps are located. Include trailing slash. */
170 cMapUrl?: string;
171 /**
172 * Specifies if the Adobe CMaps are
173 * binary packed. */
174 cMapPacked?: boolean;
175 /**
176 * The factory that will be
177 * used when reading built-in CMap files. Providing a custom factory is useful
178 * for environments without `XMLHttpRequest` support, such as e.g. Node.js.
179 * The default value is {DOMCMapReaderFactory}.
180 */
181 CMapReaderFactory?: any;
182 /**
183 * Reject certain promises, e.g.
184 * `getOperatorList`, `getTextContent`, and `RenderTask`, when the associated
185 * PDF data cannot be successfully parsed, instead of attempting to recover
186 * whatever possible of the data. The default value is `false`.
187 */
188 stopAtErrors?: boolean;
189 /**
190 * The maximum allowed image size
191 * in total pixels, i.e. width * height. Images above this value will not be
192 * rendered. Use -1 for no limit, which is also the default value.
193 */
194 maxImageSize?: number;
195 /**
196 * Determines if we can eval
197 * strings as JS. Primarily used to improve performance of font rendering,
198 * and when parsing PDF functions. The default value is `true`.
199 */
200 isEvalSupported?: boolean;
201 /**
202 * By default fonts are
203 * converted to OpenType fonts and loaded via font face rules. If disabled,
204 * fonts will be rendered using a built-in font renderer that constructs the
205 * glyphs with primitive path commands. The default value is `false`.
206 */
207 disableFontFace?: boolean;
208 /**
209 * Disable range request loading
210 * of PDF files. When enabled, and if the server supports partial content
211 * requests, then the PDF will be fetched in chunks.
212 * The default value is `false`.
213 */
214 disableRange?: boolean;
215 /**
216 * Disable streaming of PDF file
217 * data. By default PDF.js attempts to load PDFs in chunks.
218 * The default value is `false`.
219 */
220 disableStream?: boolean;
221 /**
222 * Disable pre-fetching of PDF
223 * file data. When range requests are enabled PDF.js will automatically keep
224 * fetching more data even if it isn't needed to display the current page.
225 * The default value is `false`.
226 * NOTE: It is also necessary to disable streaming, see above,
227 * in order for disabling of pre-fetching to work correctly.
228 */
229 disableAutoFetch?: boolean;
230 /**
231 * Disable the use of
232 * `URL.createObjectURL`, for compatibility with older browsers.
233 * The default value is `false`.
234 */
235 disableCreateObjectURL?: boolean;
236 /**
237 * Enables special hooks for debugging
238 * PDF.js (see `web/debugger.js`). The default value is `false`.
239 */
240 pdfBug?: boolean;
241}
242
243interface PDFProgressData {
244 loaded: number;
245 total: number;
246}
247
248interface PDFDocumentProxy {
249 /**
250 * Total number of pages the PDF contains.
251 **/
252 numPages: number;
253
254 /**
255 * A unique ID to identify a PDF. Not guaranteed to be unique. [jbaldwin: haha what]
256 **/
257 fingerprint: string;
258
259 /**
260 * True if embedded document fonts are in use. Will be set during rendering of the pages.
261 **/
262 embeddedFontsUsed(): boolean;
263
264 /**
265 * @param number The page number to get. The first page is 1.
266 * @return A promise that is resolved with a PDFPageProxy.
267 **/
268 getPage(number: number): Promise<PDFPageProxy>;
269
270 /**
271 * TODO: return type of Promise<???>
272 * A promise that is resolved with a lookup table for mapping named destinations to reference numbers.
273 **/
274 getDestinations(): Promise<any[]>;
275
276 /**
277 * A promise that is resolved with an array of all the JavaScript strings in the name tree.
278 **/
279 getJavaScript(): Promise<string[]>;
280
281 /**
282 * A promise that is resolved with an array that is a tree outline (if it has one) of the PDF. @see PDFTreeNode
283 **/
284 getOutline(): Promise<PDFTreeNode[]>;
285
286 /**
287 * A promise that is resolved with an array that contains the permission flags for the PDF document.
288 **/
289 getPermissions(): Promise<number[]>;
290
291 /**
292 * A promise that is resolved with the info and metadata of the PDF.
293 **/
294 getMetadata(): Promise<{ info: PDFInfo; metadata: PDFMetadata }>;
295
296 /**
297 * Is the PDF encrypted?
298 **/
299 isEncrypted(): Promise<boolean>;
300
301 /**
302 * A promise that is resolved with Uint8Array that has the raw PDF data.
303 **/
304 getData(): Promise<Uint8Array>;
305
306 /**
307 * TODO: return type of Promise<???>
308 * A promise that is resolved when the document's data is loaded.
309 **/
310 dataLoaded(): Promise<any[]>;
311
312 /**
313 *
314 **/
315 destroy(): void;
316}
317
318interface PDFRef {
319 num: number;
320 gen: any; // todo
321}
322
323interface PDFPageViewportOptions {
324 viewBox: any;
325 scale: number;
326 rotation: number;
327 offsetX: number;
328 offsetY: number;
329 dontFlip: boolean;
330}
331
332interface PDFPageViewport {
333 width: number;
334 height: number;
335 scale: number;
336 transforms: number[];
337
338 clone(options: PDFPageViewportOptions): PDFPageViewport;
339 convertToViewportPoint(x: number, y: number): number[]; // [x, y]
340 convertToViewportRectangle(rect: number[]): number[]; // [x1, y1, x2, y2]
341 convertToPdfPoint(x: number, y: number): number[]; // [x, y]
342}
343
344interface ViewportParameters {
345 scale: number; // The desired scale of the viewport.
346 rotation?: number; // (optional) The desired rotation, in degrees, of the viewport. If omitted it defaults to the page rotation.
347 offsetX?: number; // (optional) The horizontal, i.e. x-axis, offset. The default value is `0`.
348 offsetY?: number; // (optional) The vertical, i.e. y-axis, offset. The default value is `0`.
349 dontFlip?: boolean; // (optional) If true, the y-axis will not be flipped. The default value is `false`.
350}
351interface PDFAnnotationData {
352 subtype: string;
353 rect: number[]; // [x1, y1, x2, y2]
354 annotationFlags: any; // todo
355 color: number[]; // [r,g,b]
356 borderWidth: number;
357 hasAppearance: boolean;
358}
359
360interface PDFAnnotations {
361 getData(): PDFAnnotationData;
362 hasHtml(): boolean; // always false
363 getHtmlElement(commonOjbs: any): HTMLElement; // throw new NotImplementedException()
364 getEmptyContainer(tagName: string, rect: number[]): HTMLElement; // deprecated
365 isViewable(): boolean;
366 loadResources(keys: any): Promise<any>;
367 getOperatorList(evaluator: any): Promise<any>;
368 // ... todo
369}
370
371interface PDFRenderTextLayer {
372 beginLayout(): void;
373 endLayout(): void;
374 appendText(): void;
375}
376
377interface PDFRenderImageLayer {
378 beginLayout(): void;
379 endLayout(): void;
380 appendImage(): void;
381}
382
383interface PDFRenderParams {
384 canvasContext: CanvasRenderingContext2D;
385 viewport?: PDFPageViewport;
386 textLayer?: PDFRenderTextLayer;
387 imageLayer?: PDFRenderImageLayer;
388 renderInteractiveForms?: boolean;
389 continueCallback?: (_continue: () => void) => void;
390}
391
392interface PDFViewerParams {
393 container: HTMLElement;
394 viewer?: HTMLElement;
395}
396
397/**
398 * RenderTask is basically a promise but adds a cancel function to termiate it.
399 **/
400interface PDFRenderTask extends PDFLoadingTask<PDFPageProxy> {
401 /**
402 * Cancel the rendering task. If the task is currently rendering it will not be cancelled until graphics pauses with a timeout. The promise that this object extends will resolve when cancelled.
403 **/
404 cancel(): void;
405}
406
407interface PDFPageProxy {
408 /**
409 * Page index of the page. First page is 0.
410 */
411 pageIndex: number;
412
413 /**
414 * Page number of the page. First page is 1.
415 **/
416 pageNumber: number;
417
418 /**
419 * The number of degrees the page is rotated clockwise.
420 **/
421 rotate: number;
422
423 /**
424 * The reference that points to this page.
425 **/
426 ref: PDFRef;
427
428 /**
429 * @return An array of the visible portion of the PDF page in the user space units - [x1, y1, x2, y2].
430 **/
431 view: number[];
432
433 /**
434 * @param params viewport options
435 * @return
436 **/
437 getViewport(params: ViewportParameters): PDFPageViewport;
438
439 /**
440 * A promise that is resolved with an array of the annotation objects.
441 **/
442 getAnnotations(): Promise<PDFAnnotations>;
443
444 /**
445 * Begins the process of rendering a page to the desired context.
446 * @param params Rendering options.
447 * @return An extended promise that is resolved when the page finishes rendering.
448 **/
449 render(params: PDFRenderParams): PDFRenderTask;
450
451 /**
452 * A promise that is resolved with the string that is the text content frm the page.
453 **/
454 getTextContent(): Promise<TextContent>;
455
456 /**
457 * marked as future feature
458 **/
459 //getOperationList(): Promise<>;
460
461 /**
462 * Destroyes resources allocated by the page.
463 **/
464 destroy(): void;
465}
466
467interface TextContentItem {
468 str: string;
469 transform: number[]; // [0..5] 4=x, 5=y
470 width: number;
471 height: number;
472 dir: string; // Left-to-right (ltr), etc
473 fontName: string; // A lookup into the styles map of the owning TextContent
474}
475
476interface TextContent {
477 items: TextContentItem[];
478 styles: any;
479}
480
481/**
482 * A PDF document and page is built of many objects. E.g. there are objects for fonts, images, rendering code and such. These objects might get processed inside of a worker. The `PDFObjects` implements some basic functions to manage these objects.
483 **/
484interface PDFObjects {
485 get(objId: number, callback?: any): any;
486 resolve(objId: number, data: any): any;
487 isResolved(objId: number): boolean;
488 hasData(objId: number): boolean;
489 getData(objId: number): any;
490 clear(): void;
491}
492
493interface PDFJSUtilStatic {
494 /**
495 * Normalize rectangle so that (x1,y1) < (x2,y2)
496 * @param {number[]} rect - the rectangle with [x1,y1,x2,y2]
497 *
498 * For coordinate systems whose origin lies in the bottom-left, this
499 * means normalization to (BL,TR) ordering. For systems with origin in the
500 * top-left, this means (TL,BR) ordering.
501 **/
502 normalizeRect(rect: number[]): number[];
503}
504
505export const PDFJS: PDFJSStatic;
506
507interface PDFJSStatic {
508 /**
509 * The maximum allowed image size in total pixels e.g. width * height. Images above this value will not be drawn. Use -1 for no limit.
510 **/
511 maxImageSize: number;
512
513 /**
514 * The url of where the predefined Adobe CMaps are located. Include trailing
515 * slash.
516 */
517 cMapUrl: string;
518
519 /**
520 * Specifies if CMaps are binary packed.
521 */
522 cMapPacked: boolean;
523
524 /**
525 * By default fonts are converted to OpenType fonts and loaded via font face rules. If disabled, the font will be rendered using a built in font renderer that constructs the glyphs with primitive path commands.
526 **/
527 disableFontFace: boolean;
528
529 /**
530 * Path for image resources, mainly for annotation icons. Include trailing
531 * slash.
532 */
533 imageResourcesPath: string;
534
535 /**
536 * Disable the web worker and run all code on the main thread. This will happen
537 * automatically if the browser doesn't support workers or sending typed arrays
538 * to workers.
539 */
540 disableWorker: boolean;
541
542 /**
543 * Path and filename of the worker file. Required when the worker is enabled in
544 * development mode. If unspecified in the production build, the worker will be
545 * loaded based on the location of the pdf.js file.
546 */
547 workerSrc: string;
548
549 /**
550 * Disable range request loading of PDF files. When enabled and if the server
551 * supports partial content requests then the PDF will be fetched in chunks.
552 * Enabled (false) by default.
553 */
554 disableRange: boolean;
555
556 /**
557 * Disable streaming of PDF file data. By default PDF.js attempts to load PDF
558 * in chunks. This default behavior can be disabled.
559 */
560 disableStream: boolean;
561
562 /**
563 * Disable pre-fetching of PDF file data. When range requests are enabled PDF.js
564 * will automatically keep fetching more data even if it isn't needed to display
565 * the current page. This default behavior can be disabled.
566 *
567 * NOTE: It is also necessary to disable streaming, see above,
568 * in order for disabling of pre-fetching to work correctly.
569 */
570 disableAutoFetch: boolean;
571
572 /**
573 * Enables special hooks for debugging PDF.js.
574 */
575 pdfBug: boolean;
576
577 /**
578 * Enables transfer usage in postMessage for ArrayBuffers.
579 */
580 postMessageTransfers: boolean;
581
582 /**
583 * Disables URL.createObjectURL usage.
584 */
585 disableCreateObjectURL: boolean;
586
587 /**
588 * Disables WebGL usage.
589 */
590 disableWebGL: boolean;
591
592 /**
593 * Disables fullscreen support, and by extension Presentation Mode,
594 * in browsers which support the fullscreen API.
595 */
596 disableFullscreen: boolean;
597
598 /**
599 * Disable the text layer of PDF when used PDF.js renders a canvas instead of div elements
600 *
601 */
602 disableTextLayer: boolean;
603
604 /**
605 * Enables CSS only zooming.
606 */
607 useOnlyCssZoom: boolean;
608
609 /**
610 * Controls the logging level.
611 * The constants from PDFJS.VERBOSITY_LEVELS should be used:
612 * - errors
613 * - warnings [default]
614 * - infos
615 */
616 verbosity: number;
617
618 /**
619 * The maximum supported canvas size in total pixels e.g. width * height.
620 * The default value is 4096 * 4096. Use -1 for no limit.
621 */
622 maxCanvasPixels: number;
623
624 /**
625 * Opens external links in a new window if enabled. The default behavior opens
626 * external links in the PDF.js window.
627 */
628 openExternalLinksInNewWindow: boolean;
629
630 /**
631 * Determines if we can eval strings as JS. Primarily used to improve
632 * performance for font rendering.
633 */
634 isEvalSupported: boolean;
635
636 PDFViewer(params: PDFViewerParams): void;
637 /**
638 * yet another viewer, this will render only one page at the time, reducing rendering time
639 * very important for mobile development
640 * @params {PDFViewerParams}
641 */
642 PDFSinglePageViewer(params: PDFViewerParams): void;
643}
644
645interface PDFLoadingTask<T> {
646 promise: Promise<T>;
647}
648
649declare const Util: PDFJSUtilStatic;
650
651/**
652 * This is the main entry point for loading a PDF and interacting with it.
653 * NOTE: If a URL is used to fetch the PDF data a standard XMLHttpRequest(XHR)
654 * is used, which means it must follow the same origin rules that any XHR does
655 * e.g. No corss domain requests without CORS.
656 * @param source
657 * @param pdfDataRangeTransport Used if you want to manually server range requests for data in the PDF. @ee viewer.js for an example of pdfDataRangeTransport's interface.
658 * @param passwordCallback Used to request a password if wrong or no password was provided. The callback receives two parameters: function that needs to be called with new password and the reason.
659 * @param progressCallback Progress callback.
660 * @return A promise that is resolved with PDFDocumentProxy object.
661 **/
662declare function getDocument(
663 url: string,
664 pdfDataRangeTransport?: PDFDataRangeTransport,
665 passwordCallback?: (fn: (password: string) => void, reason: string) => string,
666 progressCallback?: (progressData: PDFProgressData) => void,
667): PDFLoadingTask<PDFDocumentProxy>;
668
669declare function getDocument(
670 data: Uint8Array | BufferSource,
671 pdfDataRangeTransport?: PDFDataRangeTransport,
672 passwordCallback?: (fn: (password: string) => void, reason: string) => string,
673 progressCallback?: (progressData: PDFProgressData) => void,
674): PDFLoadingTask<PDFDocumentProxy>;
675
676declare function getDocument(
677 source: PDFSource,
678 pdfDataRangeTransport?: PDFDataRangeTransport,
679 passwordCallback?: (fn: (password: string) => void, reason: string) => string,
680 progressCallback?: (progressData: PDFProgressData) => void,
681): PDFLoadingTask<PDFDocumentProxy>;