Manually create a toc in a word document

Is it possible to manually create a Table of Contents in a word document?

If yes, can you please give me some code?

Thanks

Hi Nitin,

Thanks for your inquiry. Sure, please see the following code that demonstrates how to insert a Table of contents (TOC) into a document using heading styles as entries.

// Use a blank document
Document doc = new Document();
// Create a document builder to insert content with into document.
DocumentBuilder builder = new DocumentBuilder(doc);
// Insert a table of contents at the beginning of the document.
builder.InsertTableOfContents("\\o \"1-3\" \\h \\z \\u");
// Start the actual document content on the second page.
builder.InsertBreak(BreakType.PageBreak);
// Build a document with complex structure by applying different heading styles thus creating TOC entries.
builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading1;
builder.Writeln("Heading 1");
builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading2;
builder.Writeln("Heading 1.1");
builder.Writeln("Heading 1.2");
builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading1;
builder.Writeln("Heading 2");
builder.Writeln("Heading 3");
builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading2;
builder.Writeln("Heading 3.1");
builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading3;
builder.Writeln("Heading 3.1.1");
builder.Writeln("Heading 3.1.2");
builder.Writeln("Heading 3.1.3");
builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading2;
builder.Writeln("Heading 3.2");
builder.Writeln("Heading 3.3");
// Call the method below to update the TOC.
doc.UpdateFields();

I hope, this helps.

Best regards,

That’s great.
So how do i now make these TOC items clickable and link them to a specific section of my document?
I need to do this so that I can build a TOC with only
the items I need. Not the whole document’s chapters headings.
Thanks

Hi Nitin,

Thanks for your inquiry. In order to make your TOC entries appear as hyperlink, you need to provide \h switch in field code.

Secondly, please attach your input Word document and target document showing the desired behaviour here for testing. I will investigate the structure of your target document as to how you would like TOC be generated like in your target document and provide you code snippet to achieve the same using Aspose.Words.

PS: You can create target document using Microsoft Word.

Best regards,