How to download view only protected PDF from Google Drive (JS code)

The Coding Cat got some document that he could not read on his Android phone or iPad showing only error because of read only mode that the mobile devices could not handle. He needed it on other devices than his PC, so he wrote a little ‘hack’  in JS.

Note 1: It was tested on Opera Browser.

Note 2: It converts pages to jpg images. The Coding Cat thinks it could be done preserving text, but he didn’t have more time for this and jpg solution was sufficient.

Note 3: If you’re getting only part of the document visible, try zooming out your browser and then run the script.

Step by step:

  1. Open the document in Google Docs
  2. Scroll to the bottom of the document, so all the pages are present
  3. Open Developer Tools on separate window and choose the Console tab
  4. Paste the code below (and hit enter)
    let jspdf = document.createElement("script");
    
    jspdf.onload = function () {
    
        let pdf = new jsPDF();
        let elements = document.getElementsByTagName("img");
        for (let i in elements) {
            let img = elements[i];
            console.log("add img ", img);
            if (!/^blob:/.test(img.src)) {
                console.log("invalid src");
                continue;
            }
            let can = document.createElement('canvas');
            let con = can.getContext("2d");
            can.width = img.width;
            can.height = img.height;
            con.drawImage(img, 0, 0);
            let imgData = can.toDataURL("image/jpeg", 1.0);
            pdf.addImage(imgData, 'JPEG', 0, 0);
            pdf.addPage();
        }
    
        pdf.save("download.pdf");
    };
    
    jspdf.src = 'https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.5.3/jspdf.debug.js';
    document.body.appendChild(jspdf);
    
  5. Now the PDF should be downloaded

 

What it does? It iterates trough the document checking for images (Google Drive stores pages as images) then writes it’s contents to a PDF.

Leave a comment if it works for you.