EN VI

Google-apps-script - How to access shapes inside grouped shapes on Google slides using Apps Script?

2024-03-09 23:00:31
Google-apps-script - How to access shapes inside grouped shapes on Google slides using Apps Script?

I found that getShapes() does not retrieve the shapes on a Google slide that has been grouped.

For instance, create two shapes on a Google slide. Leave them ungrouped.

A grey circle and a grey rectangle

When I run the following code, the shapes will be filled with blue, as intended.

function myFunction() {
  var deckID = "SLIDE_ID";
  var slide = SlidesApp.openById(deckID).getSlides()[0];

  const blue = "#0000ff";
  const shapes = slide.getShapes();
  if (shapes.length > 0) {
    shapes.forEach(shape => shape.getFill().setSolidFill(blue));
  }
}

A blue circle and a blue rectangle

But if I group them (Right click -> Group, or Cmd + Option + G on Mac), and run the code again, they will remain the same grey color. Logging the array returned by getShapes() shows that it is completely empty, meaning grouped shapes are not treated as shapes.

How can I access all the shapes inside a group by code, without having to ungroup the shapes on the slide?

Solution:

In your showing script, how about the following modification?

Modified script:

function myFunctiondd() {
  var deckID = "SLIDE_ID";
  var slide = SlidesApp.openById(deckID).getSlides()[0];

  const blue = "#0000ff";
  const shapes = slide.getShapes();
  if (shapes.length > 0) {
    shapes.forEach(shape => shape.getFill().setSolidFill(blue));
  }

  // I added the below script.
  const processGroups = g => {
    g.getChildren().forEach(c => {
      const type = c.getPageElementType();
      if (type == SlidesApp.PageElementType.SHAPE) {
        c.asShape().getFill().setSolidFill(blue);
      } else if (type == SlidesApp.PageElementType.GROUP) {
        processGroups(c.asGroup());
      }
    });
  }
  slide.getGroups().forEach(processGroups);
}
  • When this script is run, the shapes in the groups are processed with getFill().setSolidFill(blue).

Reference:

Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login