Download protected PDF file from Google Drive

You can download protected PDF file

您需要先安裝使用者腳本管理器擴展,如 TampermonkeyGreasemonkeyViolentmonkey 之後才能安裝該腳本。

You will need to install an extension such as Tampermonkey to install this script.

您需要先安裝使用者腳本管理器擴充功能,如 TampermonkeyViolentmonkey 後才能安裝該腳本。

您需要先安裝使用者腳本管理器擴充功能,如 TampermonkeyUserscripts 後才能安裝該腳本。

你需要先安裝一款使用者腳本管理器擴展,比如 Tampermonkey,才能安裝此腳本

您需要先安裝使用者腳本管理器擴充功能後才能安裝該腳本。

(我已經安裝了使用者腳本管理器,讓我安裝!)

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

(我已經安裝了使用者樣式管理器,讓我安裝!)

// ==UserScript==
// @name         Download protected PDF file from Google Drive
// @namespace    Download protected PDF file
// @description  You can download protected PDF file
// @version      1.1
// @match        https://drive.google.com/*
// @grant        GM_registerMenuCommand
// @require      https://unpkg.com/jspdf@latest/dist/jspdf.umd.min.js
// ==/UserScript==

(function() {
    'use strict';
    function rescale(width, height, fitWidth, fitHeight) {
        let ratio = width / height;
        let fitRatio = fitWidth / fitHeight;
        if (ratio <= fitRatio) {
            return [width, width / fitRatio];
        } else {
            return [height * fitRatio, height];
        }
    }

    function imageToBase64(img) {
        let canvas = document.createElement("canvas");
        let context = canvas.getContext("2d");
        canvas.width = img.naturalWidth;
        canvas.height = img.naturalHeight;
        context.drawImage(img, 0, 0, img.naturalWidth, img.naturalHeight);
        return canvas.toDataURL("image/png", 1.0);
    }

    function downloadPDF() {
        try {
            let jsPDF = window.jspdf.jsPDF;
            let pdf = new jsPDF();
            let pdfWidth = pdf.internal.pageSize.getWidth();
            let pdfHeight = pdf.internal.pageSize.getHeight();
            let elements = document.getElementsByTagName("img");
            for (let img of elements) {
                if (!/^blob:/.test(img.src)) {
                    continue;
                }
                console.log("adding image", img.src);
                let imgData = imageToBase64(img);
                let [newWidth, newHeight] = rescale(pdfWidth, pdfHeight, img.naturalWidth, img.naturalHeight);
                pdf.addImage(imgData, "png", 0, 0, newWidth, newHeight);
                pdf.addPage();
            }
            pdf.deletePage(pdf.internal.getNumberOfPages());
            pdf.save("download.pdf");
        } catch(e) {
            console.log(e);
        }
    }

    GM_registerMenuCommand("Download PDF file", downloadPDF, "d");
})();