Question

I'm writing a script for Google Docs. I want to get the position of all the headings in the document. Then I want to create a list of other links with these headings in the document. I do not want to use TABLE_OF_CONTENTS. I want to make similarity Navigation Panel in Word 2010(link). Only in Google Docs. How can I get the position, or create links to all the headings in the document and put them in the sidebar? Thank you for your help! Have a nice day.

Was it helpful?

Solution 3

See this example. It's a Google Doc with a script to create a sidebar with a table of contents.

Below is just the code to get the list of headers. The linked document has everything in its Script Editor.

//Recursively get subsections
function getHeadersFromParagraphs(paragraphs, limit, starter){
  var headers = [], header, hType, level, start, result,
      paragraph,
      heading,
      i,
      h1 = DocumentApp.ParagraphHeading.HEADING1,
      h2 = DocumentApp.ParagraphHeading.HEADING2,
      h3 = DocumentApp.ParagraphHeading.HEADING3,
      h4 = DocumentApp.ParagraphHeading.HEADING4,
      h5 = DocumentApp.ParagraphHeading.HEADING5,
      h6 = DocumentApp.ParagraphHeading.HEADING6,
      hTypes = [h1,h2,h3,h4,h5,h6];

  //Loop through all paragraphs
  start = starter ? starter.id+1 : 0;
  for(i = start; i < paragraphs.length; i += 1){
    paragraph = paragraphs[i];
    heading = paragraph.getHeading();
    level = hTypes.indexOf(heading);

    if(level > -1 && level < limit){
      if(paragraph.getText() == "") continue;
      if(starter && level <= starter.level) { i--; break; }

      header = { name : paragraph.getText(), id : i, level : level };
      result = getHeadersFromParagraphs(paragraphs, limit, header);
      i = result.index;
      header.subheaders = result.headers;
      headers.push(header);
    }
  }
  return { headers : headers, index : i }
}

//Initiate parsing of headers. By default, limit to Heading 1.
function pullHeaders(level){
  level = level || 1;
  var body = DocumentApp.getActiveDocument().getBody(),
      paragraphs = body.getParagraphs();
  var result = getHeadersFromParagraphs(paragraphs, level);
  return JSON.stringify(result.headers);
}

OTHER TIPS

You no longer need to resort to 3rd party add-ons as Google has embraced this feature and released it on 09/03/2016.

Just check Tools > Document outline option and you are good to go.

By now this answer might be obsolete, but there is an Add on in Google Docs that allows you to do that. Just click "Add-Ons" and search for "table of contents" or "document navigator" - you'll find the add on that will generate you a navigation bar as you described. There may be other add ons out there doing the same stuff.....

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top