Search code examples
google-apps-scriptweb-applications

Random ‘Limit’ of times you can Export a Spreadsheet as PDF


[Solved] As @ziganotschka suggested - Adding a try and catch statement with an experiential sleep time when the code fails.

I have a simple script that modifies a Spreadsheet then ‘exports’ it as a PDF then modifies the same sheet again and exports once again, Depending on how many times it needs to loop.

So I Have 46 queries queued when it runs sometimes it exports 4 and sometimes it exports 8 sometimes more, sometimes less.

Although nothing has changed.

I’ve tried adding Utilities.sleep(1000); and upward to 5000 once again sometimes helped and sometimes hindered.

Is there some kind of limitation placed on exporting to PDF that I am unaware of?

Am I doing something wrong?

Error Occurs on var docurl = UrlFetchApp.fetch(theurl, { headers: { 'Authorization': 'Bearer ' + token, muteHttpExceptions: true,} });

Uncaught at generatePdf (Code:531) (File Name) at userClicked (Code:299) (File Name)

function doGet(e){

  return HtmlService.createHtmlOutputFromFile("page");

};

The Html Page has a button and fields that pass over when the button is clicked

function userClicked(userInfo){

//Start the main Loop for each new pdf to be made 

//Sheet modification

//in an attempt at making the loop run more times
    var sleepDuration = 0; 
           if (loopI >= 6) {
             sleepDuration = 1500;
       }

       Utilities.sleep(sleepDuration);

       if (typeof subFolderExist == 'undefined') {
        subFolderExist = generatePdf(sheetid, Title[1], varName);
       } else {
         //Sub Folder Exists -  do nothing.
         // varTrash is only there to call the function and isn't used 
//anywhere else 
         var varTrash = generatePdf(sheetid, Title[1], varName, 
  subFolderExist);
       }
}





function generatePdf(sourceSpreadsheet, sheetName, Name, varifSubFolderExist) {


  var sourceSpreadsheetId = sourceSpreadsheet.getId();
  var ss = SpreadsheetApp.openById(sourceSpreadsheetId);
  var nameoffile = ss.getSheetByName('W1-D1').getRange(1, 1).getValue();  
      var theurl = 'https://docs.google.com/spreadsheets/d/'  

      + '' + sourceSpreadsheetId + '' //the file ID
      + '/export?exportFormat=pdf&format=pdf'
      + '&size=LETTER'
      + '&portrait=true'
      + '&fitw=true'       
      + '&top_margin=0.50'              
      + '&bottom_margin=0.50'          
      + '&left_margin=0.50'             
      + '&right_margin=0.50'           
      + '&sheetnames=false&printtitle=false'
      + '&pagenum=false'
      + '&gridlines=false'
      + '&fzr=FALSE'      
      + '&gid='
      + '1304619048';  




    // Get folder containing spreadsheet to save pdf in.
    var parents = DriveApp.getFileById(sourceSpreadsheetId).getParents();
    if (parents.hasNext()) {
      var folder = parents.next();
    }
    else {
      folder = DriveApp.getRootFolder();
    }



     //Create SubFolder
     var subFolder;
      if(typeof varifSubFolderExist === "undefined") {


     var today = new Date();
     var date = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate();
     var hours = today.getHours();
     var timePeriod;

         if (hours > 12) {
          hours = (hours - 12);
           timePeriod = "PM";
          }

       timePeriod = "AM";

       var time = hours + ":" + today.getMinutes() + ":" + today.getSeconds();
       var dateTime = date+' '+time + timePeriod;

       // Set the output folder name.
       var folderName = "PDFs - [" + dateTime + "]";


       subFolder = folder.createFolder(folderName);
       // Add Unique String
    } else {
       subFolder = DriveApp.getFolderById(varifSubFolderExist[0]);
   }
  //End Create SubFolder


      var token = ScriptApp.getOAuthToken();

      var docurl = UrlFetchApp.fetch(theurl, { headers: { 'Authorization': 'Bearer ' +  token, muteHttpExceptions: true,} });
      //var fileid = DriveApp.createFile(docurl.getBlob()).setName(nameoffile+ '.pdf').getId();
      var fileid = subFolder.createFile(docurl.getBlob()).setName(sheetName + " " + Name + '.pdf').getId();

      var pdf = docurl.getBlob().setName(nameoffile + '.pdf');
      var filetodel = DriveApp.getFileById(fileid);

  return [subFolder.getId(), folderName];

}

Solution

  • As @ziganotschka suggested - Adding a try and catch statement with an exponentially increasing sleeping when the code fails worked perfectly.