I'm looking to inesrt image files into google slides according to the date they were created. I have the following code, which sequentually inserts images to googles slides from a drive folder:
function makeSlides() {
var presentation = SlidesApp.openById(slideID);
var folder = DriveApp.getFolderById(folderID);
var contents = folder.getFiles()
var file;
var i = 1;
while (contents.hasNext()) {
var file = contents.next();
data = file.getId();
// insert above image
var image = DriveApp.getFileById(data);
var slide = presentation.getSlides()[i];
var image = slide.insertImage(image);
slide = presentation.appendSlide(SlidesApp.PredefinedLayout.BLANK);
i ;
}
}
I would like to alter it so that the images are added by the date they were created (either newest or oldest). Any help received will be greatly appreciated. Thanks.
CodePudding user response:
I believe your goal is as follows.
- You want to retrieve the image files from the specific folder.
- You want to put the retrieved images to Google Slides in order of the created date of the file.
- You want to achieve this using Google Apps Script.
In this case, how about the following modification?
When the method of "Files: list" in Drive API is used, the file list can be retrieved in order of the created date. This is used for the modification.
Modified script:
Before you use this script, please enable Drive API at Advanced Google services.
function makeSlides() {
var slideID = "###"; // Please set your Google Slides ID.
var folderID = "###"; // Please set your folder ID.
var presentation = SlidesApp.openById(slideID);
var files = Drive.Files.list({orderBy: "createdDate asc", q: `'${folderID}' in parents and trashed=false and mimeType contains 'image'`, fields: "items(id)"}).items;
files.forEach(({id}, i) => {
var image = DriveApp.getFileById(id);
var slide = presentation.getSlides()[i];
var image = slide.insertImage(image);
slide = presentation.appendSlide(SlidesApp.PredefinedLayout.BLANK);
});
}
- When this script is run, the file list is retrieved from the specific folder in order of the created date of the file. In this case,
orderBy: "createdDate asc"
is used. This mean that the 1st image is the oldest image. When you want to use the order that the 1st image is the newest image, please modify toorderBy: "createdDate desc"
.
References:
CodePudding user response:
If you want them in specific order just sort them before adding.