代码之家  ›  专栏  ›  技术社区  ›  Mavi Domates

谷歌文档/应用程序脚本:插入带有样式的文本

  •  0
  • Mavi Domates  · 技术社区  · 4 年前

    我正在研究使用 Apps Scripts 。似乎可以选择一系列文本并对其应用样式,本问答中给出了一个示例: Formatting text with apps script (Google Docs) /但这不包括 插入带有样式的文本 .

    以身作则 here -我编辑了insertText方法,只需插入一个文本并按如下方式格式化,但它并没有按预期的方式工作。它插入了文本,但没有样式。

    function insertText(newText) {
           var cursor = DocumentApp.getActiveDocument().getCursor();
           cursor.insertText(newText).setForegroundColor('#123123').setBackgroundColor('#000').setItalic(true);
    }
    

    理想情况下,我正在寻找一种插入带有样式的文本的方法,如下所示:

    /// props being something on the lines of 
    /// { bold: true, fontFamily: 'something', italic: true, backgroundColor, foregroundColor etc... }
    
    ...insertText(text, {props});
    
    0 回复  |  直到 4 年前
        1
  •  1
  •   Tanaike    4 年前

    我相信你的目标如下。

    • 您希望在使用Google Apps脚本插入文本时设置文本样式。
    • 要将文字样式设置为 { bold: true, fontFamily: 'something', italic: true, backgroundColor, foregroundColor etc... } .

    在这种情况下,我认为 setAttributes 可以用来实现你的目标。

    示例脚本:

    function insertText(newText) {
      var prop = {"BOLD": true, "FONT_FAMILY": "Arial", "ITALIC": true, "BACKGROUND_COLOR": "#ffff00", "FOREGROUND_COLOR": "#ff0000"};
    
      var cursor = DocumentApp.getActiveDocument().getCursor();
      var text = cursor.insertText(newText);
      var attributes = Object.entries(prop).reduce((o, [k, v]) => Object.assign(o, {[k]: v}), {});
      text.setAttributes(attributes);
    }
    
    • 在官方文件中可以看到“BOLD”、“FONT_FAMILY”等键。 Ref 从本文档中,您可以选择其他样式。

    参考资料: