google-apps-scriptgoogle-docsgoogle-docs-api

How do i get all h1 headings in google doc with google apps script?


Basically, I want to get all the h1 heading in the active doc and change it into h2 also planning to do some font styling, etc.

function abc() {
  var body = DocumentApp.getActiveDocument().getBody();

 // instead of appending the paragraph in line 8 i want to get all the h1 heading that are avialble in the active document

 var par1 = body.appendParagraph("changing h1 to h2 heading");
 par1.setHeading(DocumentApp.ParagraphHeading.HEADING2);


}

Solution

  • You can refer to this sample code:

    function findHeader() {
      var doc = DocumentApp.getActiveDocument();
      var body = doc.getBody();
      // Define the search parameters.
      var searchType = DocumentApp.ElementType.PARAGRAPH;
      var searchHeading = DocumentApp.ParagraphHeading.HEADING1;
      var searchResult = null;
      
      var style = {};
      style[DocumentApp.Attribute.FONT_FAMILY] = 'Calibri';
      style[DocumentApp.Attribute.BOLD] = true;
    
      // Search until the paragraph is found.
      while (searchResult = body.findElement(searchType, searchResult)) {
        var par = searchResult.getElement().asParagraph();
        if (par.getHeading() == searchHeading) {
          // Found one, update
          par.setHeading(DocumentApp.ParagraphHeading.HEADING2);
          par.setAttributes(style);
        }
      }
    }
    

    What it does?

    1. Search for paragraphs in the document using Body.findElement(elementType, from)
    2. Check the heading of the current paragraph using Paragraph.getHeading()
    3. If the heading is DocumentApp.ParagraphHeading.HEADING1, set the heading to DocumentApp.ParagraphHeading.HEADING2 and change its paragraph attributes using Paragraph.setHeading(heading) and Paragraph.setAttributes(attributes)

    Output:

    Before:

    enter image description here

    After:

    enter image description here