0
votes

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});
1

1 Answers

1
votes

I believe your goal as follows.

  • You want to set the text style when the text is inserted using Google Apps Script.
  • You want to set the text style with { bold: true, fontFamily: 'something', italic: true, backgroundColor, foregroundColor etc... }.

In this case, I think that setAttributes can be used for achieving your goal.

Sample script:

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 keys like "BOLD", "FONT_FAMILY" and so on can be seen at the official document. Ref From this document, you can select other styles.

References: