0

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 Answer 1

1

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:

Sign up to request clarification or add additional context in comments.

2 Comments

OP says cursor.insertText(newText).setForegroundColor('#123123').setBackgroundColor('#000').setItalic(true); this didn't work. Any reason?
@TheMaster I think that the script works. From which hasn't worked the way it's supposed to. I thought that OP might have tested to use the object. From OP's direction which wants to set the text style using the object like { bold: true, fontFamily: 'something', italic: true, backgroundColor, foregroundColor etc... }, I proposed to use setAttributes. If this alsy didn't work, I think that the reason might be the same with the 1st issue. At that time, I will confirm it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.