How to generate Table Of Contents using OpenXML SDK 2.0?

Using the SDK I'm building Word documents that contain reports. These documents need to have TOC. Does anybody have a complete solution that I can follow in order to understand how to do this?

(I've read everything on http://openxmldeveloper.org/)


How to generate a Table of Contents (TOC) � Issue #223 � OfficeDev , no way in generating a Table of Contents as per sdk 2.0 but is it updated be to use Word automation in conjunction with Open XML SDK to� Explains the markup of tables-of-contents. TOCs use field markup. See Deep dive into OpenXML Fields for more info. Screen-cast #2. Presents some sample code that shows how to insert TOC markup into a document. Screen-cast #3. Shows how to use Word Automation to update the TOC. Screen-cast #4. Shows how to use Word Automation Services to update


Use auto Table of contents (clickable)

  1. Set Heading

    public static Paragraph SetHeading1(this Paragraph p)
    {
        var pPr = p.Descendants<ParagraphProperties>().First();
        pPr.ParagraphStyleId = new ParagraphStyleId() { Val = "Heading1" };
        return p;
    }
    
  2. Generate TOC from empty document, you can use this:

    private static string GetTOC(string title, int titleFontSize)
    {
        return $@"<w:sdt>
     <w:sdtPr>
        <w:id w:val=""-493258456"" />
        <w:docPartObj>
           <w:docPartGallery w:val=""Table of Contents"" />
           <w:docPartUnique />
        </w:docPartObj>
     </w:sdtPr>
     <w:sdtEndPr>
        <w:rPr>
           <w:rFonts w:asciiTheme=""minorHAnsi"" w:eastAsiaTheme=""minorHAnsi"" w:hAnsiTheme=""minorHAnsi"" w:cstheme=""minorBidi"" />
           <w:b />
           <w:bCs />
           <w:noProof />
           <w:color w:val=""auto"" />
           <w:sz w:val=""22"" />
           <w:szCs w:val=""22"" />
        </w:rPr>
     </w:sdtEndPr>
     <w:sdtContent>
        <w:p w:rsidR=""00095C65"" w:rsidRDefault=""00095C65"">
           <w:pPr>
              <w:pStyle w:val=""TOCHeading"" />
              <w:jc w:val=""center"" /> 
           </w:pPr>
           <w:r>
                <w:rPr>
                  <w:b /> 
                  <w:color w:val=""2E74B5"" w:themeColor=""accent1"" w:themeShade=""BF"" /> 
                  <w:sz w:val=""{titleFontSize * 2}"" /> 
                  <w:szCs w:val=""{titleFontSize * 2}"" /> 
              </w:rPr>
              <w:t>{title}</w:t>
           </w:r>
        </w:p>
        <w:p w:rsidR=""00095C65"" w:rsidRDefault=""00095C65"">
           <w:r>
              <w:rPr>
                 <w:b />
                 <w:bCs />
                 <w:noProof />
              </w:rPr>
              <w:fldChar w:fldCharType=""begin"" />
           </w:r>
           <w:r>
              <w:rPr>
                 <w:b />
                 <w:bCs />
                 <w:noProof />
              </w:rPr>
              <w:instrText xml:space=""preserve""> TOC \o ""1-3"" \h \z \u </w:instrText>
           </w:r>
           <w:r>
              <w:rPr>
                 <w:b />
                 <w:bCs />
                 <w:noProof />
              </w:rPr>
              <w:fldChar w:fldCharType=""separate"" />
           </w:r>
           <w:r>
              <w:rPr>
                 <w:noProof />
              </w:rPr>
              <w:t>No table of contents entries found.</w:t>
           </w:r>
           <w:r>
              <w:rPr>
                 <w:b />
                 <w:bCs />
                 <w:noProof />
              </w:rPr>
              <w:fldChar w:fldCharType=""end"" />
           </w:r>
        </w:p>
     </w:sdtContent>
    

    " }

  3. Create SdtBlock, and set TOC xml

        var sdtBlock = new SdtBlock();
        sdtBlock.InnerXml = GetTOC(Translations.ResultsBooksTableOfContentsTitle, 16);
        document.MainDocumentPart.Document.Body.AppendChild(sdtBlock);
    
  4. Set UpdateFieldsOnOpen

        var settingsPart = document.MainDocumentPart.AddNewPart<DocumentSettingsPart>();
        settingsPart.Settings = new Settings { BordersDoNotSurroundFooter = new BordersDoNotSurroundFooter() { Val = true } };
    
        settingsPart.Settings.Append(new UpdateFieldsOnOpen() { Val = true });
    

if you need generate pdf file from docx, it's working fine!

How do we use Open XML SDK 2.0 and update the TOC, What is the best way to update the TOC in an Open XML word document? Is there something in the SDK that will do this? Thomas Abruzzo� Features include the ability to generate Open XML SDK 2.0 source code based on document content, compare source and target Open XML documents to reveal differences and to generate source code to create the target from the source, validate documents, and display documentation for the Open XML SDK v2.0, the ECMA376v1 standard, and the Microsoft


Thanks to Dmitri Pavlov (@DmitryPavlov) for the help.

I don't want to give an answer to my own question, but this is just to illustrate the steps that I’ve taken.

The advice for anyone interested is to watch the 5-part screen-cast by Eric White - Exploring Tables-of-Contents in Open XML WordprocessingML Documents. This has all the info with respect to adding and updating a TOC (am much more).

My solution was to use a Template (just a regular empty document that had styles for everything I needed: Header 1-5, TOC style, etc.). This is particularly useful as a quick fix for the styles issue (the new document, that has the TOC, will have a new style.xml created; this file has some additional data; as a result the hierarchy in the TOC isn’t as expected – i.e., header 2 is the child of header 1, header 3 is a child of header 2, etc.).

Therefore:

  1. Create a Word document and add all the elements that you expect to be added later programmatically (e.g., Header 1-5, Table of Contents, etc.). Delete all the contents and save the document (the reason for this is to create styles for all the necessary elements).

  2. I personally added the template (the file created at step #1) as a resource in my project.

  3. In your code, create a new copy of the template (this will be the actual file that you will work on). I used:

    byte[] stream = Properties.Resources.Template;
    File.WriteAllBytes(@"D:\Template.docx", stream);
    File.Copy(@"D:\Template.docx", @"D:\New.docx");
    
  4. Flush all the data to this document.

  5. Add the source files from screen-cast 2, 3 or 4 to your project (for this please see screen-cast 3) - at the end of those posts you will find a link to download TocAdder.zip. Or just add a reference to TocAdder.dll.

  6. Insert the TOC. Just an example:

    using (WordprocessingDocument wdoc = WordprocessingDocument.Open(@"D:\New.docx", true))
    {
        XElement firstPara = wdoc
            .MainDocumentPart
            .GetXDocument()
            .Descendants(W.p)
            .FirstOrDefault();
        TocAdder.AddToc(wdoc, firstPara,
            @"TOC \o '1-3' \h \z \u", null, null);
    }
    
  7. Replace the styles in the newly created document with the ones from the template. You can use this resource from MSDN: Replacing the Styles Parts in Word 2010 Documents by Using the Open XML SDK 2.0. Again, an example:

    string fromDoc = @"D:\Template.docx";
    string toDoc = @"D:\New.docx";
    var node = WDExtractStyles(fromDoc, false);
    if (node != null)
        WDReplaceStyles(toDoc, node, false);
    node = WDExtractStyles(fromDoc);
    if (node != null)
        WDReplaceStyles(toDoc, node);
    
  8. Optionally use one of the methods described in screen-cast 3, 4 or 5 in order to get around the problem with the modal dialog box that Word puts up.

Hope this will be useful for somebody.

How to generate Table Of Contents using OpenXML SDK 2.0 , Open XML SDK 2.0 does not have this feature supported. But you can generate a small TOC through Word app, and reflect the TOC parts with Document� This article describes the various approaches to working with documents in memory. It also presents some code that uses the Open XML SDK 2.0 to show how to implement these scenarios. Using MemoryStream Objects with the Open XML SDK 2.0. One of the overloads of the Open() method enables you to open an Open XML document from a stream. There is


If you have a TOC field, this will cause it to be updated when the document is opened in Word (body is a reference to the document body):

DocumentFormat.OpenXml.Wordprocessing.SimpleField f;
f = new SimpleField();
f.Instruction="sdtContent";
f.Dirty = true;
body.Append(f);

Exploring Tables-of-Contents in Open XML WordprocessingML , As part of the definition of each TOC, you specify a set of switches that Word uses as instructions on how to construct the TOC. This screen-cast discusses the TOC � Using document = WordprocessingDocument.Open(fileName, True) Dim doc = document.MainDocumentPart.Document ' Code removed here… End Using Creating the Table Object and Setting Its Properties. Before you can insert a table into a document, you must create the Table object and set its properties.


Open XML SDK, Back to TOCJust VideosCondensed TOC . Generating Documents from SharePoint with Open XML Content Controls deals with revision tracking, and how to programmatically accept tracked revisions using the Open XML Format SDK 2.0. Fixes to the Open XML SDK 2.0 for Microsoft Office—Open XML SDK 2.5 includes fixes to known issues in the Open XML SDK 2.0 for Microsoft Office. These include lost whitespaces in PowerPoint presentations and an issue with the Custom UI in Word documents where a specified argument was reported as being out of the range of valid values.


open xml sdk 2.0 for office, This thread on Stack Overflow might be useful to read: How to generate Table Of Contents using OpenXML SDK 2.0? Purposes The purpose to export a� In order to use the classes, you must add as a reference the DocumentFormat.OpenXml library from Open XML SDK 2.0, and WindowsBase in your project; adding in Visual Studio is straightforward. First, you have install Open XML SDK 2.0 provided by Microsoft, and it will install into C:\Program Files\Open XML SDK .


create word document using openxml c#, Creating word doc using Open XML SDK 2.0 Microsoft. you create Word processing document structure and content using strongly-typed classes that you can use that , alternatively I have just release article on creation of word table using� The main using: using DocumentFormat.OpenXml; Create Table. Tables in OpenXml isn't much more difficult. In order you have to create a table, then rows, then