title: Google Appscript Exporting all Sheets as PDF and name it from a specific Cell Value - Save in a specific Folder
body: <p>I'm trying to export all sheets as PDF, get the filename from cell D5 and save them to a specific folder in Google drive, however, I'm getting a bunch of duplicates with the same name as the first sheet. Any suggestions? Also changed DriveApp.getRootFolder(); for getFolderbyName, seems that is not recognizing the actual folder, everything else in the code is working flawlessly.</p>
  <pre><code>
  function savePDFs( optSSId, optSheetId ) {
  
    var ss = (optSSId) ? SpreadsheetApp.openById(optSSId) : SpreadsheetApp.getActiveSpreadsheet();
    
  
    var url = ss.getUrl().replace(/edit$/,'');
  
   
    var parents = DriveApp.getFileById(ss.getId()).getParents();
    if (parents.hasNext()) {
      var folder = parents.next();
    }
    else {
      folder = DriveApp.getFolderbyName('Invoices');
    }
    
  
    var sheets = ss.getSheets();
    
  
    for (var i=0; i&lt;sheets.length; i++) {
      var sheet = sheets[i];
      
  
      if (optSheetId &amp;&amp; optSheetId !== sheet.getSheetId()) continue; 
      
  
      var url_ext = 'export?exportFormat=pdf&amp;format=pdf'   //export as pdf
          + '&amp;gid=' + sheet.getSheetId()   //the sheet's Id
          // following parameters are optional...
          + '&amp;size=letter'      // paper size
          + '&amp;portrait=true'    // orientation, false for landscape
          + '&amp;fitw=true'        // fit to width, false for actual size
          + '&amp;sheetnames=false&amp;printtitle=false&amp;pagenumbers=false'  //hide optional headers and footers
          + '&amp;gridlines=false'  // hide gridlines
          + '&amp;fzr=false';       // do not repeat row headers (frozen rows) on each page
  
      var options = {
        headers: {
          'Authorization': 'Bearer ' +  ScriptApp.getOAuthToken()
        }
      }
  
      var response = UrlFetchApp.fetch(url + url_ext, options);
      
      var ss2= SpreadsheetApp.getActiveSpreadsheet();
      
  var valor = SpreadsheetApp.getActiveSheet().getRange('D5').getValue()
      
      var blob = response.getBlob().setName(valor + '.pdf');
  
  
      folder.createFile(blob);
    }
  }
  
  </code></pre>