Search code examples
google-sheetsgoogle-apps-scriptpdfgoogle-drive-api

Save each individual sheet in a google spreadsheet as its own PDF on Google Drive with Apps Scripts


I have a spreadsheet with 46 sheets in it. I would like to be able to hide 4 of them and then send the rest to google drive as PDFs. It should not require button clicks to send the files.

I found this out there and modified it to hide sheets prior to export, but it downloads to local drive and requires input, instead of sending to google drive automaticaly.

function PDF() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var allSheets = ss.getSheets();
  hideSheet("test2");
  allSheets.forEach(function(sheet){
    if(!sheet.isSheetHidden()){
      var sheetId = sheet.getSheetId(); 
      var url = "https://docs.google.com/a/mydomain.org/spreadsheets/d/" + ss.getId() + "/export?exportFormat=pdf&gid=" + sheetId + "&access_token=" + ScriptApp.getOAuthToken();
      var str = '<input type="button" value="Download" onClick="location.href=\'' + url + '\'" >';
      var html = HtmlService.createHtmlOutput(str);
    SpreadsheetApp.getUi().showModalDialog(html, "Click the button to download");
    }
  })
}

function hideSheet(sheetName) {
 SpreadsheetApp.getActive().getSheetByName(sheetName).hideSheet();
}

Solution

  • To send the PDFs directly to Google Drive without requiring manual intervention you save the PDFs to Google Drive directly

    function PDF() {
      var ss = SpreadsheetApp.getActiveSpreadsheet();
      var allSheets = ss.getSheets();
      hideSheet("test2");
      allSheets.forEach(function(sheet){
        if(!sheet.isSheetHidden()){
          var sheetId = sheet.getSheetId(); 
          var url = "https://docs.google.com/a/mydomain.org/spreadsheets/d/" + ss.getId() + "/export?exportFormat=pdf&gid=" + sheetId + "&access_token=" + ScriptApp.getOAuthToken();
          
          // Save PDF to Google Drive so you don't have to do it manually later
          var folderSave = DriveApp.getRootFolder(); // make this where you want to save it.
          var blob = UrlFetchApp.fetch(url).getBlob().setName(sheet.getName() + ".pdf");
          // this should make the file 
          folderSave.createFile(blob);
        }
      });
    }
    
    function hideSheet(sheetName) {
     SpreadsheetApp.getActive().getSheetByName(sheetName).hideSheet();
    }