Reputation: 81
When the saved PDF files are viewed, the name does not change to the respective name from the sheet. Any idea why? I think this has something to do with async/await stuff.
The name and the usn taken from a spreadsheet {{name}} to be replaced by actual name but in the PDF generated it is not getting displayed. Please help
function myFunction() {
var dataspreadsheet = "https://docs.google.com/spreadsheets/d/XXXXX/edit"
var slide = SlidesApp.getActivePresentation();
var ss = SpreadsheetApp.openByUrl(dataspreadsheet)
var sheet = ss.getSheetByName('Sheet1')
var startRow = 2;
var numRows = 3;
var dataRange = sheet.getRange(startRow, 1, numRows, 3);
var data = dataRange.getValues();
console.log(data);
for (var i in data) {
var slides = slide.getSlides();
var template = slides[0]
var row = data[i];
var name = row[0]; // First column
var usn = row[1]; //Second column
template.replaceAllText("{{name}}",name);
var options =
{
"contentType" : "application/pdf",
"muteHttpExceptions": false
};
var presentationCopyId = 'YYY'
var blob = DriveApp.getFileById(presentationCopyId).getBlob();
var folderId = "ZZZ"
DriveApp.getFolderById(folderId).createFile(blob).setName(usn+".pdf");
template.replaceAllText(name,"{{name}}");
}
}
Upvotes: 0
Views: 99
Reputation: 1738
The main problem here is that the text replaced is not updated, for that reason, you can make a copy of your slide filling the necessary information by using replaceAllText as you are actually doing. Then save and close it in order to flush and apply the changes. After all this procedure get the new files generated on the fly and move them to your trash directory.
function myFunction() {
var dataspreadsheet = "https://docs.google.com/spreadsheets/d/XXXX/edit"
var slide = SlidesApp.getActivePresentation();
var ss = SpreadsheetApp.openByUrl(dataspreadsheet);
var sheet = ss.getSheetByName('Sheet1');
var startRow = 2;
var numRows = 3;
var dataRange = sheet.getRange(startRow, 1, numRows, 3);
var data = dataRange.getValues();
var slides = slide.getSlides(); // You only need to get the slides once
for (var i in data) {
var row = data[i];
var name = row[0]; // First column
var usn = row[1]; //Second column
/* Make a copy instead */
var tmpSlide = SlidesApp.create(`tmp_presentation_${name}`);
slide.getSlides().forEach(s => {
tmpSlide.appendSlide(s);
});
var slidesTemplate = tmpSlide.getSlides();
slidesTemplate[0].remove(); // Remove the first empty slide
var template = slidesTemplate[1]; // Get the first slide of the copy without the empty slide
template.replaceAllText("{{name}}", name);
tmpSlide.saveAndClose(); // updates flushed and applied
var presentationCopyId = tmpSlide.getId(); // Get the ID of the new copy
var slideFile = DriveApp.getFileById(presentationCopyId);
var blob = slideFile.getBlob();
var folderId = "ZZZ"
DriveApp.getFolderById(folderId).createFile(blob).setName(usn+".pdf");
slideFile.setTrashed(true); // Then remove the slide previously created
}
}
Upvotes: 1