Tutorial: Generating Google Slides from images

Goal

Complete the steps here to produce a script that creates a new presentation with individual slides for each image in an array of online images (accessible by URL). This tutorial is the full-length companion to the DevByte video on this page.

Time to complete

Approximately 20 minutes

Prerequisites

To install and run this sample, you need the following:

  1. The URL locations of several images to include in the constructed presentation. You must have read access to the images.

Overview

  1. Create a brand new script.
  2. Add addImageSlide() which creates a new slide and inserts an image.
  3. Implement the driving application which calls addImageSlide() for each image.
  4. Run the sample; see the results.
  5. Improve the sample code and wrap-up.

Creating our new script

In this tutorial, we're going to keep it simple and build a standalone script (not tied to any particular document). Let's get started by creating a new script. The easiest way to do that is to point your browser to script.google.com. (You can also click NEW in your Google Drive user interface and select "Google Apps Script".) If you encounter a welcome screen, click Blank Project.

Replace all lines of code with the following:

var NAME = "My favorite images";
var deck = SlidesApp.create(NAME);

Here, we're naming our slide deck as well as creating a new Google Slides file with the same name. All of the action when interacting with the Slides Service takes place with the SlidesApp object.

addImageSlide() function

Copy these lines for the addImageSlide() function into the code editor just below the two lines of code you pasted into the editor from the previous step above:

 function addImageSlide(imageUrl, index) {
     var slide = deck.appendSlide(SlidesApp.PredefinedLayout.BLANK);
     var image = slide.insertImage(imageUrl);
 }
function addImageSlide(imageUrl, index) {
    var slide = presentation.appendSlide(SlidesApp.PredefinedLayout.BLANK);
    var image = slide.insertImage(imageUrl);
    var imgWidth   = image.getWidth();
    var imgHeight  = image.getHeight();
    var pageWidth  = presentation.getPageWidth();
    var pageHeight = presentation.getPageHeight();
    var newX = pageWidth/2.  - imgWidth/2.;
    var newY = pageHeight/2. - imgHeight/2.;
    image.setLeft(newX).setTop(newY);
}

This function creates a new blank slide in the presentation and inserts the image into it via its URL. This function is called for each image you have, creating a new slide each time. Note that the image may be automatically resized by the API to fit within a slide page's dimensions.

Save the file by clicking File > Save, name your project "Image Slides" (or similar), then OK.

Create the main loop

Now let's create the driver app. Add the following main() function to the end of your script file. This function sets the array of image URLs then creates a new slide in the presentation for each one. We've provided some generic Google images by default but feel free to replace any and all with your own.

function main() {
    var images = [
        "https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png",
        "http://www.google.com/services/images/phone-animation-results_2x.png",
        "http://www.google.com/services/images/section-work-card-img_2x.jpg",
        "http://gsuite.google.com/img/icons/product-lockup.png",
        "http://gsuite.google.com/img/home-hero_2x.jpg"
    ];
    var [title, subtitle] = deck.getSlides()[0].getPageElements();
    title.asShape().getText().setText(NAME);
    subtitle.asShape().getText().setText("Google Apps Script\nSlides Service demo");
    images.forEach(addImageSlide);
}

The image array is followed by code that grabs the title and subtitle textboxes from the first slide (index 0), then fills them in with the file name (also the presentation title) and a generic subtitle of, "Google Apps Script Slides Service demo". The last part is a forEach() that loops over each image in the array, creating new slides for each of them.

Run the sample

In the Apps Script editor, click Run > Run function > main.

The first time scripts are executed, users are prompted to grant permission for the services requested. In this case, it is the user's Google Slides presentations:

  1. Click the Review permissions button then select your Google account.
  2. The script requires authorization to run. When presented with such a request, read it carefully then click Allow to authorize the script.

The script executes, adding the requested images as slides in the presentation. By default, each image is placed in the upper-left corner of their respective slides, so you should see something like this:

Improving our script

While we accomplished the original objective of building a slide deck from a set of images, you would likely want those images centered if you were delivering a presentation, so let's adjust the code to do that.

Replace the current addImageSlide() function with the one below. The first pair of lines is identical to what we had earlier. The magic is in the 7 new lines we appended:

 function addImageSlide(imageUrl, index) {
     var slide = deck.appendSlide(SlidesApp.PredefinedLayout.BLANK);
     var image = slide.insertImage(imageUrl);
 }
function addImageSlide(imageUrl, index) {
    var slide = presentation.appendSlide(SlidesApp.PredefinedLayout.BLANK);
    var image = slide.insertImage(imageUrl);
    var imgWidth   = image.getWidth();
    var imgHeight  = image.getHeight();
    var pageWidth  = presentation.getPageWidth();
    var pageHeight = presentation.getPageHeight();
    var newX = pageWidth/2.  - imgWidth/2.;
    var newY = pageHeight/2. - imgHeight/2.;
    image.setLeft(newX).setTop(newY);
}

First, we get the dimensions of the image being added, then do the same for the slide page. The final 3 lines calculate the new (X, Y) coordinates to center the image on the page then sets its new location via setLeft() and setTop(). If we run our sample again with this change, all of the images are centered as desired:

Further study and additional reading

Other resources

You've now completed a quick intro to the Slides Service in Apps Script... congrats! If you want lower-level access to manipulating Slides, you may wish to consider the Slides Advanced Service. The advanced service is a wrapper around the Slides (REST) API.

If you want to programmatically access Google Slides but outside the Apps Script environment, perhaps with your own development tools, consider using the Slides API directly from a client library. The Google APIs Client Libraries documentation features a list of all supported languages.

If you wish to distribute your app more broadly, consider turning your script into an add-on. To make your script an add-on, you must add a few things, such as an onOpen() function to create menu items.

Add-on scripts also have a few special authorization rules that they need to follow. Although the sample that we've created works well as a standalone script, it violates rules against executing global statements as part of the Add-on Authorization Lifecycle. Once your add-on is compliant, you can publish it!

Code challenges

If you want to expand your understanding or dive deeper into Apps Script coding, try to augment the sample above with the following upgrades:

  1. Instead of online files, choose files in Google Drive
  2. Use the Google Drive file picker interface (files first then folders)
  3. Accept images from a web form (files first then a ZIP archive)

If you're happy with the sample above, try building on top of it. Instead of creating a presentation from images available online, tweak the code to get images from Google Drive. Take a look at the Drive Service documentation to learn how to use it.

Then consider taking that app a step further by using the Drive file picker dialog user interface and let your users choose which file(s) to add to the slide show. Extra credit if you then extend it to allow your users to select a Drive folder of images instead of just a single file.

Once you get that working, perhaps you want to skip accessing Drive altogether. Want to write a tiny web app that accepts images uploaded directly through an HTML form? Give it a shot, but if you want some hints:

Once you get that working, your final challenge is to upgrade that app to accept a ZIP file of images with the unzip() utility and build an entire slide presentation from it.

Reference

Sample script plus comments

var NAME = "My favorite images";
var presentation = SlidesApp.create(NAME);

/**
 * Creates a single slide using the image from the given link;
 * used directly by foreach(), hence the parameters are fixed.
 *
 * @param {Date} link A String object representing an image URL
 * @param {Date} index The index into the array; unused (req'd by forEach)
 */
function addImageSlide(imageUrl, index) {
    var slide = presentation.appendSlide(SlidesApp.PredefinedLayout.BLANK);
    var image = slide.insertImage(imageUrl);
    var imgWidth   = image.getWidth();
    var imgHeight  = image.getHeight();
    var pageWidth  = presentation.getPageWidth();
    var pageHeight = presentation.getPageHeight();
    var newX = pageWidth/2.  - imgWidth/2.;
    var newY = pageHeight/2. - imgHeight/2.;
    image.setLeft(newX).setTop(newY);
}

/**
 * The driver application features an array of image URLs, setting of the
 * main title & subtitle, and creation of individual slides for each image.
 */
function main() {
    var images = [
        "http://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png",
        "http://www.google.com/services/images/phone-animation-results_2x.png",
        "http://www.google.com/services/images/section-work-card-img_2x.jpg",
        "http://gsuite.google.com/img/icons/product-lockup.png",
        "http://gsuite.google.com/img/home-hero_2x.jpg"
    ];
    var [title, subtitle] = presentation.getSlides()[0].getPageElements();
    title.asShape().getText().setText(NAME);
    subtitle.asShape().getText().setText("Google Apps Script\nSlides Service demo");
    images.forEach(addImageSlide);
}

Send feedback about...

Apps Script
Apps Script