Skip to content

Instantly share code, notes, and snippets.

@mcgivrer
Last active December 30, 2024 01:10
Show Gist options
  • Save mcgivrer/e6837544e84b4b316f1fbcf3d0ea63c8 to your computer and use it in GitHub Desktop.
Save mcgivrer/e6837544e84b4b316f1fbcf3d0ea63c8 to your computer and use it in GitHub Desktop.
Google Apps script to generate slide from spreadsheet data
function generateBookSlideFromDataSheet() {
var presentationTemplateId = '[SLIDE_GOOGLE_DOC_ID]';
var spreadSheetDataId = '[SPREADSHEET_GOOGLE_DOC_ID]';
var dataRange="[DATA_RANGE:'A2:J10']"
var generatedBooksFolderId='[FOLDER_OUTPUT_GOOGLE_DOC_ID]';
var bookdata = Sheets.Spreadsheets.Values.get(spreadSheetDataId,dataRange);
// Parse all lines from the Spreadsheet and stop if a line is empty.
for(var i=0;bookdata.values.length;i++){
if(bookdata.values[i]==undefined){
break;
}
var bookItem = bookdata.values[i];
var bookTitle = bookItem[0];
var authorName = bookItem[1];
var authorPhoto = bookItem[2];
var authorDesc = bookItem[3];
var publisherName = bookItem[4];
var publishingYear = bookItem[5];
var publisherUrl = bookItem[6];
var bookDesc = bookItem[7];
var coverImageFront = bookItem[8];
var coverImageBack = bookItem[9];
var texts = [
["${book.title}", bookTitle],
["${author.name}", authorName],
["${author.description}", authorDesc],
["${book.description}", bookDesc],
["${publisher.name}", publisherName],
["${publisher.url}", publisherUrl],
["${publishing.year}", publishingYear],
["${image.book.front}",coverImageFront],
["${image.book.back}",coverImageBack],
["${image.author.photo}",authorPhoto]
];
// Create the new Presentation based on the template and rename it accordingly to book title.
var newBookPresentation = DriveApp.getFileById(presentationTemplateId).makeCopy();
var bookId = newBookPresentation.getId();
DriveApp.getFileById(bookId).setName('book-' + (i+1) + '-' + bookTitle );
var presentation=SlidesApp.openById(bookId);
console.info(presentation.getName());
// replace all placeholder in the current slide
texts.forEach(t=>{
if(t[0].toString().trim().startsWith("${image.")){
presentation.getSlides().forEach(slide=>{
slide.getShapes().forEach(shape=>{
if(shape.getText().asString().trim()==t[0]){
var sWidth = shape.getWidth();
var sHeight = shape.getHeight();
console.info(shape.getText() + "w:"+sWidth+" h:"+sHeight);
shape.replaceWithImage(t[1]);
}
})
});
}else{
presentation.replaceAllText(t[0],t[1]);
}
});
presentation.saveAndClose();
//MNove the generated book to the "generatedBooks" folder.
DriveApp.getFileById(bookId).moveTo(DriveApp.getFolderById(generatedBooksFolderId));
}
SlidesApp.flush();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment