This demo uses the DevExpress Word Processing Document API to insert a table of contents into the predefined template.
Select document data/formatting you want to use to construct the table of contents: outlines, paragraph styles, or TC fields. The Table of Contents Settings pane allows you to specify the display style.
Click Generate Table of Contents and Save as… to select an output format, apply changes, and download the result.
Sample Document
TableOfContents_Template.docx
Table of Contents Settings
using DevExpress.XtraRichEdit;
using DevExpress.XtraRichEdit.API.Native;
MemoryStream CreateTableOfContents(Stream stream, TabLeaderType tabLeaderType, bool includePageNumbers,
TOCInsertMode insertMode, int startLevel, int endLevel, bool useHyperlinks, DocumentFormat targetFormat) {
using var wordProcessor = new RichEditDocumentServer();
wordProcessor.LoadDocument(stream);
List<string> switches = new();
// Hyperlinks switch
if (useHyperlinks)
switches.Add("\\h");
// Levels (only if not TC fields selection and valid range)
if (insertMode != TOCInsertMode.TCFields)
switches.Add($"\\o \"{startLevel}-{endLevel}\"");
// Show / hide page numbers (if IncludePageNumbers false add \n to hide)
if (!includePageNumbers)
switches.Add($"\\n \"{startLevel}-{endLevel}\"");
// OutlineLevels vs ParagraphStyles vs TC fields
switch (insertMode) {
case TOCInsertMode.OutlineLevels:
switches.Add("\\u"); // use outline levels
break;
case TOCInsertMode.TCFields:
// Use identifier for TC fields (choose static id) \f id
switches.Add($"\\f chapters");
switches.Add($"\\l \"{startLevel}-{endLevel}\"");
break;
}
string fieldCode = "TOC" + (switches.Count > 0 ? (" " + string.Join(" ", switches)) : string.Empty) + " ";
var document = wordProcessor.Document;
var tocParagraphRange = document.Bookmarks["toc_bookmark"].Range;
Field tocField = document.Fields.Create(tocParagraphRange.Start, fieldCode);
tocField.Update();
document.UpdateAllFields();
var output = new MemoryStream();
wordProcessor.SaveDocument(output, targetFormat);
output.Position = 0;
return output;
}