Home > Back-end >  Convert multiple URL to individual PDFs
Convert multiple URL to individual PDFs

Time:03-08

Question - I have a Google Sheet with about 200 Google Doc URLS. Is it possible to have a script that will convert the URLS to individual PDF files and save it to my desktop?

I have searched the internet high and low and I cannot find a solution. If anyone has any insight or can point me in the right direction, that would be really helpful.

CodePudding user response:

One solution will be, create a folder inside of Drive, convert the documents to PDFs, and download the folder as a .zip.

function convertDocuments() {
  /* Select the Spreadsheet */
  const SS_ID = "SPREADSHEET_ID"
  const SS = SpreadsheetApp.openById(SS_ID)
  const PDF_MIME = "application/pdf"
  const newFolder = DriveApp.createFolder('PDFs')
  /* Get the links */
  const getLinks = SS.getRange('A2:A').getValues()
  getLinks.forEach((cells)=>{
    const link = cells[0]
    if(link==="") return
    /* Getting the ID from the URL */
    const parseID = link.toString().split("/")[5]
    /* CREATE THE PDF */
    const document = DriveApp.getFileById(parseID).getAs(PDF_MIME).copyBlob()
    /* Inserting the PDF into the file */
    newFolder.createFile(document)
  })
  Logger.log(newFolder.getUrl())
  /* downloadFolder(newFolder.getId()) */
}

The steps are as follows:

  1. Retrieve all links inside the A column
  2. Use DriveApp in order to create a PDF for every link (link needs to be parsed for retrieving the ID)
  3. Place the PDF inside the Drive Folder
  4. From here, you have two possibilities:
    • Use the UI to download the folder
    • Use this function (provided by @Tanaike) to get directly the download link. Inside my script is referenced as downloadFolder
function downloadFolder(folderId) {
  const folder = DriveApp.getFolderById(folderId);
  const files = folder.getFiles();
  let blobs = [];
  while (files.hasNext()) {
    blobs.push(files.next().getBlob());
  }
  const zipBlob = Utilities.zip(blobs, folder.getName()   ".zip");
  const fileId = DriveApp.createFile(zipBlob).getId();
  const url = "https://drive.google.com/uc?export=download&id="   fileId;
  Logger.log(url);
}
Documentation
  • Related