Linking TOC in Google Docs, with appropriate header

Viewed 55

I've a word document which I convert to Google Docs, but after the conversion as expected table of content break down in google docs, with no links to headers.

So I am trying to build the script to loop through the TOC and search the appropriate header in doc and change the style to "Header", while restoring the font size and style as it is.,

But it is not working, as when script runs it change style of TOC to header, instead of actual header, I want to exclude the TOC.

Here is the script:-

function toc() {
     const body = DocumentApp.getActiveDocument().getBody()
     const toc = body.findElement(DocumentApp.ElementType.TABLE_OF_CONTENTS).getElement().asTableOfContents()
     for(var i =  0 ; i < toc.getNumChildren() ; i++)
     {
        var tocElem = toc.getChild(i)
        var text = tocElem.getText()
        text = text.replace(/[\d\.]/g, "").trim() //.replace(/[\d\.]+$/, '')removing pagination of TOC
        console.log(text)
       if(text)
       {
         try{
        var elem = body.editAsText().findText(text)
        
        elem = elem.getElement().asText()
        console.log(elem)
        var font = elem.getFontFamily()
        var fontSize = elem.getFontSize()
        var style = {};
        style[DocumentApp.Attribute.HEADING] = DocumentApp.ParagraphHeading.HEADING6;
        var found =   body.findText(text)
        found.getElement().getParent().setAttributes(style)
         }
         catch(err)
         {
            //do nothing
         }
       }
     }
}

This is the script I build, let me know if there is other way to do it please.

Thanks

1 Answers

Since the TOC paragraphs are included in the body you need to find the first occurance of the TOC text and use that as a starting point to look for the second occurance.

var elem = body.editAsText().findText(text);
elem = body.editAsText().findText(text,elem);
if( !elem ) throw "paragraph not found";
Related