-
Notifications
You must be signed in to change notification settings - Fork 10k
/
app.js
2861 lines (2585 loc) · 87.3 KB
/
app.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 PDFBug, Stats */
import {
animationStarted,
AutoPrintRegExp,
DEFAULT_SCALE_VALUE,
EventBus,
getPDFFileNameFromURL,
isValidRotation,
isValidScrollMode,
isValidSpreadMode,
MAX_SCALE,
MIN_SCALE,
noContextMenuHandler,
normalizeWheelEventDelta,
parseQueryString,
PresentationModeState,
ProgressBar,
RendererType,
ScrollMode,
SpreadMode,
TextLayerMode,
} from "./ui_utils.js";
import { AppOptions, OptionKind } from "./app_options.js";
import {
build,
createPromiseCapability,
getDocument,
getFilenameFromUrl,
GlobalWorkerOptions,
InvalidPDFException,
LinkTarget,
loadScript,
MissingPDFException,
OPS,
PDFWorker,
PermissionFlag,
shadow,
UnexpectedResponseException,
UNSUPPORTED_FEATURES,
version,
} from "pdfjs-lib";
import { CursorTool, PDFCursorTools } from "./pdf_cursor_tools.js";
import { PDFRenderingQueue, RenderingStates } from "./pdf_rendering_queue.js";
import { PDFSidebar, SidebarView } from "./pdf_sidebar.js";
import { OverlayManager } from "./overlay_manager.js";
import { PasswordPrompt } from "./password_prompt.js";
import { PDFAttachmentViewer } from "./pdf_attachment_viewer.js";
import { PDFDocumentProperties } from "./pdf_document_properties.js";
import { PDFFindBar } from "./pdf_find_bar.js";
import { PDFFindController } from "./pdf_find_controller.js";
import { PDFHistory } from "./pdf_history.js";
import { PDFLinkService } from "./pdf_link_service.js";
import { PDFOutlineViewer } from "./pdf_outline_viewer.js";
import { PDFPresentationMode } from "./pdf_presentation_mode.js";
import { PDFSidebarResizer } from "./pdf_sidebar_resizer.js";
import { PDFThumbnailViewer } from "./pdf_thumbnail_viewer.js";
import { PDFViewer } from "./pdf_viewer.js";
import { SecondaryToolbar } from "./secondary_toolbar.js";
import { Toolbar } from "./toolbar.js";
import { ViewHistory } from "./view_history.js";
const DEFAULT_SCALE_DELTA = 1.1;
const DISABLE_AUTO_FETCH_LOADING_BAR_TIMEOUT = 5000; // ms
const FORCE_PAGES_LOADED_TIMEOUT = 10000; // ms
const WHEEL_ZOOM_DISABLED_TIMEOUT = 1000; // ms
const ENABLE_PERMISSIONS_CLASS = "enablePermissions";
const ViewOnLoad = {
UNKNOWN: -1,
PREVIOUS: 0, // Default value.
INITIAL: 1,
};
class DefaultExternalServices {
constructor() {
throw new Error("Cannot initialize DefaultExternalServices.");
}
static updateFindControlState(data) {}
static updateFindMatchesCount(data) {}
static initPassiveLoading(callbacks) {}
static fallback(data, callback) {}
static reportTelemetry(data) {}
static createDownloadManager(options) {
throw new Error("Not implemented: createDownloadManager");
}
static createPreferences() {
throw new Error("Not implemented: createPreferences");
}
static createL10n(options) {
throw new Error("Not implemented: createL10n");
}
static get supportsIntegratedFind() {
return shadow(this, "supportsIntegratedFind", false);
}
static get supportsDocumentFonts() {
return shadow(this, "supportsDocumentFonts", true);
}
static get supportedMouseWheelZoomModifierKeys() {
return shadow(this, "supportedMouseWheelZoomModifierKeys", {
ctrlKey: true,
metaKey: true,
});
}
static get isInAutomation() {
return shadow(this, "isInAutomation", false);
}
}
const PDFViewerApplication = {
initialBookmark: document.location.hash.substring(1),
_initializedCapability: createPromiseCapability(),
fellback: false,
appConfig: null,
pdfDocument: null,
pdfLoadingTask: null,
printService: null,
/** @type {PDFViewer} */
pdfViewer: null,
/** @type {PDFThumbnailViewer} */
pdfThumbnailViewer: null,
/** @type {PDFRenderingQueue} */
pdfRenderingQueue: null,
/** @type {PDFPresentationMode} */
pdfPresentationMode: null,
/** @type {PDFDocumentProperties} */
pdfDocumentProperties: null,
/** @type {PDFLinkService} */
pdfLinkService: null,
/** @type {PDFHistory} */
pdfHistory: null,
/** @type {PDFSidebar} */
pdfSidebar: null,
/** @type {PDFSidebarResizer} */
pdfSidebarResizer: null,
/** @type {PDFOutlineViewer} */
pdfOutlineViewer: null,
/** @type {PDFAttachmentViewer} */
pdfAttachmentViewer: null,
/** @type {PDFCursorTools} */
pdfCursorTools: null,
/** @type {ViewHistory} */
store: null,
/** @type {DownloadManager} */
downloadManager: null,
/** @type {OverlayManager} */
overlayManager: null,
/** @type {Preferences} */
preferences: null,
/** @type {Toolbar} */
toolbar: null,
/** @type {SecondaryToolbar} */
secondaryToolbar: null,
/** @type {EventBus} */
eventBus: null,
/** @type {IL10n} */
l10n: null,
isInitialViewSet: false,
downloadComplete: false,
isViewerEmbedded: window.parent !== window,
url: "",
baseUrl: "",
externalServices: DefaultExternalServices,
_boundEvents: {},
contentDispositionFilename: null,
// Called once when the document is loaded.
async initialize(appConfig) {
this.preferences = this.externalServices.createPreferences();
this.appConfig = appConfig;
await this._readPreferences();
await this._parseHashParameters();
await this._initializeL10n();
if (
this.isViewerEmbedded &&
AppOptions.get("externalLinkTarget") === LinkTarget.NONE
) {
// Prevent external links from "replacing" the viewer,
// when it's embedded in e.g. an <iframe> or an <object>.
AppOptions.set("externalLinkTarget", LinkTarget.TOP);
}
await this._initializeViewerComponents();
// Bind the various event handlers *after* the viewer has been
// initialized, to prevent errors if an event arrives too soon.
this.bindEvents();
this.bindWindowEvents();
// We can start UI localization now.
const appContainer = appConfig.appContainer || document.documentElement;
this.l10n.translate(appContainer).then(() => {
// Dispatch the 'localized' event on the `eventBus` once the viewer
// has been fully initialized and translated.
this.eventBus.dispatch("localized", { source: this });
});
this._initializedCapability.resolve();
},
/**
* @private
*/
async _readPreferences() {
if (AppOptions.get("disablePreferences") === true) {
// Give custom implementations of the default viewer a simpler way to
// opt-out of having the `Preferences` override existing `AppOptions`.
return;
}
try {
const prefs = await this.preferences.getAll();
for (const name in prefs) {
AppOptions.set(name, prefs[name]);
}
} catch (reason) {
console.error(`_readPreferences: "${reason.message}".`);
}
},
/**
* Potentially parse special debugging flags in the hash section of the URL.
* @private
*/
async _parseHashParameters() {
if (
typeof PDFJSDev !== "undefined" &&
PDFJSDev.test("PRODUCTION") &&
!AppOptions.get("pdfBugEnabled")
) {
return undefined;
}
const hash = document.location.hash.substring(1);
if (!hash) {
return undefined;
}
const hashParams = parseQueryString(hash),
waitOn = [];
if ("disableworker" in hashParams && hashParams.disableworker === "true") {
waitOn.push(loadFakeWorker());
}
if ("disablerange" in hashParams) {
AppOptions.set("disableRange", hashParams.disablerange === "true");
}
if ("disablestream" in hashParams) {
AppOptions.set("disableStream", hashParams.disablestream === "true");
}
if ("disableautofetch" in hashParams) {
AppOptions.set(
"disableAutoFetch",
hashParams.disableautofetch === "true"
);
}
if ("disablefontface" in hashParams) {
AppOptions.set("disableFontFace", hashParams.disablefontface === "true");
}
if ("disablehistory" in hashParams) {
AppOptions.set("disableHistory", hashParams.disablehistory === "true");
}
if ("webgl" in hashParams) {
AppOptions.set("enableWebGL", hashParams.webgl === "true");
}
if ("verbosity" in hashParams) {
AppOptions.set("verbosity", hashParams.verbosity | 0);
}
if ("textlayer" in hashParams) {
switch (hashParams.textlayer) {
case "off":
AppOptions.set("textLayerMode", TextLayerMode.DISABLE);
break;
case "visible":
case "shadow":
case "hover":
const viewer = this.appConfig.viewerContainer;
viewer.classList.add("textLayer-" + hashParams.textlayer);
break;
}
}
if ("pdfbug" in hashParams) {
AppOptions.set("pdfBug", true);
AppOptions.set("fontExtraProperties", true);
const enabled = hashParams.pdfbug.split(",");
waitOn.push(loadAndEnablePDFBug(enabled));
}
// It is not possible to change locale for the (various) extension builds.
if (
(typeof PDFJSDev === "undefined" ||
PDFJSDev.test("!PRODUCTION || GENERIC")) &&
"locale" in hashParams
) {
AppOptions.set("locale", hashParams.locale);
}
return Promise.all(waitOn).catch(reason => {
console.error(`_parseHashParameters: "${reason.message}".`);
});
},
/**
* @private
*/
async _initializeL10n() {
this.l10n = this.externalServices.createL10n({
locale: AppOptions.get("locale"),
});
const dir = await this.l10n.getDirection();
document.getElementsByTagName("html")[0].dir = dir;
},
/**
* @private
*/
async _initializeViewerComponents() {
const appConfig = this.appConfig;
const eventBus =
appConfig.eventBus ||
new EventBus({ isInAutomation: this.externalServices.isInAutomation });
this.eventBus = eventBus;
this.overlayManager = new OverlayManager();
const pdfRenderingQueue = new PDFRenderingQueue();
pdfRenderingQueue.onIdle = this.cleanup.bind(this);
this.pdfRenderingQueue = pdfRenderingQueue;
const pdfLinkService = new PDFLinkService({
eventBus,
externalLinkTarget: AppOptions.get("externalLinkTarget"),
externalLinkRel: AppOptions.get("externalLinkRel"),
ignoreDestinationZoom: AppOptions.get("ignoreDestinationZoom"),
});
this.pdfLinkService = pdfLinkService;
const downloadManager = this.externalServices.createDownloadManager({
disableCreateObjectURL: AppOptions.get("disableCreateObjectURL"),
});
this.downloadManager = downloadManager;
const findController = new PDFFindController({
linkService: pdfLinkService,
eventBus,
});
this.findController = findController;
const container = appConfig.mainContainer;
const viewer = appConfig.viewerContainer;
this.pdfViewer = new PDFViewer({
container,
viewer,
eventBus,
renderingQueue: pdfRenderingQueue,
linkService: pdfLinkService,
downloadManager,
findController,
renderer: AppOptions.get("renderer"),
enableWebGL: AppOptions.get("enableWebGL"),
l10n: this.l10n,
textLayerMode: AppOptions.get("textLayerMode"),
imageResourcesPath: AppOptions.get("imageResourcesPath"),
renderInteractiveForms: AppOptions.get("renderInteractiveForms"),
enablePrintAutoRotate: AppOptions.get("enablePrintAutoRotate"),
useOnlyCssZoom: AppOptions.get("useOnlyCssZoom"),
maxCanvasPixels: AppOptions.get("maxCanvasPixels"),
});
pdfRenderingQueue.setViewer(this.pdfViewer);
pdfLinkService.setViewer(this.pdfViewer);
this.pdfThumbnailViewer = new PDFThumbnailViewer({
container: appConfig.sidebar.thumbnailView,
renderingQueue: pdfRenderingQueue,
linkService: pdfLinkService,
l10n: this.l10n,
});
pdfRenderingQueue.setThumbnailViewer(this.pdfThumbnailViewer);
this.pdfHistory = new PDFHistory({
linkService: pdfLinkService,
eventBus,
});
pdfLinkService.setHistory(this.pdfHistory);
if (!this.supportsIntegratedFind) {
this.findBar = new PDFFindBar(appConfig.findBar, eventBus, this.l10n);
}
this.pdfDocumentProperties = new PDFDocumentProperties(
appConfig.documentProperties,
this.overlayManager,
eventBus,
this.l10n
);
this.pdfCursorTools = new PDFCursorTools({
container,
eventBus,
cursorToolOnLoad: AppOptions.get("cursorToolOnLoad"),
});
this.toolbar = new Toolbar(appConfig.toolbar, eventBus, this.l10n);
this.secondaryToolbar = new SecondaryToolbar(
appConfig.secondaryToolbar,
container,
eventBus
);
if (this.supportsFullscreen) {
this.pdfPresentationMode = new PDFPresentationMode({
container,
pdfViewer: this.pdfViewer,
eventBus,
contextMenuItems: appConfig.fullscreen,
});
}
this.passwordPrompt = new PasswordPrompt(
appConfig.passwordOverlay,
this.overlayManager,
this.l10n
);
this.pdfOutlineViewer = new PDFOutlineViewer({
container: appConfig.sidebar.outlineView,
eventBus,
linkService: pdfLinkService,
});
this.pdfAttachmentViewer = new PDFAttachmentViewer({
container: appConfig.sidebar.attachmentsView,
eventBus,
downloadManager,
});
this.pdfSidebar = new PDFSidebar({
elements: appConfig.sidebar,
pdfViewer: this.pdfViewer,
pdfThumbnailViewer: this.pdfThumbnailViewer,
eventBus,
l10n: this.l10n,
});
this.pdfSidebar.onToggled = this.forceRendering.bind(this);
this.pdfSidebarResizer = new PDFSidebarResizer(
appConfig.sidebarResizer,
eventBus,
this.l10n
);
},
run(config) {
this.initialize(config).then(webViewerInitialized);
},
get initialized() {
return this._initializedCapability.settled;
},
get initializedPromise() {
return this._initializedCapability.promise;
},
zoomIn(ticks) {
if (this.pdfViewer.isInPresentationMode) {
return;
}
let newScale = this.pdfViewer.currentScale;
do {
newScale = (newScale * DEFAULT_SCALE_DELTA).toFixed(2);
newScale = Math.ceil(newScale * 10) / 10;
newScale = Math.min(MAX_SCALE, newScale);
} while (--ticks > 0 && newScale < MAX_SCALE);
this.pdfViewer.currentScaleValue = newScale;
},
zoomOut(ticks) {
if (this.pdfViewer.isInPresentationMode) {
return;
}
let newScale = this.pdfViewer.currentScale;
do {
newScale = (newScale / DEFAULT_SCALE_DELTA).toFixed(2);
newScale = Math.floor(newScale * 10) / 10;
newScale = Math.max(MIN_SCALE, newScale);
} while (--ticks > 0 && newScale > MIN_SCALE);
this.pdfViewer.currentScaleValue = newScale;
},
zoomReset() {
if (this.pdfViewer.isInPresentationMode) {
return;
}
this.pdfViewer.currentScaleValue = DEFAULT_SCALE_VALUE;
},
get pagesCount() {
return this.pdfDocument ? this.pdfDocument.numPages : 0;
},
set page(val) {
this.pdfViewer.currentPageNumber = val;
},
get page() {
return this.pdfViewer.currentPageNumber;
},
get printing() {
return !!this.printService;
},
get supportsPrinting() {
return PDFPrintServiceFactory.instance.supportsPrinting;
},
get supportsFullscreen() {
let support;
if (typeof PDFJSDev !== "undefined" && PDFJSDev.test("MOZCENTRAL")) {
support =
document.fullscreenEnabled === true ||
document.mozFullScreenEnabled === true;
} else {
const doc = document.documentElement;
support = !!(
doc.requestFullscreen ||
doc.mozRequestFullScreen ||
doc.webkitRequestFullScreen ||
doc.msRequestFullscreen
);
if (
document.fullscreenEnabled === false ||
document.mozFullScreenEnabled === false ||
document.webkitFullscreenEnabled === false ||
document.msFullscreenEnabled === false
) {
support = false;
}
}
return shadow(this, "supportsFullscreen", support);
},
get supportsIntegratedFind() {
return this.externalServices.supportsIntegratedFind;
},
get supportsDocumentFonts() {
return this.externalServices.supportsDocumentFonts;
},
get loadingBar() {
const bar = new ProgressBar("#loadingBar");
return shadow(this, "loadingBar", bar);
},
get supportedMouseWheelZoomModifierKeys() {
return this.externalServices.supportedMouseWheelZoomModifierKeys;
},
initPassiveLoading() {
if (
typeof PDFJSDev === "undefined" ||
!PDFJSDev.test("MOZCENTRAL || CHROME")
) {
throw new Error("Not implemented: initPassiveLoading");
}
this.externalServices.initPassiveLoading({
onOpenWithTransport(url, length, transport) {
PDFViewerApplication.open(url, { length, range: transport });
},
onOpenWithData(data) {
PDFViewerApplication.open(data);
},
onOpenWithURL(url, length, originalUrl) {
let file = url,
args = null;
if (length !== undefined) {
args = { length };
}
if (originalUrl !== undefined) {
file = { url, originalUrl };
}
PDFViewerApplication.open(file, args);
},
onError(err) {
PDFViewerApplication.l10n
.get(
"loading_error",
null,
"An error occurred while loading the PDF."
)
.then(msg => {
PDFViewerApplication.error(msg, err);
});
},
onProgress(loaded, total) {
PDFViewerApplication.progress(loaded / total);
},
});
},
setTitleUsingUrl(url = "") {
this.url = url;
this.baseUrl = url.split("#")[0];
let title = getPDFFileNameFromURL(url, "");
if (!title) {
try {
title = decodeURIComponent(getFilenameFromUrl(url)) || url;
} catch (ex) {
// decodeURIComponent may throw URIError,
// fall back to using the unprocessed url in that case
title = url;
}
}
this.setTitle(title);
},
setTitle(title) {
if (this.isViewerEmbedded) {
// Embedded PDF viewers should not be changing their parent page's title.
return;
}
document.title = title;
},
/**
* Closes opened PDF document.
* @returns {Promise} - Returns the promise, which is resolved when all
* destruction is completed.
*/
async close() {
const errorWrapper = this.appConfig.errorWrapper.container;
errorWrapper.setAttribute("hidden", "true");
if (!this.pdfLoadingTask) {
return undefined;
}
const promise = this.pdfLoadingTask.destroy();
this.pdfLoadingTask = null;
if (this.pdfDocument) {
this.pdfDocument = null;
this.pdfThumbnailViewer.setDocument(null);
this.pdfViewer.setDocument(null);
this.pdfLinkService.setDocument(null);
this.pdfDocumentProperties.setDocument(null);
}
webViewerResetPermissions();
this.store = null;
this.isInitialViewSet = false;
this.downloadComplete = false;
this.url = "";
this.baseUrl = "";
this.contentDispositionFilename = null;
this.pdfSidebar.reset();
this.pdfOutlineViewer.reset();
this.pdfAttachmentViewer.reset();
if (this.pdfHistory) {
this.pdfHistory.reset();
}
if (this.findBar) {
this.findBar.reset();
}
this.toolbar.reset();
this.secondaryToolbar.reset();
if (typeof PDFBug !== "undefined") {
PDFBug.cleanup();
}
return promise;
},
/**
* Opens PDF document specified by URL or array with additional arguments.
* @param {string|TypedArray|ArrayBuffer} file - PDF location or binary data.
* @param {Object} [args] - Additional arguments for the getDocument call,
* e.g. HTTP headers ('httpHeaders') or alternative
* data transport ('range').
* @returns {Promise} - Returns the promise, which is resolved when document
* is opened.
*/
async open(file, args) {
if (this.pdfLoadingTask) {
// We need to destroy already opened document.
await this.close();
}
// Set the necessary global worker parameters, using the available options.
const workerParameters = AppOptions.getAll(OptionKind.WORKER);
for (const key in workerParameters) {
GlobalWorkerOptions[key] = workerParameters[key];
}
const parameters = Object.create(null);
if (typeof file === "string") {
// URL
this.setTitleUsingUrl(file);
parameters.url = file;
} else if (file && "byteLength" in file) {
// ArrayBuffer
parameters.data = file;
} else if (file.url && file.originalUrl) {
this.setTitleUsingUrl(file.originalUrl);
parameters.url = file.url;
}
// Set the necessary API parameters, using the available options.
const apiParameters = AppOptions.getAll(OptionKind.API);
for (const key in apiParameters) {
let value = apiParameters[key];
if (key === "docBaseUrl" && !value) {
if (typeof PDFJSDev === "undefined" || !PDFJSDev.test("PRODUCTION")) {
value = document.URL.split("#")[0];
} else if (PDFJSDev.test("MOZCENTRAL || CHROME")) {
value = this.baseUrl;
}
}
parameters[key] = value;
}
if (args) {
for (const key in args) {
const value = args[key];
if (key === "length") {
this.pdfDocumentProperties.setFileSize(value);
}
parameters[key] = value;
}
}
const loadingTask = getDocument(parameters);
this.pdfLoadingTask = loadingTask;
loadingTask.onPassword = (updateCallback, reason) => {
this.pdfLinkService.externalLinkEnabled = false;
this.passwordPrompt.setUpdateCallback(updateCallback, reason);
this.passwordPrompt.open();
};
loadingTask.onProgress = ({ loaded, total }) => {
this.progress(loaded / total);
};
// Listen for unsupported features to trigger the fallback UI.
loadingTask.onUnsupportedFeature = this.fallback.bind(this);
return loadingTask.promise.then(
pdfDocument => {
this.load(pdfDocument);
},
exception => {
if (loadingTask !== this.pdfLoadingTask) {
return undefined; // Ignore errors for previously opened PDF files.
}
const message = exception && exception.message;
let loadingErrorMessage;
if (exception instanceof InvalidPDFException) {
// change error message also for other builds
loadingErrorMessage = this.l10n.get(
"invalid_file_error",
null,
"Invalid or corrupted PDF file."
);
} else if (exception instanceof MissingPDFException) {
// special message for missing PDF's
loadingErrorMessage = this.l10n.get(
"missing_file_error",
null,
"Missing PDF file."
);
} else if (exception instanceof UnexpectedResponseException) {
loadingErrorMessage = this.l10n.get(
"unexpected_response_error",
null,
"Unexpected server response."
);
} else {
loadingErrorMessage = this.l10n.get(
"loading_error",
null,
"An error occurred while loading the PDF."
);
}
return loadingErrorMessage.then(msg => {
this.error(msg, { message });
throw new Error(msg);
});
}
);
},
download() {
function downloadByUrl() {
downloadManager.downloadUrl(url, filename);
}
const url = this.baseUrl;
// Use this.url instead of this.baseUrl to perform filename detection based
// on the reference fragment as ultimate fallback if needed.
const filename =
this.contentDispositionFilename || getPDFFileNameFromURL(this.url);
const downloadManager = this.downloadManager;
downloadManager.onerror = err => {
// This error won't really be helpful because it's likely the
// fallback won't work either (or is already open).
this.error(`PDF failed to download: ${err}`);
};
// When the PDF document isn't ready, or the PDF file is still downloading,
// simply download using the URL.
if (!this.pdfDocument || !this.downloadComplete) {
downloadByUrl();
return;
}
this.pdfDocument
.getData()
.then(function (data) {
const blob = new Blob([data], { type: "application/pdf" });
downloadManager.download(blob, url, filename);
})
.catch(downloadByUrl); // Error occurred, try downloading with the URL.
},
fallback(featureId) {
if (
typeof PDFJSDev === "undefined" ||
PDFJSDev.test("MOZCENTRAL || GENERIC")
) {
// Only trigger the fallback once so we don't spam the user with messages
// for one PDF.
if (this.fellback) {
return;
}
this.fellback = true;
this.externalServices.fallback(
{
featureId,
url: this.baseUrl,
},
function response(download) {
if (!download) {
return;
}
PDFViewerApplication.download();
}
);
}
},
/**
* Show the error box.
* @param {string} message - A message that is human readable.
* @param {Object} [moreInfo] - Further information about the error that is
* more technical. Should have a 'message' and
* optionally a 'stack' property.
*/
error(message, moreInfo) {
const moreInfoText = [
this.l10n.get(
"error_version_info",
{ version: version || "?", build: build || "?" },
"PDF.js v{{version}} (build: {{build}})"
),
];
if (moreInfo) {
moreInfoText.push(
this.l10n.get(
"error_message",
{ message: moreInfo.message },
"Message: {{message}}"
)
);
if (moreInfo.stack) {
moreInfoText.push(
this.l10n.get(
"error_stack",
{ stack: moreInfo.stack },
"Stack: {{stack}}"
)
);
} else {
if (moreInfo.filename) {
moreInfoText.push(
this.l10n.get(
"error_file",
{ file: moreInfo.filename },
"File: {{file}}"
)
);
}
if (moreInfo.lineNumber) {
moreInfoText.push(
this.l10n.get(
"error_line",
{ line: moreInfo.lineNumber },
"Line: {{line}}"
)
);
}
}
}
if (typeof PDFJSDev === "undefined" || !PDFJSDev.test("MOZCENTRAL")) {
const errorWrapperConfig = this.appConfig.errorWrapper;
const errorWrapper = errorWrapperConfig.container;
errorWrapper.removeAttribute("hidden");
const errorMessage = errorWrapperConfig.errorMessage;
errorMessage.textContent = message;
const closeButton = errorWrapperConfig.closeButton;
closeButton.onclick = function () {
errorWrapper.setAttribute("hidden", "true");
};
const errorMoreInfo = errorWrapperConfig.errorMoreInfo;
const moreInfoButton = errorWrapperConfig.moreInfoButton;
const lessInfoButton = errorWrapperConfig.lessInfoButton;
moreInfoButton.onclick = function () {
errorMoreInfo.removeAttribute("hidden");
moreInfoButton.setAttribute("hidden", "true");
lessInfoButton.removeAttribute("hidden");
errorMoreInfo.style.height = errorMoreInfo.scrollHeight + "px";
};
lessInfoButton.onclick = function () {
errorMoreInfo.setAttribute("hidden", "true");
moreInfoButton.removeAttribute("hidden");
lessInfoButton.setAttribute("hidden", "true");
};
moreInfoButton.oncontextmenu = noContextMenuHandler;
lessInfoButton.oncontextmenu = noContextMenuHandler;
closeButton.oncontextmenu = noContextMenuHandler;
moreInfoButton.removeAttribute("hidden");
lessInfoButton.setAttribute("hidden", "true");
Promise.all(moreInfoText).then(parts => {
errorMoreInfo.value = parts.join("\n");
});
} else {
Promise.all(moreInfoText).then(parts => {
console.error(message + "\n" + parts.join("\n"));
});
this.fallback();
}
},
progress(level) {
if (this.downloadComplete) {
// Don't accidentally show the loading bar again when the entire file has
// already been fetched (only an issue when disableAutoFetch is enabled).
return;
}
const percent = Math.round(level * 100);
// When we transition from full request to range requests, it's possible
// that we discard some of the loaded data. This can cause the loading
// bar to move backwards. So prevent this by only updating the bar if it
// increases.
if (percent > this.loadingBar.percent || isNaN(percent)) {
this.loadingBar.percent = percent;
// When disableAutoFetch is enabled, it's not uncommon for the entire file
// to never be fetched (depends on e.g. the file structure). In this case
// the loading bar will not be completely filled, nor will it be hidden.
// To prevent displaying a partially filled loading bar permanently, we
// hide it when no data has been loaded during a certain amount of time.
const disableAutoFetch = this.pdfDocument