UNPKG

2.81 kBJavaScriptView Raw
1/**
2 * @licstart The following is the entire license notice for the
3 * JavaScript code in this page
4 *
5 * Copyright 2022 Mozilla Foundation
6 *
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 *
19 * @licend The above is the entire license notice for the
20 * JavaScript code in this page
21 */
22"use strict";
23
24Object.defineProperty(exports, "__esModule", {
25 value: true
26});
27exports.DownloadManager = void 0;
28
29var _pdf = require("../pdf");
30
31;
32
33function download(blobUrl, filename) {
34 const a = document.createElement("a");
35
36 if (!a.click) {
37 throw new Error('DownloadManager: "a.click()" is not supported.');
38 }
39
40 a.href = blobUrl;
41 a.target = "_parent";
42
43 if ("download" in a) {
44 a.download = filename;
45 }
46
47 (document.body || document.documentElement).append(a);
48 a.click();
49 a.remove();
50}
51
52class DownloadManager {
53 constructor() {
54 this._openBlobUrls = new WeakMap();
55 }
56
57 downloadUrl(url, filename) {
58 if (!(0, _pdf.createValidAbsoluteUrl)(url, "http://example.com")) {
59 console.error(`downloadUrl - not a valid URL: ${url}`);
60 return;
61 }
62
63 download(url + "#pdfjs.action=download", filename);
64 }
65
66 downloadData(data, filename, contentType) {
67 const blobUrl = URL.createObjectURL(new Blob([data], {
68 type: contentType
69 }));
70 download(blobUrl, filename);
71 }
72
73 openOrDownloadData(element, data, filename) {
74 const isPdfData = (0, _pdf.isPdfFile)(filename);
75 const contentType = isPdfData ? "application/pdf" : "";
76
77 if (isPdfData) {
78 let blobUrl = this._openBlobUrls.get(element);
79
80 if (!blobUrl) {
81 blobUrl = URL.createObjectURL(new Blob([data], {
82 type: contentType
83 }));
84
85 this._openBlobUrls.set(element, blobUrl);
86 }
87
88 let viewerUrl;
89 viewerUrl = "?file=" + encodeURIComponent(blobUrl + "#" + filename);
90
91 try {
92 window.open(viewerUrl);
93 return true;
94 } catch (ex) {
95 console.error(`openOrDownloadData: ${ex}`);
96 URL.revokeObjectURL(blobUrl);
97
98 this._openBlobUrls.delete(element);
99 }
100 }
101
102 this.downloadData(data, filename, contentType);
103 return false;
104 }
105
106 download(blob, url, filename) {
107 const blobUrl = URL.createObjectURL(blob);
108 download(blobUrl, filename);
109 }
110
111}
112
113exports.DownloadManager = DownloadManager;
\No newline at end of file