Managing Texts on Google Slides using Google Apps Script

Gists

This is a sample script for managing the texts on Google Slides using Google Apps Script. Recently, I got the request like this. I published this here, because I thought that this might be also useful for other users.

Demo

In this demonstration, the text of {{baz}} on Google Slides are searched and replaced to other text, and also, the text style is changed.

Sample situation

In this case, it supposes that there are 3 types of shapes in the slide. Those are the text box, the rectangle shape and the explosion shape. Each shape has the texts and the title of the shape like shape1, shape2 and shape3. The sample script searches the shape using the title. You can see it at the following image.

Sample script

When this script is run, the texts of all sheets in the Google Slides can be managed.

function myFunction() {
  // This object is used for managing the texts on Google Slides.
  const obj = {
    shape1: {
      search: "\\{\\{baz\\}\\}",
      replace: "sample1",
      style: {
        foregroundColor: "#ffff00",
        backgroundColor: "#000080",
        bold: true,
        fontSize: 30,
      },
    },
    shape2: {
      search: "\\{\\{baz\\}\\}",
      replace: "sample2",
      style: { foregroundColor: "#ffff00" },
    },
    shape3: {
      search: "\\{\\{baz\\}\\}",
      replace: "sample3",
      style: { url: "https://tanaikech.github.io/" },
    },
  };

  SlidesApp.getActivePresentation()
    .getSlides()
    .forEach((slide) => {
      slide.getShapes().forEach((s) => {
        const o = obj[s.getTitle()];
        s.getText()
          .find(o.search)
          .forEach((v) => {
            const style = v.setText(o.replace).getTextStyle();
            const os = o.style;
            if (os) {
              if (os.bold) style.setBold(os.bold);
              if (os.backgroundColor)
                style.setBackgroundColor(os.backgroundColor);
              if (os.fontSize) style.setFontSize(os.fontSize);
              if (os.url) style.setLinkUrl(os.url);
              if (os.foregroundColor)
                style.setForegroundColor(os.foregroundColor);
            }
          });
      });
    });
}
  • This is a sample script. So when you want to manage other text style, you can achieve this by modifying above script.

Important points

  • When find() is used, please be careful. When find("{{baz}}") is used, an error occurs. So please use find("\\{\\{baz\\}\\}").
  • When setForegroundColor and setLinkUrl are used, at first, please use setLinkUrl, and then use setForegroundColor. By this, the text has the link and the foreground color.

References

 Share!