Skip to content

Instantly share code, notes, and snippets.

@tanaikech
Created March 12, 2025 05:16
Show Gist options
  • Save tanaikech/0779fec840d06cbc545d07cb0209bd3d to your computer and use it in GitHub Desktop.
Save tanaikech/0779fec840d06cbc545d07cb0209bd3d to your computer and use it in GitHub Desktop.
Creating Tree Structure from Headings in Google Documents using Google Apps Script

Creating Tree Structure from Headings in Google Documents using Google Apps Script

Description

This is a Google Apps Script for creating the tree structure from headings in Google Documents.

Usage

In order to test this script, please do the following steps.

1. Sample Document

Create a sample Document as follows.

2. Sample script

Open the script editor and copy and paste the following script.

In this script, Document service (DocumentApp) is used.

function sample1() {
  const headTypes = [
    "TITLE",
    "HEADING1",
    "HEADING2",
    "HEADING3",
    "HEADING4",
    "HEADING5",
    "HEADING6",
  ];
  const body = DocumentApp.getActiveDocument().getBody();
  const res = body
    .getParagraphs()
    .reduce((ar, p) => {
      const idx = headTypes.indexOf(p.getHeading().toString());
      if (idx > -1) {
        ar.push(Array(idx).fill(" ").join("") + p.getText());
      }
      return ar;
    }, [])
    .join("\n");
  console.log(res);
}

As another approach, the following script uses Docs API. Please enable Docs API at Advanced Google services. Ref

function sample2() {
  const headTypes = [
    "TITLE",
    "HEADING_1",
    "HEADING_2",
    "HEADING_3",
    "HEADING_4",
    "HEADING_5",
    "HEADING_6",
  ];
  const documentId = DocumentApp.getActiveDocument().getId();
  const obj = Docs.Documents.get(documentId).body.content;
  const res = obj
    .reduce((ar, e) => {
      if (
        e.paragraph &&
        e.paragraph.paragraphStyle &&
        e.paragraph.paragraphStyle.namedStyleType
      ) {
        const idx = headTypes.indexOf(
          e.paragraph.paragraphStyle.namedStyleType
        );
        if (idx > -1) {
          ar.push(
            Array(idx).fill(" ").join("") +
              e.paragraph.elements[0].textRun.content.trim()
          );
        }
      }
      return ar;
    }, [])
    .join("\n");
  console.log(res);
}

When you run the functions sample1 and sample2, the following result is obtained in the console.

Title1A
 Heading1A
  Heading2A
   Heading3A
    Heading4A
     Heading5A
      Heading6A
Title1B
 Heading1B
  Heading2B
   Heading3B
    Heading4B
     Heading5B
      Heading6B
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment