Erwin Lengkeek
Erwin Lengkeek

Reputation: 128

Change default paragraph headings programmatically for Google Docs with Apps Script

I've been searching for this feature for quite awhile now. Basically, I'd like to change the default paragraph styles for Title, Subtitle, Heading 1 and so on.

I know it is possible with the Google Docs interface (https://support.google.com/docs/answer/116338?hl=en), but as far as I know not programatically with Apps Script.

Did anyone find a solution for this yet? And if not, can we submit it as a feature request for the Google Apps script team? It would be a great addition to the already existing Apps Script Docs API for branding purposes.

Upvotes: 2

Views: 1779

Answers (1)

user6655984
user6655984

Reputation:

Now this is possible with the 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);

It doesn't seem possible to reset the attributes back to their default, so if you think that a reset will be needed, get the original attributes with getHeadingAttributes and store them in document properties.

Note that changing heading attributes does not immediately affect already existing headings: they 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.

Upvotes: 2

Related Questions