如何使用谷歌应用程序脚本获取谷歌文档中的所有 h1 标题?

时间:2021-04-12 18:57:09

标签: google-apps-script google-docs google-docs-api

基本上,我想获取活动文档中的所有 h1 标题并将其更改为 h2 还计划做一些字体样式等。

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


}

1 个答案:

答案 0 :(得分:0)

你可以参考这个示例代码:

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

它有什么作用?

  1. 使用 Body.findElement(elementType, from)
  2. 在文档中搜索段落
  3. 使用Paragraph.getHeading()检查当前段落的标题
  4. 如果标题为DocumentApp.ParagraphHeading.HEADING1,则将标题设置为DocumentApp.ParagraphHeading.HEADING2并使用Paragraph.setHeading(heading)Paragraph.setAttributes(attributes)更改其段落属性

输出:

之前:

enter image description here

之后:

enter image description here

相关问题