Created
February 28, 2023 22:13
-
-
Save RobinDeBaets/994a76fd2a7fda20438d49e938f0a943 to your computer and use it in GitHub Desktop.
This script allows you to download view-only PDF's on Google Drive. Simply open the document, scroll through it until all pages are loaded and then execute this script in your browser console. This script has some improvements compared to other scripts and avoids blur on high-resolution images.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let pdfScript = document.createElement("script"); | |
function rescale(width, height, fitWidth, fitHeight) { | |
let ratio = width / height; | |
let fitRatio = fitWidth / fitHeight; | |
if (ratio <= fitRatio) { | |
// Dimensions to fit are wider, fix the width | |
return [width, width / fitRatio]; | |
} else { | |
// Dimensions to fit are taller, fix the height | |
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); | |
} | |
pdfScript.onload = function () { | |
try { | |
let jsPDF = window.jspdf.jsPDF; | |
let pdf = new jsPDF(); | |
let pdfWidth = pdf.internal.pageSize.getWidth(); | |
let pdfHeight = pdf.internal.pageSize.getHeight(); | |
let pdfRatio = pdfWidth / pdfHeight; | |
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); | |
} | |
}; | |
pdfScript.src = "https://unpkg.com/jspdf@latest/dist/jspdf.umd.min.js"; | |
document.body.appendChild(pdfScript); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I think this script might be outdated with some new security permissions. You have to add a trusted script url assignment in order for your scripts url to be trusted. Some browsers might not support this struct of trusted script url; however, chrome does and this code I have pasted below is for chrome.