Google Docs – Recover Formatting of Logical Elements

google docsgoogle-apps-script

I created a properly structured Google doc with correct title, heading 1..4 and "normal text" &c.

A "contributor" (&%&%^$!!!!!) did Ctrl-A and set font and font size for the whole document. Now headings and normal text look exactly the same, but the text is still correctly marked as headings vs. normal text.

Is there a way to recover the proper style for headings without going through the whole document and reformatting each heading by hand?

PS. I know about revision history, but there have been far too many content changes since that formatting change, as well as selective formatting changes for some of the the headings (by the same contributor).

Best Answer

This can be done with the following script (see Tools > Script Editor), where the variables h1Style, etc, define the style that should be applied to the headings at that level. The complete list of attributes that could be set is here, but I give representative examples (font family, size, weight, and color) below.

The script loops through the paragraphs (technically, a heading is a paragraph too), and applies the style when the paragraph is of heading type.

function restoreHeadings() {
  var h1Style = {};
  h1Style[DocumentApp.Attribute.FONT_SIZE] = 20;
  h1Style[DocumentApp.Attribute.FONT_FAMILY] = "Georgia";
  var h2Style = {};
  h2Style[DocumentApp.Attribute.FONT_SIZE] = 16;
  h2Style[DocumentApp.Attribute.FOREGROUND_COLOR] = "#555555";
  var h3Style = {};
  h3Style[DocumentApp.Attribute.FONT_SIZE] = 14;
  var h4Style = {};
  h4Style[DocumentApp.Attribute.FONT_SIZE] = 12;
  h4Style[DocumentApp.Attribute.BOLD] = true;

  var body = DocumentApp.getActiveDocument().getBody();
  var para = body.getParagraphs();
  for (var i in para) {
    switch (para[i].getHeading()) {
      case DocumentApp.ParagraphHeading.HEADING1:
        para[i].setAttributes(h1Style);
        break;
      case DocumentApp.ParagraphHeading.HEADING2:
        para[i].setAttributes(h2Style);
        break;
      case DocumentApp.ParagraphHeading.HEADING3:
        para[i].setAttributes(h3Style);
        break;
      case DocumentApp.ParagraphHeading.HEADING4:
        para[i].setAttributes(h4Style);
        break;        
    }
  }
}