Google Docs/Apps 脚本:插入带有样式的文本
Google Docs / Apps Script: Insert text with styles
我正在考虑使用 Apps Scripts. It looks like it's possible to select a range of text and apply styles to it, an example is presented in this question and answer: Formatting text with apps script (Google Docs) 向 Google 文档插入一个简单的文本块,但这不包括 使用样式插入文本.
按照示例 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});
我相信你的目标如下。
- 您想在使用 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 从该文档中,您可以 select 其他样式。
参考文献:
我正在考虑使用 Apps Scripts. It looks like it's possible to select a range of text and apply styles to it, an example is presented in this question and answer: Formatting text with apps script (Google Docs) 向 Google 文档插入一个简单的文本块,但这不包括 使用样式插入文本.
按照示例 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});
我相信你的目标如下。
- 您想在使用 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 从该文档中,您可以 select 其他样式。