Enhanced Text Manipulation in Google Slides using Google Apps Script

Gists

Description

This is a sample Google Apps Script designed to replace all instances of specific text within a Google Slides presentation, while simultaneously applying a desired text style. The built-in Presentation.replaceAllText() method within the Google Slides service is limited; it efficiently replaces text strings but lacks the functionality to modify text formatting during the replacement process. This limitation poses a challenge when aiming for styled text replacements. This report presents a detailed script solution that overcomes this constraint. The script iterates through all text elements within the slides, identifies matching text, and performs a replacement. Crucially, it also applies specified text formatting attributes, such as font, font size, color, and bold/italic settings, to the replaced text. This enhanced functionality allows users to maintain consistent and visually appealing presentations when automating text modifications. Furthermore, the script illustrates the use of TextRange methods for precise text manipulation and styling within Google Slides. This approach offers a more robust alternative to the standard replaceAllText() method, providing greater control over text replacement and formatting in Google Slides automation workflows.

Sample

This is a sample Google Slide.

Script

Please copy and paste the following script into the Google Slides script editor. Ensure you configure the replaceObj object with your desired replacement values. This script will replace all matching text occurrences across every slide in your Google Slides presentation.

/**
 * ### Description
 * Replace all texts in all slides in a Google Slide by giving the text styles.
 *
 * @param {SlidesApp.Presentation} presentation Class Presentation object
 * @param {Object} replaceObj Object for replacing texts.
 * @return {void}
 */
function findReplaceAllText_(presentation, replaceObj) {
  const replaceWithLink_ = (text) => {
    replaceObj.forEach(({ replaceText, containsText, style }) => {
      const f = text.find(replaceText);
      if (f.length > 0) {
        f.forEach((ff) => {
          const text = ff.setText(containsText);
          if (style) {
            Object.entries(style).forEach(([k, v]) =>
              text
                .getTextStyle()
                [`set${k.replace(/^./, ([a]) => a.toUpperCase())}`](v)
            );
          }
        });
      }
    });
  };
  const forTable = (table) => {
    for (let r = 0; r < table.getNumRows(); r++) {
      for (let c = 0; c < table.getNumColumns(); c++) {
        replaceWithLink_(table.getCell(r, c).getText());
      }
    }
  };
  const forGroup = (g) => {
    g.getChildren().forEach((c) => {
      const type = c.getPageElementType();
      if (type == SlidesApp.PageElementType.SHAPE) {
        replaceWithLink_(c.asShape().getText());
      } else if (type == SlidesApp.PageElementType.TABLE) {
        forTable(p.asTable());
      } else if (type == SlidesApp.PageElementType.GROUP) {
        forGroup(c.asGroup());
      }
    });
  };
  presentation.getSlides().forEach((slide) => {
    slide.getPageElements().forEach((p) => {
      const type = p.getPageElementType();
      if (type == SlidesApp.PageElementType.SHAPE) {
        replaceWithLink_(p.asShape().getText());
      } else if (type == SlidesApp.PageElementType.TABLE) {
        forTable(p.asTable());
      } else if (type == SlidesApp.PageElementType.GROUP) {
        slide.getGroups().forEach(forGroup);
      }
    });
  });
}

// Please run this function.
function main() {
  const replaceObj = [
    {
      replaceText: "\\{\\{sample1\\}\\}",
      containsText: "value1",
      style: {
        linkUrl: "https://tanaikech.github.io",
        bold: true,
        italic: true,
        smallCaps: true,
        strikethrough: true,
        underline: true,
        foregroundColor: "#ff0000",
        fontSize: 16,
        backgroundColor: "#d9ead3",
      },
    },
    {
      replaceText: "\\{\\{sample2\\}\\}",
      containsText: "value2",
      style: { linkUrl: "https://github.com/tanaikech" },
    },
    { replaceText: "\\{\\{sample3\\}\\}", containsText: "value3" },
    {
      replaceText: "\\{\\{sample4\\}\\}",
      containsText: "value4",
      style: { bold: true },
    },
    {
      replaceText: "\\{\\{sample5\\}\\}",
      containsText: "value5",
      style: { italic: true },
    },
  ];
  const presentation = SlidesApp.getActivePresentation();
  findReplaceAllText_(presentation, replaceObj);
}

Testing

When the main function is executed, it interacts with the Google Slides API to dynamically update the provided sample presentation. Specifically, it identifies placeholders within the slide and replaces them with user-defined content, while meticulously preserving and applying the specified text styles. The resulting Google Slide, after the main function completes, showcases the successful replacement of all placeholders, demonstrating the function’s ability to automate content updates and maintain consistent formatting. This includes, but is not limited to, font type, size, color, and bold/italic/underline attributes.

Reference

Note

  • The top image was created by Gemini from the introduction.

 Share!