123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116 |
- import { createValidAbsoluteUrl, isPdfFile } from "pdfjs-lib";
- if (typeof PDFJSDev !== "undefined" && !PDFJSDev.test("CHROME || GENERIC")) {
- throw new Error(
- 'Module "pdfjs-web/download_manager" shall not be used ' +
- "outside CHROME and GENERIC builds."
- );
- }
- function download(blobUrl, filename) {
- const a = document.createElement("a");
- if (!a.click) {
- throw new Error('DownloadManager: "a.click()" is not supported.');
- }
- a.href = blobUrl;
- a.target = "_parent";
-
-
- if ("download" in a) {
- a.download = filename;
- }
-
-
- (document.body || document.documentElement).append(a);
- a.click();
- a.remove();
- }
- class DownloadManager {
- #openBlobUrls = new WeakMap();
- downloadUrl(url, filename) {
- if (!createValidAbsoluteUrl(url, "http://example.com")) {
- console.error(`downloadUrl - not a valid URL: ${url}`);
- return;
- }
- download(url + "#pdfjs.action=download", filename);
- }
- downloadData(data, filename, contentType) {
- const blobUrl = URL.createObjectURL(
- new Blob([data], { type: contentType })
- );
- download(blobUrl, filename);
- }
-
- openOrDownloadData(element, data, filename) {
- const isPdfData = isPdfFile(filename);
- const contentType = isPdfData ? "application/pdf" : "";
- if (isPdfData) {
- let blobUrl = this.#openBlobUrls.get(element);
- if (!blobUrl) {
- blobUrl = URL.createObjectURL(new Blob([data], { type: contentType }));
- this.#openBlobUrls.set(element, blobUrl);
- }
- let viewerUrl;
- if (typeof PDFJSDev === "undefined" || PDFJSDev.test("GENERIC")) {
-
- viewerUrl = "?file=" + encodeURIComponent(blobUrl + "#" + filename);
- } else if (PDFJSDev.test("CHROME")) {
-
-
- viewerUrl =
-
- chrome.runtime.getURL("/content/web/viewer.html") +
- "?file=" +
- encodeURIComponent(blobUrl + "#" + filename);
- }
- try {
- window.open(viewerUrl);
- return true;
- } catch (ex) {
- console.error(`openOrDownloadData: ${ex}`);
-
-
- URL.revokeObjectURL(blobUrl);
- this.#openBlobUrls.delete(element);
- }
- }
- this.downloadData(data, filename, contentType);
- return false;
- }
- download(blob, url, filename) {
- const blobUrl = URL.createObjectURL(blob);
- download(blobUrl, filename);
- }
- }
- export { DownloadManager };
|