Google Docs – Change Built-in Paragraph Styles with Script

google docsgoogle-apps-script

I need to edit the look of the styles in Google docs. I'm using script to insert text into a blank document. Before I insert the text I define the look of new styles like this:

var vedlegget = {};
vedlegget[DocumentApp.Attribute.FONT_SIZE] = 10;
vedlegget[DocumentApp.Attribute.BOLD] = false;
vedlegget[DocumentApp.Attribute.ITALIC] = true;
vedlegget[DocumentApp.Attribute.SPACING_AFTER] =7;
vedlegget[DocumentApp.Attribute.LINE_SPACING]=1;
vedlegget[DocumentApp.Attribute.FOREGROUND_COLOR] = '#007cb0';

But I also need to use the built-in-styles like Normal and Headings. I need to make a Table of Contents etc.

How do I define the look of the style HEADING1?

I insert the Heading 1 text like shown here:
https://developers.google.com/apps-script/reference/document/paragraph-heading

But I cannot find any way of editing the style.

Best Answer

Use setHeadingAttributes method. For example, here I redefine the styles of Heading levels 1 and 2.

  myHeading1 = {};
  myHeading1[DocumentApp.Attribute.FONT_SIZE] = 24;
  myHeading1[DocumentApp.Attribute.FONT_FAMILY] = "Georgia";

  myHeading2 = {};
  myHeading2[DocumentApp.Attribute.FONT_SIZE] = 16;
  myHeading2[DocumentApp.Attribute.FONT_FAMILY] = "Verdana";
  myHeading2[DocumentApp.Attribute.FOREGROUND_COLOR] = "#555555";

  var body = DocumentApp.getActiveDocument().getBody();
  body.setHeadingAttributes(DocumentApp.ParagraphHeading.HEADING1, myHeading1);
  body.setHeadingAttributes(DocumentApp.ParagraphHeading.HEADING2, myHeading2);

Note that this does not immediately affect already existing paragraphs: those stay with their current style unless someone touches their heading level (i.e., selects something from the heading level drop-down, even the same level as the current one). To apply the changes retroactively to existing paragraphs, see this answer.

Related Topic