-
Notifications
You must be signed in to change notification settings - Fork 10.1k
/
api.js
2434 lines (2198 loc) · 82 KB
/
api.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* Copyright 2012 Mozilla Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* globals requirejs, __non_webpack_require__ */
import {
assert, createPromiseCapability, deprecated, getVerbosityLevel, info,
InvalidPDFException, isArrayBuffer, isSameOrigin, loadJpegStream,
MessageHandler, MissingPDFException, NativeImageDecoding, PageViewport,
PasswordException, StatTimer, stringToBytes, UnexpectedResponseException,
UnknownErrorException, Util, warn
} from '../shared/util';
import {
DOMCanvasFactory, DOMCMapReaderFactory, getDefaultSetting,
RenderingCancelledException
} from './dom_utils';
import { FontFaceObject, FontLoader } from './font_loader';
import { CanvasGraphics } from './canvas';
import globalScope from '../shared/global_scope';
import { Metadata } from './metadata';
import { PDFDataTransportStream } from './transport_stream';
var DEFAULT_RANGE_CHUNK_SIZE = 65536; // 2^16 = 65536
var isWorkerDisabled = false;
var workerSrc;
var isPostMessageTransfersDisabled = false;
var pdfjsFilePath =
typeof PDFJSDev !== 'undefined' &&
PDFJSDev.test('PRODUCTION && !(MOZCENTRAL || FIREFOX)') &&
typeof document !== 'undefined' && document.currentScript ?
document.currentScript.src : null;
var fakeWorkerFilesLoader = null;
var useRequireEnsure = false;
if (typeof PDFJSDev !== 'undefined' &&
PDFJSDev.test('GENERIC && !SINGLE_FILE')) {
// For GENERIC build we need add support of different fake file loaders
// for different frameworks.
if (typeof window === 'undefined') {
// node.js - disable worker and set require.ensure.
isWorkerDisabled = true;
if (typeof __non_webpack_require__.ensure === 'undefined') {
__non_webpack_require__.ensure = __non_webpack_require__('node-ensure');
}
useRequireEnsure = true;
} else if (typeof __non_webpack_require__ !== 'undefined' &&
typeof __non_webpack_require__.ensure === 'function') {
useRequireEnsure = true;
}
if (typeof requirejs !== 'undefined' && requirejs.toUrl) {
workerSrc = requirejs.toUrl('pdfjs-dist/build/pdf.worker.js');
}
var dynamicLoaderSupported =
typeof requirejs !== 'undefined' && requirejs.load;
fakeWorkerFilesLoader = useRequireEnsure ? (function (callback) {
__non_webpack_require__.ensure([], function () {
var worker;
if (typeof PDFJSDev !== 'undefined' && PDFJSDev.test('LIB')) {
worker = __non_webpack_require__('../pdf.worker.js');
} else {
worker = __non_webpack_require__('./pdf.worker.js');
}
callback(worker.WorkerMessageHandler);
});
}) : dynamicLoaderSupported ? (function (callback) {
requirejs(['pdfjs-dist/build/pdf.worker'], function (worker) {
callback(worker.WorkerMessageHandler);
});
}) : null;
}
/** @type IPDFStream */
var PDFNetworkStream;
/**
* Sets PDFNetworkStream class to be used as alternative PDF data transport.
* @param {IPDFStream} cls - the PDF data transport.
*/
function setPDFNetworkStreamClass(cls) {
PDFNetworkStream = cls;
}
/**
* Document initialization / loading parameters object.
*
* @typedef {Object} DocumentInitParameters
* @property {string} url - The URL of the PDF.
* @property {TypedArray|Array|string} data - Binary PDF data. Use typed arrays
* (Uint8Array) to improve the memory usage. If PDF data is BASE64-encoded,
* use atob() to convert it to a binary string first.
* @property {Object} httpHeaders - Basic authentication headers.
* @property {boolean} withCredentials - Indicates whether or not cross-site
* Access-Control requests should be made using credentials such as cookies
* or authorization headers. The default is false.
* @property {string} password - For decrypting password-protected PDFs.
* @property {TypedArray} initialData - A typed array with the first portion or
* all of the pdf data. Used by the extension since some data is already
* loaded before the switch to range requests.
* @property {number} length - The PDF file length. It's used for progress
* reports and range requests operations.
* @property {PDFDataRangeTransport} range
* @property {number} rangeChunkSize - Optional parameter to specify
* maximum number of bytes fetched per range request. The default value is
* 2^16 = 65536.
* @property {PDFWorker} worker - The worker that will be used for the loading
* and parsing of the PDF data.
* @property {string} docBaseUrl - (optional) The base URL of the document,
* used when attempting to recover valid absolute URLs for annotations, and
* outline items, that (incorrectly) only specify relative URLs.
* @property {boolean} disableNativeImageDecoder - (deprecated) Disable decoding
* of certain (simple) JPEG images in the browser. This is useful for
* environments without DOM image support, such as e.g. Node.js.
* The default value is `false`.
* @property {string} nativeImageDecoderSupport - (optional) Strategy for
* decoding certain (simple) JPEG images in the browser. This is useful for
* environments without DOM image and canvas support, such as e.g. Node.js.
* Valid values are 'decode', 'display' or 'none'; where 'decode' is intended
* for browsers with full image/canvas support, 'display' for environments
* with limited image support through stubs (useful for SVG conversion),
* and 'none' where JPEG images will be decoded entirely by PDF.js.
* The default value is 'decode'.
* @property {Object} CMapReaderFactory - (optional) The factory that will be
* used when reading built-in CMap files. Providing a custom factory is useful
* for environments without `XMLHttpRequest` support, such as e.g. Node.js.
* The default value is {DOMCMapReaderFactory}.
* @property {boolean} stopAtErrors - (optional) Reject certain promises, e.g.
* `getOperatorList`, `getTextContent`, and `RenderTask`, when the associated
* PDF data cannot be successfully parsed, instead of attempting to recover
* whatever possible of the data. The default value is `false`.
*/
/**
* @typedef {Object} PDFDocumentStats
* @property {Array} streamTypes - Used stream types in the document (an item
* is set to true if specific stream ID was used in the document).
* @property {Array} fontTypes - Used font type in the document (an item is set
* to true if specific font ID was used in the document).
*/
/**
* This is the main entry point for loading a PDF and interacting with it.
* NOTE: If a URL is used to fetch the PDF data a standard XMLHttpRequest(XHR)
* is used, which means it must follow the same origin rules that any XHR does
* e.g. No cross domain requests without CORS.
*
* @param {string|TypedArray|DocumentInitParameters|PDFDataRangeTransport} src
* Can be a url to where a PDF is located, a typed array (Uint8Array)
* already populated with data or parameter object.
*
* @param {PDFDataRangeTransport} pdfDataRangeTransport (deprecated) It is used
* if you want to manually serve range requests for data in the PDF.
*
* @param {function} passwordCallback (deprecated) It is 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 reason
* (see {PasswordResponses}).
*
* @param {function} progressCallback (deprecated) It is used to be able to
* monitor the loading progress of the PDF file (necessary to implement e.g.
* a loading bar). The callback receives an {Object} with the properties:
* {number} loaded and {number} total.
*
* @return {PDFDocumentLoadingTask}
*/
function getDocument(src, pdfDataRangeTransport,
passwordCallback, progressCallback) {
var task = new PDFDocumentLoadingTask();
// Support of the obsolete arguments (for compatibility with API v1.0)
if (arguments.length > 1) {
deprecated('getDocument is called with pdfDataRangeTransport, ' +
'passwordCallback or progressCallback argument');
}
if (pdfDataRangeTransport) {
if (!(pdfDataRangeTransport instanceof PDFDataRangeTransport)) {
// Not a PDFDataRangeTransport instance, trying to add missing properties.
pdfDataRangeTransport = Object.create(pdfDataRangeTransport);
pdfDataRangeTransport.length = src.length;
pdfDataRangeTransport.initialData = src.initialData;
if (!pdfDataRangeTransport.abort) {
pdfDataRangeTransport.abort = function () {};
}
}
src = Object.create(src);
src.range = pdfDataRangeTransport;
}
task.onPassword = passwordCallback || null;
task.onProgress = progressCallback || null;
var source;
if (typeof src === 'string') {
source = { url: src, };
} else if (isArrayBuffer(src)) {
source = { data: src, };
} else if (src instanceof PDFDataRangeTransport) {
source = { range: src, };
} else {
if (typeof src !== 'object') {
throw new Error('Invalid parameter in getDocument, ' +
'need either Uint8Array, string or a parameter object');
}
if (!src.url && !src.data && !src.range) {
throw new Error(
'Invalid parameter object: need either .data, .range or .url');
}
source = src;
}
var params = {};
var rangeTransport = null;
var worker = null;
var CMapReaderFactory = DOMCMapReaderFactory;
for (var key in source) {
if (key === 'url' && typeof window !== 'undefined') {
// The full path is required in the 'url' field.
params[key] = new URL(source[key], window.location).href;
continue;
} else if (key === 'range') {
rangeTransport = source[key];
continue;
} else if (key === 'worker') {
worker = source[key];
continue;
} else if (key === 'data' && !(source[key] instanceof Uint8Array)) {
// Converting string or array-like data to Uint8Array.
var pdfBytes = source[key];
if (typeof pdfBytes === 'string') {
params[key] = stringToBytes(pdfBytes);
} else if (typeof pdfBytes === 'object' && pdfBytes !== null &&
!isNaN(pdfBytes.length)) {
params[key] = new Uint8Array(pdfBytes);
} else if (isArrayBuffer(pdfBytes)) {
params[key] = new Uint8Array(pdfBytes);
} else {
throw new Error('Invalid PDF binary data: either typed array, ' +
'string or array-like object is expected in the ' +
'data property.');
}
continue;
} else if (key === 'CMapReaderFactory') {
CMapReaderFactory = source[key];
continue;
}
params[key] = source[key];
}
params.rangeChunkSize = params.rangeChunkSize || DEFAULT_RANGE_CHUNK_SIZE;
params.ignoreErrors = params.stopAtErrors !== true;
if (params.disableNativeImageDecoder !== undefined) {
deprecated('parameter disableNativeImageDecoder, ' +
'use nativeImageDecoderSupport instead');
}
params.nativeImageDecoderSupport = params.nativeImageDecoderSupport ||
(params.disableNativeImageDecoder === true ? NativeImageDecoding.NONE :
NativeImageDecoding.DECODE);
if (params.nativeImageDecoderSupport !== NativeImageDecoding.DECODE &&
params.nativeImageDecoderSupport !== NativeImageDecoding.NONE &&
params.nativeImageDecoderSupport !== NativeImageDecoding.DISPLAY) {
warn('Invalid parameter nativeImageDecoderSupport: ' +
'need a state of enum {NativeImageDecoding}');
params.nativeImageDecoderSupport = NativeImageDecoding.DECODE;
}
if (!worker) {
// Worker was not provided -- creating and owning our own. If message port
// is specified in global settings, using it.
var workerPort = getDefaultSetting('workerPort');
worker = workerPort ? PDFWorker.fromPort(workerPort) : new PDFWorker();
task._worker = worker;
}
var docId = task.docId;
worker.promise.then(function () {
if (task.destroyed) {
throw new Error('Loading aborted');
}
return _fetchDocument(worker, params, rangeTransport, docId).then(
function (workerId) {
if (task.destroyed) {
throw new Error('Loading aborted');
}
let networkStream;
if (rangeTransport) {
networkStream = new PDFDataTransportStream(params, rangeTransport);
} else if (!params.data) {
networkStream = new PDFNetworkStream({
source: params,
disableRange: getDefaultSetting('disableRange'),
});
}
var messageHandler = new MessageHandler(docId, workerId, worker.port);
messageHandler.postMessageTransfers = worker.postMessageTransfers;
var transport = new WorkerTransport(messageHandler, task, networkStream,
CMapReaderFactory);
task._transport = transport;
messageHandler.send('Ready', null);
});
}).catch(task._capability.reject);
return task;
}
/**
* Starts fetching of specified PDF document/data.
* @param {PDFWorker} worker
* @param {Object} source
* @param {PDFDataRangeTransport} pdfDataRangeTransport
* @param {string} docId Unique document id, used as MessageHandler id.
* @returns {Promise} The promise, which is resolved when worker id of
* MessageHandler is known.
* @private
*/
function _fetchDocument(worker, source, pdfDataRangeTransport, docId) {
if (worker.destroyed) {
return Promise.reject(new Error('Worker was destroyed'));
}
source.disableAutoFetch = getDefaultSetting('disableAutoFetch');
source.disableStream = getDefaultSetting('disableStream');
source.chunkedViewerLoading = !!pdfDataRangeTransport;
if (pdfDataRangeTransport) {
source.length = pdfDataRangeTransport.length;
source.initialData = pdfDataRangeTransport.initialData;
}
return worker.messageHandler.sendWithPromise('GetDocRequest', {
docId,
source: {
data: source.data,
url: source.url,
password: source.password,
disableAutoFetch: source.disableAutoFetch,
rangeChunkSize: source.rangeChunkSize,
length: source.length,
},
maxImageSize: getDefaultSetting('maxImageSize'),
disableFontFace: getDefaultSetting('disableFontFace'),
disableCreateObjectURL: getDefaultSetting('disableCreateObjectURL'),
postMessageTransfers: getDefaultSetting('postMessageTransfers') &&
!isPostMessageTransfersDisabled,
docBaseUrl: source.docBaseUrl,
nativeImageDecoderSupport: source.nativeImageDecoderSupport,
ignoreErrors: source.ignoreErrors,
}).then(function (workerId) {
if (worker.destroyed) {
throw new Error('Worker was destroyed');
}
return workerId;
});
}
/**
* PDF document loading operation.
* @class
* @alias PDFDocumentLoadingTask
*/
var PDFDocumentLoadingTask = (function PDFDocumentLoadingTaskClosure() {
var nextDocumentId = 0;
/** @constructs PDFDocumentLoadingTask */
function PDFDocumentLoadingTask() {
this._capability = createPromiseCapability();
this._transport = null;
this._worker = null;
/**
* Unique document loading task id -- used in MessageHandlers.
* @type {string}
*/
this.docId = 'd' + (nextDocumentId++);
/**
* Shows if loading task is destroyed.
* @type {boolean}
*/
this.destroyed = false;
/**
* Callback 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 reason (see {PasswordResponses}).
*/
this.onPassword = null;
/**
* Callback to be able to monitor the loading progress of the PDF file
* (necessary to implement e.g. a loading bar). The callback receives
* an {Object} with the properties: {number} loaded and {number} total.
*/
this.onProgress = null;
/**
* Callback to when unsupported feature is used. The callback receives
* an {UNSUPPORTED_FEATURES} argument.
*/
this.onUnsupportedFeature = null;
}
PDFDocumentLoadingTask.prototype =
/** @lends PDFDocumentLoadingTask.prototype */ {
/**
* @return {Promise}
*/
get promise() {
return this._capability.promise;
},
/**
* Aborts all network requests and destroys worker.
* @return {Promise} A promise that is resolved after destruction activity
* is completed.
*/
destroy() {
this.destroyed = true;
var transportDestroyed = !this._transport ? Promise.resolve() :
this._transport.destroy();
return transportDestroyed.then(() => {
this._transport = null;
if (this._worker) {
this._worker.destroy();
this._worker = null;
}
});
},
/**
* Registers callbacks to indicate the document loading completion.
*
* @param {function} onFulfilled The callback for the loading completion.
* @param {function} onRejected The callback for the loading failure.
* @return {Promise} A promise that is resolved after the onFulfilled or
* onRejected callback.
*/
then: function PDFDocumentLoadingTask_then(onFulfilled, onRejected) {
return this.promise.then.apply(this.promise, arguments);
},
};
return PDFDocumentLoadingTask;
})();
/**
* Abstract class to support range requests file loading.
* @class
* @alias PDFDataRangeTransport
* @param {number} length
* @param {Uint8Array} initialData
*/
var PDFDataRangeTransport = (function pdfDataRangeTransportClosure() {
function PDFDataRangeTransport(length, initialData) {
this.length = length;
this.initialData = initialData;
this._rangeListeners = [];
this._progressListeners = [];
this._progressiveReadListeners = [];
this._readyCapability = createPromiseCapability();
}
PDFDataRangeTransport.prototype =
/** @lends PDFDataRangeTransport.prototype */ {
addRangeListener:
function PDFDataRangeTransport_addRangeListener(listener) {
this._rangeListeners.push(listener);
},
addProgressListener:
function PDFDataRangeTransport_addProgressListener(listener) {
this._progressListeners.push(listener);
},
addProgressiveReadListener:
function PDFDataRangeTransport_addProgressiveReadListener(listener) {
this._progressiveReadListeners.push(listener);
},
onDataRange: function PDFDataRangeTransport_onDataRange(begin, chunk) {
var listeners = this._rangeListeners;
for (var i = 0, n = listeners.length; i < n; ++i) {
listeners[i](begin, chunk);
}
},
onDataProgress: function PDFDataRangeTransport_onDataProgress(loaded) {
this._readyCapability.promise.then(() => {
var listeners = this._progressListeners;
for (var i = 0, n = listeners.length; i < n; ++i) {
listeners[i](loaded);
}
});
},
onDataProgressiveRead:
function PDFDataRangeTransport_onDataProgress(chunk) {
this._readyCapability.promise.then(() => {
var listeners = this._progressiveReadListeners;
for (var i = 0, n = listeners.length; i < n; ++i) {
listeners[i](chunk);
}
});
},
transportReady: function PDFDataRangeTransport_transportReady() {
this._readyCapability.resolve();
},
requestDataRange:
function PDFDataRangeTransport_requestDataRange(begin, end) {
throw new Error('Abstract method PDFDataRangeTransport.requestDataRange');
},
abort: function PDFDataRangeTransport_abort() {
},
};
return PDFDataRangeTransport;
})();
/**
* Proxy to a PDFDocument in the worker thread. Also, contains commonly used
* properties that can be read synchronously.
* @class
* @alias PDFDocumentProxy
*/
var PDFDocumentProxy = (function PDFDocumentProxyClosure() {
function PDFDocumentProxy(pdfInfo, transport, loadingTask) {
this.pdfInfo = pdfInfo;
this.transport = transport;
this.loadingTask = loadingTask;
}
PDFDocumentProxy.prototype = /** @lends PDFDocumentProxy.prototype */ {
/**
* @return {number} Total number of pages the PDF contains.
*/
get numPages() {
return this.pdfInfo.numPages;
},
/**
* @return {string} A unique ID to identify a PDF. Not guaranteed to be
* unique.
*/
get fingerprint() {
return this.pdfInfo.fingerprint;
},
/**
* @param {number} pageNumber The page number to get. The first page is 1.
* @return {Promise} A promise that is resolved with a {@link PDFPageProxy}
* object.
*/
getPage: function PDFDocumentProxy_getPage(pageNumber) {
return this.transport.getPage(pageNumber);
},
/**
* @param {{num: number, gen: number}} ref The page reference. Must have
* the 'num' and 'gen' properties.
* @return {Promise} A promise that is resolved with the page index that is
* associated with the reference.
*/
getPageIndex: function PDFDocumentProxy_getPageIndex(ref) {
return this.transport.getPageIndex(ref);
},
/**
* @return {Promise} A promise that is resolved with a lookup table for
* mapping named destinations to reference numbers.
*
* This can be slow for large documents: use getDestination instead
*/
getDestinations: function PDFDocumentProxy_getDestinations() {
return this.transport.getDestinations();
},
/**
* @param {string} id The named destination to get.
* @return {Promise} A promise that is resolved with all information
* of the given named destination.
*/
getDestination: function PDFDocumentProxy_getDestination(id) {
return this.transport.getDestination(id);
},
/**
* @return {Promise} A promise that is resolved with:
* an Array containing the pageLabels that correspond to the pageIndexes,
* or `null` when no pageLabels are present in the PDF file.
*/
getPageLabels: function PDFDocumentProxy_getPageLabels() {
return this.transport.getPageLabels();
},
/**
* @return {Promise} A promise that is resolved with a {string} containing
* the PageMode name.
*/
getPageMode() {
return this.transport.getPageMode();
},
/**
* @return {Promise} A promise that is resolved with a lookup table for
* mapping named attachments to their content.
*/
getAttachments: function PDFDocumentProxy_getAttachments() {
return this.transport.getAttachments();
},
/**
* @return {Promise} A promise that is resolved with an array of all the
* JavaScript strings in the name tree.
*/
getJavaScript: function PDFDocumentProxy_getJavaScript() {
return this.transport.getJavaScript();
},
/**
* @return {Promise} A promise that is resolved with an {Array} that is a
* tree outline (if it has one) of the PDF. The tree is in the format of:
* [
* {
* title: string,
* bold: boolean,
* italic: boolean,
* color: rgb Uint8Array,
* dest: dest obj,
* url: string,
* items: array of more items like this
* },
* ...
* ].
*/
getOutline: function PDFDocumentProxy_getOutline() {
return this.transport.getOutline();
},
/**
* @return {Promise} A promise that is resolved with an {Object} that has
* info and metadata properties. Info is an {Object} filled with anything
* available in the information dictionary and similarly metadata is a
* {Metadata} object with information from the metadata section of the PDF.
*/
getMetadata: function PDFDocumentProxy_getMetadata() {
return this.transport.getMetadata();
},
/**
* @return {Promise} A promise that is resolved with a TypedArray that has
* the raw data from the PDF.
*/
getData: function PDFDocumentProxy_getData() {
return this.transport.getData();
},
/**
* @return {Promise} A promise that is resolved when the document's data
* is loaded. It is resolved with an {Object} that contains the length
* property that indicates size of the PDF data in bytes.
*/
getDownloadInfo: function PDFDocumentProxy_getDownloadInfo() {
return this.transport.downloadInfoCapability.promise;
},
/**
* @return {Promise} A promise this is resolved with current stats about
* document structures (see {@link PDFDocumentStats}).
*/
getStats: function PDFDocumentProxy_getStats() {
return this.transport.getStats();
},
/**
* Cleans up resources allocated by the document, e.g. created @font-face.
*/
cleanup: function PDFDocumentProxy_cleanup() {
this.transport.startCleanup();
},
/**
* Destroys current document instance and terminates worker.
*/
destroy: function PDFDocumentProxy_destroy() {
return this.loadingTask.destroy();
},
};
return PDFDocumentProxy;
})();
/**
* Page getTextContent parameters.
*
* @typedef {Object} getTextContentParameters
* @property {boolean} normalizeWhitespace - replaces all occurrences of
* whitespace with standard spaces (0x20). The default value is `false`.
* @property {boolean} disableCombineTextItems - do not attempt to combine
* same line {@link TextItem}'s. The default value is `false`.
*/
/**
* Page text content.
*
* @typedef {Object} TextContent
* @property {array} items - array of {@link TextItem}
* @property {Object} styles - {@link TextStyles} objects, indexed by font name.
*/
/**
* Page text content part.
*
* @typedef {Object} TextItem
* @property {string} str - text content.
* @property {string} dir - text direction: 'ttb', 'ltr' or 'rtl'.
* @property {array} transform - transformation matrix.
* @property {number} width - width in device space.
* @property {number} height - height in device space.
* @property {string} fontName - font name used by pdf.js for converted font.
*/
/**
* Text style.
*
* @typedef {Object} TextStyle
* @property {number} ascent - font ascent.
* @property {number} descent - font descent.
* @property {boolean} vertical - text is in vertical mode.
* @property {string} fontFamily - possible font family
*/
/**
* Page annotation parameters.
*
* @typedef {Object} GetAnnotationsParameters
* @property {string} intent - Determines the annotations that will be fetched,
* can be either 'display' (viewable annotations) or 'print'
* (printable annotations).
* If the parameter is omitted, all annotations are fetched.
*/
/**
* Page render parameters.
*
* @typedef {Object} RenderParameters
* @property {Object} canvasContext - A 2D context of a DOM Canvas object.
* @property {PageViewport} viewport - Rendering viewport obtained by
* calling of PDFPage.getViewport method.
* @property {string} intent - Rendering intent, can be 'display' or 'print'
* (default value is 'display').
* @property {boolean} renderInteractiveForms - (optional) Whether or not
* interactive form elements are rendered in the display
* layer. If so, we do not render them on canvas as well.
* @property {Array} transform - (optional) Additional transform, applied
* just before viewport transform.
* @property {Object} imageLayer - (optional) An object that has beginLayout,
* endLayout and appendImage functions.
* @property {function} continueCallback - (deprecated) A function that will be
* called each time the rendering is paused. To continue
* rendering call the function that is the first argument
* to the callback.
* @property {Object} canvasFactory - (optional) The factory that will be used
* when creating canvases. The default value is
* {DOMCanvasFactory}.
* @property {Object} background - (optional) Background to use for the canvas.
* Can use any valid canvas.fillStyle: A DOMString parsed as
* CSS <color> value, a CanvasGradient object (a linear or
* radial gradient) or a CanvasPattern object (a repetitive
* image). The default value is 'rgb(255,255,255)'.
*/
/**
* PDF page operator list.
*
* @typedef {Object} PDFOperatorList
* @property {Array} fnArray - Array containing the operator functions.
* @property {Array} argsArray - Array containing the arguments of the
* functions.
*/
/**
* Proxy to a PDFPage in the worker thread.
* @class
* @alias PDFPageProxy
*/
var PDFPageProxy = (function PDFPageProxyClosure() {
function PDFPageProxy(pageIndex, pageInfo, transport) {
this.pageIndex = pageIndex;
this.pageInfo = pageInfo;
this.transport = transport;
this.stats = new StatTimer();
this.stats.enabled = getDefaultSetting('enableStats');
this.commonObjs = transport.commonObjs;
this.objs = new PDFObjects();
this.cleanupAfterRender = false;
this.pendingCleanup = false;
this.intentStates = Object.create(null);
this.destroyed = false;
}
PDFPageProxy.prototype = /** @lends PDFPageProxy.prototype */ {
/**
* @return {number} Page number of the page. First page is 1.
*/
get pageNumber() {
return this.pageIndex + 1;
},
/**
* @return {number} The number of degrees the page is rotated clockwise.
*/
get rotate() {
return this.pageInfo.rotate;
},
/**
* @return {Object} The reference that points to this page. It has 'num' and
* 'gen' properties.
*/
get ref() {
return this.pageInfo.ref;
},
/**
* @return {number} The default size of units in 1/72nds of an inch.
*/
get userUnit() {
return this.pageInfo.userUnit;
},
/**
* @return {Array} An array of the visible portion of the PDF page in the
* user space units - [x1, y1, x2, y2].
*/
get view() {
return this.pageInfo.view;
},
/**
* @param {number} scale The desired scale of the viewport.
* @param {number} rotate Degrees to rotate the viewport. If omitted this
* defaults to the page rotation.
* @return {PageViewport} Contains 'width' and 'height' properties
* along with transforms required for rendering.
*/
getViewport: function PDFPageProxy_getViewport(scale, rotate) {
if (arguments.length < 2) {
rotate = this.rotate;
}
return new PageViewport(this.view, scale, rotate, 0, 0);
},
/**
* @param {GetAnnotationsParameters} params - Annotation parameters.
* @return {Promise} A promise that is resolved with an {Array} of the
* annotation objects.
*/
getAnnotations: function PDFPageProxy_getAnnotations(params) {
var intent = (params && params.intent) || null;
if (!this.annotationsPromise || this.annotationsIntent !== intent) {
this.annotationsPromise = this.transport.getAnnotations(this.pageIndex,
intent);
this.annotationsIntent = intent;
}
return this.annotationsPromise;
},
/**
* Begins the process of rendering a page to the desired context.
* @param {RenderParameters} params Page render parameters.
* @return {RenderTask} An object that contains the promise, which
* is resolved when the page finishes rendering.
*/
render: function PDFPageProxy_render(params) {
var stats = this.stats;
stats.time('Overall');
// If there was a pending destroy cancel it so no cleanup happens during
// this call to render.
this.pendingCleanup = false;
var renderingIntent = (params.intent === 'print' ? 'print' : 'display');
var canvasFactory = params.canvasFactory || new DOMCanvasFactory();
if (!this.intentStates[renderingIntent]) {
this.intentStates[renderingIntent] = Object.create(null);
}
var intentState = this.intentStates[renderingIntent];
// If there's no displayReadyCapability yet, then the operatorList
// was never requested before. Make the request and create the promise.
if (!intentState.displayReadyCapability) {
intentState.receivingOperatorList = true;
intentState.displayReadyCapability = createPromiseCapability();
intentState.operatorList = {
fnArray: [],
argsArray: [],
lastChunk: false,
};
this.stats.time('Page Request');
this.transport.messageHandler.send('RenderPageRequest', {
pageIndex: this.pageNumber - 1,
intent: renderingIntent,
renderInteractiveForms: (params.renderInteractiveForms === true),
});
}
var complete = (error) => {
var i = intentState.renderTasks.indexOf(internalRenderTask);
if (i >= 0) {
intentState.renderTasks.splice(i, 1);
}
if (this.cleanupAfterRender) {
this.pendingCleanup = true;
}
this._tryCleanup();
if (error) {
internalRenderTask.capability.reject(error);
} else {
internalRenderTask.capability.resolve();
}
stats.timeEnd('Rendering');
stats.timeEnd('Overall');
};
var internalRenderTask = new InternalRenderTask(complete, params,
this.objs,
this.commonObjs,
intentState.operatorList,
this.pageNumber,
canvasFactory);
internalRenderTask.useRequestAnimationFrame = renderingIntent !== 'print';
if (!intentState.renderTasks) {
intentState.renderTasks = [];
}
intentState.renderTasks.push(internalRenderTask);
var renderTask = internalRenderTask.task;
// Obsolete parameter support
if (params.continueCallback) {
deprecated('render is used with continueCallback parameter');
renderTask.onContinue = params.continueCallback;
}
intentState.displayReadyCapability.promise.then((transparency) => {
if (this.pendingCleanup) {
complete();
return;
}
stats.time('Rendering');
internalRenderTask.initializeGraphics(transparency);
internalRenderTask.operatorListChanged();
}).catch(complete);
return renderTask;
},
/**
* @return {Promise} A promise resolved with an {@link PDFOperatorList}
* object that represents page's operator list.
*/
getOperatorList: function PDFPageProxy_getOperatorList() {
function operatorListChanged() {
if (intentState.operatorList.lastChunk) {
intentState.opListReadCapability.resolve(intentState.operatorList);
var i = intentState.renderTasks.indexOf(opListTask);
if (i >= 0) {
intentState.renderTasks.splice(i, 1);
}
}
}
var renderingIntent = 'oplist';
if (!this.intentStates[renderingIntent]) {
this.intentStates[renderingIntent] = Object.create(null);
}
var intentState = this.intentStates[renderingIntent];
var opListTask;
if (!intentState.opListReadCapability) {
opListTask = {};
opListTask.operatorListChanged = operatorListChanged;
intentState.receivingOperatorList = true;
intentState.opListReadCapability = createPromiseCapability();
intentState.renderTasks = [];
intentState.renderTasks.push(opListTask);
intentState.operatorList = {
fnArray: [],
argsArray: [],
lastChunk: false,
};
this.transport.messageHandler.send('RenderPageRequest', {
pageIndex: this.pageIndex,
intent: renderingIntent,
});
}
return intentState.opListReadCapability.promise;
},
/**
* @param {getTextContentParameters} params - getTextContent parameters.
* @return {ReadableStream} ReadableStream to read textContent chunks.
*/
streamTextContent(params = {}) {
const TEXT_CONTENT_CHUNK_SIZE = 100;