google-apps-scriptpdfgoogle-slides

How do I close a presentation created from a template and then make a pdf out of it?


I am creating google slides from google sheets. I've succeeded in creating the slides but now I need to convert them to pdf so I can send them out to different people. From what I read, I am supposed to close the slide presentation before making the pdf. I tried using saveAndClose but I get the error

saveAndClose is not a function

Here is the code.

function generateCerts() {
  var ss = SpreadsheetApp.openById('the spreadsheet');
  var sheet = ss.getSheetByName('Sheet1');
  var data = sheet.getDataRange().getValues();
  var templateId = 'the template';
  var folder = DriveApp.getFolderById('the folder');

  // some other code

  for (var i = 1; i < data.length; i++) {
    var templateCopy = DriveApp.getFileById(templateId).makeCopy(folder);
    var slide = SlidesApp.openById(templateCopy.getId()).getSlides()[0];
    var shapes = slide.getShapes();

    // the slides are created in this loop

    var certificateName = school + "_Certificate";
    templateCopy.setName(certificateName);

    templateCopy.saveAndClose();
    var certBlob = templateCopy.getAs('application/pdf').setName(certificateName + '.pdf');
    folder.createFile(certBlob);
  }
}

I have tried separating them into two functions but what happened was I got several PDF copies of the template I used to create the slides instead of the slides with the data already in them.

Someone please tell me what I did wrong and how am I supposed to do this.


Solution

  • Modification points:

    When these points are reflected in your script, how about the following modification?

    Modified script:

    function generateCerts() {
      var ss = SpreadsheetApp.openById('the spreadsheet');
      var sheet = ss.getSheetByName('Sheet1');
      var data = sheet.getDataRange().getValues();
      var templateId = 'the template';
      var folder = DriveApp.getFolderById('the folder');
      
      // some other code
      
      for (var i = 1; i < data.length; i++) {
        var templateCopy = DriveApp.getFileById(templateId).makeCopy(folder);
        var s = SlidesApp.openById(templateCopy.getId()); // Modified
        var slide = s.getSlides()[0]; // Modified
        var shapes = slide.getShapes();
        
        // the slides are created in this loop
    
        var certificateName = school + "_Certificate";
        templateCopy.setName(certificateName);
    
        s.saveAndClose(); // Modified
        var certBlob = templateCopy.getAs('application/pdf').setName(certificateName + '.pdf');
        folder.createFile(certBlob);
      }
    }
    

    Reference: