This repository has been archived by the owner on Sep 29, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pdfjs-downloader.js
65 lines (54 loc) · 2.04 KB
/
pdfjs-downloader.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
// ==UserScript==
// @name PDF.js Downloader
// @namespace http://tampermonkey.net/
// @version 0.1
// @description Intercept PDF.js initialization and download the captured PDF file
// @run-at document-start
// @grant none
// ==/UserScript==
(
function() {
'use strict';
function downloadPDF(pdfDocument) {
pdfDocument.getData().then(function(data) {
const blob = new Blob([data], { type: 'application/pdf' });
const url = URL.createObjectURL(blob);
// * Create an anchor element to click and download the blob
const a = document.createElement('a');
a.href = url;
a.download = 'downloaded.pdf'; // * The file name
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
// * Handle the object URL after downloading
URL.revokeObjectURL(url);
});
}
function waitForPDFViewerApplication() {
if (typeof window.PDFViewerApplication !== 'undefined' &&
typeof window.PDFViewerApplication.pdfDocument !== 'undefined' &&
window.PDFViewerApplication.pdfDocument !== null) {
downloadPDF(window.PDFViewerApplication.pdfDocument);
} else {
setTimeout(waitForPDFViewerApplication, 1000); // * Repeat every second
}
}
// * Utilize a MutationObserver to detect loading the document by PDF.js
function observeDocumentLoad() {
const viewerContainer = document.getElementById('viewerContainer');
if (!viewerContainer) return;
const observer = new MutationObserver(function(mutationsList, observer) {
for (const mutation of mutationsList) {
if (mutation.type === 'childList' && window.PDFViewerApplication.pdfDocument) {
observer.disconnect();
downloadPDF(window.PDFViewerApplication.pdfDocument);
}
}
});
observer.observe(viewerContainer, { childList: true, subtree: true });
}
// * Start observing
waitForPDFViewerApplication();
observeDocumentLoad();
}
)();