Search code examples
google-apps-scriptgoogle-docs-api

Google Docs API in Apps Script


I am trying to use Apps Script with Google Docs API to have a setting within a personally created submenu to change text color, depending on which option is selected in the sub menu. Can someone give me a general idea of how I can get the current color of a specific paragraph and set it to a different color.


Solution

  • To get the current foreground color of a paragraph use Method:Paragraph.getAttribute and Method:Paragraph.setAttribute to set the foreground color.

    Example:

    enter image description here

    Code:

    function myFunction() {
      var doc = DocumentApp.getActiveDocument();
      var body = doc.getBody();
      body.getParagraphs().forEach(par => {
        var style = {};
        if(par.getAttributes().FOREGROUND_COLOR == '#ff0000'){
          style[DocumentApp.Attribute.FOREGROUND_COLOR] = '#0000ff';
        }else if(par.getAttributes().FOREGROUND_COLOR == '#ff9900'){
          style[DocumentApp.Attribute.FOREGROUND_COLOR] = '#008000';
        }
        par.setAttributes(style);
      })
    }
    

    Output:

    Output

    Here are the list of Attributes you can use.