Download protected PDF file from Google Drive

You can download protected PDF file

您需要先安装一个扩展,例如 篡改猴Greasemonkey暴力猴,之后才能安装此脚本。

您需要先安装一个扩展,例如 篡改猴暴力猴,之后才能安装此脚本。

您需要先安装一个扩展,例如 篡改猴暴力猴,之后才能安装此脚本。

您需要先安装一个扩展,例如 篡改猴Userscripts ,之后才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 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");
})();