简体   繁体   English

Google Docs Apps Script getBackgroundColor(Offset)

[英]Google Docs Apps Script getBackgroundColor(Offset)

Let's say I have some sentences in Google Docs.假设我在 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.不幸的是 getBackgroundColor() 似乎只适用于段落而不适用于单个单词。

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" “找不到文本对象中的函数getBackgroundColor”

Thx for any help, or hints or comments!感谢任何帮助、提示或评论!

  • 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() .在这种情况下,颜色是不是getForegroundColor()的背景颜色。
  • You want to achieve this using Google Apps Script.您想使用 Google Apps 脚本来实现这一点。

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.首先,你的错误原因是getBackgroundColor()是Class Text的方法。 In your script, getBackgroundColor() is used for the string value.在您的脚本中, getBackgroundColor()用于字符串值。 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.运行脚本时,将解析第 1 段的文本。 And you can see the result with res as an object.你可以看到结果以res作为对象。
  • In this sample script, the 1st paragraph is used as a test case.在此示例脚本中,第 1 段用作测试用例。 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.如果我误解了您的问题并且这不是您想要的方向,我深表歉意。

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'));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM