I'm looking into inserting a simple text block to a Google Doc, using the 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) / but this doesn't cover inserting the text with the styles .
Following the example here - I've edited the insertText method to simply insert a text and format it like below, which hasn't worked the way it's supposed to. It's inserting the text but without the styles.
function insertText(newText) {
var cursor = DocumentApp.getActiveDocument().getCursor();
cursor.insertText(newText).setForegroundColor('#123123').setBackgroundColor('#000').setItalic(true);
}
Ideally I'm looking for a way to insert the text with the styling, something like below:
/// props being something on the lines of
/// { bold: true, fontFamily: 'something', italic: true, backgroundColor, foregroundColor etc... }
...insertText(text, {props});
I believe your goal as follows.
{ bold: true, fontFamily: 'something', italic: true, backgroundColor, foregroundColor etc... }
. In this case, I think that setAttributes
can be used for achieving your goal.
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);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.