Home > Net >  Replacing shapes by colour in Google Slides & Google Apps Script
Replacing shapes by colour in Google Slides & Google Apps Script

Time:09-22

I am attempting to replace shapes color in a Google Slide presentation, using Google Apps Script.

function changeColors() {
  const objectId = "#an-id#";  // Please set the object ID.

  const slides = SlidesApp.openById(objectId).getSlides();
  slides.forEach(loopSlides);
  
}

function loopSlides(slide){

  var shapes = slide.getShapes();
  if (shapes.length > 0) {
    shapes.forEach(myFunction);
  }
}

function myFunction(shape) {
  try{
    var st = shape.getShapeType();
  if (st != SlidesApp.ShapeType["RECTANGLE"] && 
      st != SlidesApp.ShapeType["ROUND_RECTANGLE"] &&
      st != SlidesApp.ShapeType["UNSUPPORTED"]){
          Logger.log("Not a box!!");
          Logger.log(st);
          Logger.log(shape.getText());
        return;
      }
  }
  catch(err) {
    Logger.log("Not a Shape!!");
   return; // not a shape!
}
  var hexColor = shape.getFill().getSolidFill();
  Logger.log(hexColor);
  switch (hexColor){
    case "#f16727ff": // Computer Science
      shape.getFill().setSolidFill("#413c73ff");
    case "#0b9faeff": // Information technology
      shape.getFill().setSolidFill("#d90368ff");
    case "#d71b55ff": // Digital Literacy
      shape.getFill().setSolidFill("#aa968aff");    
      }

}

The above code will never run the replacement code (Basically it will never reach the Logger.log(hexColor); instruction

CodePudding user response:

When I run your code it reaches Logger.log(hexColor);. The issue in your code is that your hexColor variable is actually a enter image description here

Note:

  • I used String.toLowerCase() to change the rgb hex string into lowercase for your switch statement
  • Your rgb hex strings is incorrect. (I removed trailing ff). RGB hex string should only consist of 6 characters.
  • Your switch cases has missing break for each cases. If you don't include a break the shape color will always be set to the last solid fill setting which is #aa968a
  • Related