简体   繁体   中英

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);


}

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:

在此处输入图像描述

After:

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM