问题描述
我正在考虑使用Apps Scripts将简单的文本块插入Google文档。看起来可以选择一定范围的文本并为其应用样式,此问题和答案中提供了一个示例:Formatting text with apps script (Google Docs) /,但这不包括用样式插入文本。
下面的示例here-我编辑了insertText方法,以简单地插入文本并按如下所示设置其格式,但这并未达到预期的效果。它是在插入文本,但没有样式。
@H_502_6@function insertText(newText) {
var cursor = DocumentApp.getActiveDocument().getCursor();
cursor.insertText(newText).setForegroundColor('#123123').setBackgroundColor('#000').setItalic(true);
}
理想情况下,我正在寻找一种插入带有样式的文本的方法,如下所示:
@H_502_6@/// props being something on the lines of
/// { bold: true,fontFamily: 'something',italic: true,backgroundColor,foregroundColor etc... }
...insertText(text,{props});
解决方法
我相信您的目标如下。
- 您要在使用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您可以从本文档中选择其他样式。