gignu
gignu

Reputation: 2475

Google Docs Apps Script getBackgroundColor(Offset)

Let's say I have some sentences in Google Docs. Just one sentences as an example:

"My house is on fire"

I actually changed the background color so that every verb is red and every noun blue. Now I want to make a list with all the verbs and another one with the nouns. Unfortunately getBackgroundColor() only seems to work with paragraphs and not with single words.

My idea was, to do something like this (I didn't yet have the time to think about how to do the loop, but that's not the point here anyway):

var doc = DocumentApp.getActiveDocument();
var body = doc.getBody();
var paragraphs = body.getParagraphs();

var colorVar = paragraphs[0].getText().match(/\w+/).getBackgroundColor();   // The regEx matches the first word. Next I want to get the background color. 

Logger.log(colorVar);
}

The error message I get goes something like this:

"The function getBackgroundColor in the text object couldn't be found"

Thx for any help, or hints or comments!

Upvotes: 1

Views: 561

Answers (2)

Cooper
Cooper

Reputation: 64032

Here's a script your welcome to take a look at. It highlights text that a user selects...even individual letters. I did it several years ago just to learn more about how documents work.

function highLightCurrentSelection() {
  var conclusionStyle = {};
      conclusionStyle[DocumentApp.Attribute.BACKGROUND_COLOR]='#ffffff';
      conclusionStyle[DocumentApp.Attribute.FOREGROUND_COLOR]='#000000';
      conclusionStyle[DocumentApp.Attribute.FONT_FAMILY]='Calibri';
      conclusionStyle[DocumentApp.Attribute.FONT_SIZE]=20;
      conclusionStyle[DocumentApp.Attribute.BOLD]=false;
      conclusionStyle[DocumentApp.Attribute.HORIZONTAL_ALIGNMENT]=DocumentApp.HorizontalAlignment.LEFT;
      conclusionStyle[DocumentApp.Attribute.VERTICAL_ALIGNMENT]=DocumentApp.VerticalAlignment.BOTTOM;
      conclusionStyle[DocumentApp.Attribute.LINE_SPACING]=1.5;
      conclusionStyle[DocumentApp.Attribute.HEIGHT]=2;
      conclusionStyle[DocumentApp.Attribute.LEFT_TO_RIGHT]=true;
  var br = '<br />';
  var selection = DocumentApp.getActiveDocument().getSelection();
  var s='';
  if(selection) {
    s+=br + '<strong>Elements in Current Selection</strong>';
    var selectedElements = selection.getRangeElements();
    for(var i=0;i<selectedElements.length;i++) {
      var selElem = selectedElements[i];
      var el = selElem.getElement();
      var isPartial = selElem.isPartial();
      if(isPartial) {
        var selStart = selElem.getStartOffset();
        var selEnd = selElem.getEndOffsetInclusive();
        s+=br + 'isPartial:true selStart=' + selStart + ' selEnd=' + selEnd ;
        var bgcolor = (el.asText().getBackgroundColor(selStart)=='#ffff00')?'#ffffff':'#ffff00';
        el.asText().setBackgroundColor(selStart, selEnd, bgcolor)
      }else {
        var selStart = selElem.getStartOffset();
        var selEnd = selElem.getEndOffsetInclusive();
        s+=br + 'isPartial:false selStart=' + selStart + ' selEnd=' + selEnd ;
        var bgcolor = (el.asText().getBackgroundColor()=='#ffff00')?'#ffffff':'#ffff00';
        el.asText().setBackgroundColor(bgcolor);
      }
      var elType=el.getType();
      s+=br + 'selectedElement[' + i + '].getType()= ' + elType;
      if(elType==DocumentApp.ElementType.TEXT) {
        var txt = selElem.getElement().asText().getText().slice(selStart,selEnd+1);
        var elattrs = el.getAttributes();
        if(elattrs)
        {
          s+=br + 'Type:<strong>TEXT</strong>';
          s+=br + 'Text:<span style="color:#ff0000">' + txt + '</span>';
          s+=br + 'Length: ' + txt.length;
          s+=br + '<div id="sel' + Number(i) + '" style="display:none;">';
          for(var key in elattrs)
          {
             s+= br + '<strong>' + key + '</strong>' + ' = ' + elattrs[key];
             s+=br + '<input type="text" value="' + elattrs[key] +  '" id="elattr' + key + Number(i) + '" />';
             s+=br + '<input id="elattrbtn' + Number(i) + '" type="button" value="Save Changes" onClick="setSelectedElementAttribute(\'' + key + '\',' + i + ');" />'
          }
          s+='</div><a href="#sel' + Number(i) + '" onClick="toggleDiv(\'sel' + Number(i) + '\')">Show/Hide</a>';
        }
      }
      if(elType==DocumentApp.ElementType.PARAGRAPH) {
        var txt = selElem.getElement().asParagraph().getText();
        var elattrs = el.getAttributes();
        if(elattrs)
        {
          s+=br + '<strong>PARAGRAPH Attributes</strong>';
          s+=br + 'Text:<span style="color:#ff0000">' + txt + '</span> Text Length= ' + txt.length;
          for(var key in elattrs)
          {
            s+= br + key + ' = ' + elattrs[key];
          }
        }
      }
      s+='<hr width="100%"/>';
    }
     //var finalP=DocumentApp.getActiveDocument().getBody().appendParagraph('Total Number of Elements: ' + Number(selectedElements.length));
     //finalP.setAttributes(conclusionStyle);
  }else {
    s+= br + 'No Elements found in current selection';
  }
  s+='<input type="button" value="Toggle HighLight" onclick="google.script.run.highLightCurrentSelection();"/>';
  //s+='<input type="button" value="Exit" onClick="google.script.host.close();" />';
  DocumentApp.getUi().showSidebar(HtmlService.createHtmlOutputFromFile('htmlToBody').append(s).setWidth(800).setHeight(450).setTitle('Selected Elements'));
}

Upvotes: 1

Tanaike
Tanaike

Reputation: 201338

  • You want to retrieve the text from a paragraph.
  • You want to retrieve each word and the background color of each word from the retrieved the text.
    • In this case, the color is the background color which is not getForegroundColor().
  • You want to achieve this using Google Apps Script.

If my understanding is correct, how about this answer? Please think of this as just one of several possible answers. At first, the reason of your error is that getBackgroundColor() is the method of Class Text. In your script, getBackgroundColor() is used for the string value. By this, the error occurs.

In this answer, for achieving your goal, each character of the text retrieved from the paragraph is scanned, and each word and the background color of each word can be retrieved.

Sample script:

function myFunction() {
  var doc = DocumentApp.getActiveDocument();
  var body = doc.getBody();
  var paragraphs = body.getParagraphs();
  var textObj = paragraphs[0].editAsText();
  var text = textObj.getText();
  var res = [];
  var temp = "";
  for (var i = 0; i < text.length; i++) {
    var c = text[i];
    if (c != " ") {
      temp += c;
    } else {
      if (temp != "") res.push({text: temp, color: textObj.getBackgroundColor(i - 1)});
      temp = "";
    }
  }
  Logger.log(res) // result
}
  • When you run the script, the text of 1st paragraph is parsed. And you can see the result with res as an object.
  • In this sample script, the 1st paragraph is used as a test case. So if you want to retrieve the value from other paragraph, please modify the script.

References:

If I misunderstood your question and this was not the direction you want, I apologize.

Upvotes: 2

Related Questions