Apps Script to Generate a table of contents in Docs


Creating a Table of Contents (ToC) in a Google Docs document using Google Apps Script, focusing only on Heading 1 styles, is a straightforward task. Below is a script that does exactly that. It scans through your document, identifies all the text that has been styled as Heading 1, and then generates a ToC at the beginning of the document.

To use this script:

  1. Open your Google Docs document.
  2. Go to Extensions > Apps Script.
  3. Delete any code in the script editor and paste the following code.
  4. Save the script with a name, for example, Generate ToC for Heading 1.
  5. Run the script by clicking the play (▶) button.
  6. If prompted, authorize the script by following the on-screen instructions.

Here’s the Apps Script code:

function generateTableOfContents() {
  const doc = DocumentApp.getActiveDocument();
  const body = doc.getBody();

  // Create a new list for the Table of Contents
  const toc = body.insertParagraph(0, 'Table of Contents');
  toc.setHeading(DocumentApp.ParagraphHeading.HEADING1);

  // Add a line break after the ToC title
  body.insertParagraph(1, '');

  // Keep track of the position to insert the ToC entries
  let tocIndex = 2;

  // Iterate over all paragraphs to find those with Heading 1
  const paragraphs = body.getParagraphs();
  paragraphs.forEach((paragraph) => {
    if (paragraph.getHeading() === DocumentApp.ParagraphHeading.HEADING1) {
      // Use the text of the Heading 1 as the ToC entry
      const text = paragraph.getText();
      const tocEntry = body.insertParagraph(tocIndex, text);

      // Make the ToC entry a hyperlink that jumps to the Heading 1 position
      const position = doc.newPosition(paragraph, 0);
      const bookmark = doc.addBookmark(position);
      tocEntry.setLinkUrl('#' + bookmark.getId());

      // Increment the position for the next ToC entry
      tocIndex++;
    }
  });

  // Finally, add a visual separator after the ToC
  if (tocIndex > 2) { // Ensure there's at least one entry in the ToC
    body.insertParagraph(tocIndex, '-----').setAlignment(DocumentApp.HorizontalAlignment.CENTER);
  }
}

This script does the following:

  • Finds all paragraphs styled as Heading 1.
  • For each Heading 1 paragraph, it creates an entry in the Table of Contents at the top of the document.
  • Each ToC entry is made clickable, acting as a hyperlink to the corresponding heading in the document.
  • A visual separator line is added at the end of the ToC for better readability.

After running this script, you’ll see a “Table of Contents” section at the beginning of your document, with links to each Heading 1 styled text. This is a basic implementation. Depending on your needs, you might want to enhance this script, for example, by skipping the creation of a ToC if one already exists or by updating an existing ToC instead of always inserting a new one.