Search code examples
c#ms-wordnovacode-docx

DocX - how to get the index of a paragraph or list?


I am developing an application that needs to insert content from user input (including from a rich text editor) into a Word document. For this purpose I use the DocX library (http://docx.codeplex.com/). The library provides a very neat way of doing certain tasks and works great as long as you only need to insert content into an empty document.

However, the document I need to insert into is a template that already has some content. What I need is to be able to insert the user input after this content in the document. Like this:

Some default content here.

[This is were I want my content]

Some other default content here.

DocX has methods for inserting paragraphs and lists into a document:

using(var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(PathToTestFile))
{
    var doc = DocX.Load(stream); //will have two paragraphs
    var p = doc.InsertParagraph(); //adds a new, empty paragraph to the end of the document
    var list = doc.AddList(listType: ListItemType.Numbered); //adds a list
    doc.AddListItem(list, "Test1", listType: ListItemType.Numbered); //adds a listitem to the list
    doc.InsertList(list); //adds a list to the end of the document
}

A paragraph also has a method for inserting certain objects, like tables or other paragraphs either before og after itself:

//given a Paragraph p and another Paragraph newP:
p.InsertParagraphAfterSelf(newP);

Lists have the same method, but neither has the option of doing the same with other Lists (i.e. I cannot do the same as the above example with a list). For this purpose, I need the index of the paragraph or list in the document. This will allow me to use the insert methods that accepts an index as a parameter.

The DocX class has this (extracted from DocX source code: http://docx.codeplex.com/SourceControl/latest#DocX/DocX.cs):

// A lookup for the Paragraphs in this document.
    internal Dictionary<int, Paragraph> paragraphLookup = new Dictionary<int, Paragraph>();

This dictionary is internal, which means I cannot access it. I cannot, for the life of me, find any other way of finding the index, but it has to be a way since there are methods that needs this index. Has anyone encountered the same problem? A solution would be much appriciated!


Solution

  • The easiest way to do what you are asking is to edit your template document in Word and insert a bookmark into it where you want to add content. You can then use:

    document.InsertAtBookmark("Content to be added", "bookmarkname");
    

    to insert the content.