google-apps-scriptgoogle-slidestextrangetextstyle

Is it possible to get text style for each words individually?


I know it is possible to get the text style of a selected word using getSelection().getTextRange().getTextStyle()

but if I want to retrieve text styles from a previous slide word by word (getting each word's text style individually), is there a way to do that?


Solution

  • You can iterate through the PageElements of the slide, and retrieve the text style from each element.

    For each PageElement, you would have to check whether its type has TextRange as one of its properties (only Shape and TextCell elements have TextRange). If you try to retrieve text from an element that does not contain text, you might end up getting an error.

    Then, for each textRange that you retrieve, you can iterate through its runs (the different segments contained in this text that have a different text style), and retrieve the text style for each run.

    Code sample:

    function getTextStyles() {
      var slideId = "your-slide-id"; ID of the slide you want to retrieve text style
      var presentation = SlidesApp.getActivePresentation();
      var slide = presentation.getSlideById(slideId);
      var pageElements = slide.getPageElements(); // Get all page elements in slide
      pageElements.forEach(function(pageElement) { // Loop through all page elements in slide
        if (pageElement.getPageElementType() == "SHAPE") { // Check that current page element is of type "SHAPE"
          var textRange = pageElement.asShape().getText(); // Get text belonging to current page element
          textRange.getRuns().forEach(function(run) { // Loop through all runs in text
            var textStyle = run.getTextStyle(); // Get current row text style
            console.log(textStyle);
          });
        };
      });
    }
    

    Note:

    Reference: