Using the Google Slides API with Apps Script for Document Merge
Google Slides API lets you programmatically create new presentations and edit existing ones. You can pull data from an external data source, like a Google Spreadsheet or Salesforce CRM, and create a nice-looking report in the form of a presentation. You can convert a Google Document into Google Slides or export a presentation as a PDF file.
You can also read an existing presentation using the API and modify individual elements on slides. For instance, if your organization logo has changed, you can use the Google Slides API to update the embedded images inside all slide via the API. Or if you would like to delete all slide that contains specific text, that can be done with the Google Slides API.
Replace Text in Google Slides presentation
You can use Google Apps Script to modify your Google Slides presentation. This quick example shows how to replace the markers in a presentation with actual text. Do enable the Slides API under Advanced Services.
function mergeGoogleSlide() {
try {
var presentationId = 'PRESENTATION_ID';
var requests = [
{
replaceAllText: {
containsText: { text: '<>' },
replaceText: 'Amit Agarwal',
},
},
{
replaceAllText: {
containsText: { text: '<>' },
replaceText: 'amit@labnol.org',
},
},
];
Slides.Presentations.batchUpdate({ requests: requests }, presentationId);
} catch (e) {
Logger.log(e.toString());
}
}
In the next example, we directly use the REST Google API to access the slides inside Google Apps Script.
// Fetch all Tables and Shape elements inside the presentation
function googleSlidesAPI(presentationId) {
var base = 'https://slides.googleapis.com/v1beta1/presentations/';
var apiUrl = base + presentationId + '/pages/pageId?fields=pageElements(table,shape)';
var params = {
method: 'get',
contentType: 'application/json',
headers: {
Authorization: 'Bearer ' + ScriptApp.getOAuthToken(),
},
muteHttpExceptions: true,
};
// returns a JSON response
var resp = UrlFetchApp.fetch(apiUrl, params);
Logger.log(resp.getContentText());
}
Similarly, you can make HTTP POST requests to insert text boxes or images, for replacing text or for deleting specific page elements from slides. To replace text everywhere within a presentation, use a ReplaceAllTextRequest request.
Amit Agarwal
Google Developer Expert, Google Cloud Champion
Amit Agarwal is a Google Developer Expert in Google Workspace and Google Apps Script. He holds an engineering degree in Computer Science (I.I.T.) and is the first professional blogger in India.
Amit has developed several popular Google add-ons including Mail Merge for Gmail and Document Studio. Read more on Lifehacker and YourStory