我可以使用 Google Apps Script 为 Google 文档中的某些词着色吗? [英] Can I color certain words in Google Document using Google Apps Script?

查看:25
本文介绍了我可以使用 Google Apps Script 为 Google 文档中的某些词着色吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试突出显示我的 Google 文档中的某些字词.我知道我可以使用 document.replace 替换文本,但它只替换字符串本身,而不是格式.有没有办法使用 Google Apps 脚本用彩色字符串替换字符串?

I'm trying to highlight certain words in my Google Document. I know I can replace text using document.replace, but it only replaces string itself, not formatting. Is there a way to replace string with colored string using Google Apps Script?

推荐答案

这是一个更好的解决方案:

This is a better solution:

function highlightTextTwo() {
  var doc  = DocumentApp.openById('<your document id');
  var textToHighlight = 'dusty death';
  var highlightStyle = {};
  highlightStyle[DocumentApp.Attribute.FOREGROUND_COLOR] = '#FF0000';
  var paras = doc.getParagraphs();
  var textLocation = {};
  var i;

  for (i=0; i<paras.length; ++i) {
    textLocation = paras[i].findText(textToHighlight);
    if (textLocation != null && textLocation.getStartOffset() != -1) {
      textLocation.getElement().setAttributes(textLocation.getStartOffset(),textLocation.getEndOffsetInclusive(), highlightStyle);
    }
  }
}

上一个答案:

关键是能够仅引用您想要着色的单词.

The key is to being able to reference just the words you want to color.

我的解决方案是:

获取包含您要着色的单词的段落文本,删除原始段落,然后将文本的每一部分添加回去.当您将每个部分添加回来时,appendText 仅返回对添加的文本的引用,然后您可以使用 setForegroundColor() 指定其颜色:

Get the text of the paragraph that contains the words you wish to color, remove the original paragraph, then add each part of the text back. As you add each part back the appendText returns a reference to just the text added, you then can specify its color with setForegroundColor():

function highlightText() {
  var doc = DocumentApp.openById('<your document id>');
  var textToHighlight = 'dusty death';
  var textLength = textToHighlight.length;
  var paras = doc.getParagraphs();
  var paraText = '';
  var start;
  for (var i=0; i<paras.length; ++i) {
    paraText = paras[i].getText();
    start = paraText.indexOf(textToHighlight);
    if (start >= 0) {
      var preText = paraText.substr(0, start);
      var text = paraText.substr(start, textLength);
      var postText = paraText.substr(start + textLength, paraText.length);
      doc.removeChild(paras[i]);
      var newPara = doc.insertParagraph(i, preText);
      newPara.appendText(text).setForegroundColor('#FF0000');
      newPara.appendText(postText).setForegroundColor('#000000');
    }
  }
}

这篇关于我可以使用 Google Apps Script 为 Google 文档中的某些词着色吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆