stephen776
stephen776

Reputation: 9234

How do I insert an element in a .docx file at a specific location using the OpenXML SDK in .NET

Hey guys I am trying to manipulate a word .docx file using the openXML sdk and C#.

I can open the file fine and insert paragraphs but I need to insert a paragraph at a specific location in my document(after a certain paragraph in my body).

I have not been able to find anything useful online about how to accomplish this.

Can anyone point me in the right direction?

Upvotes: 2

Views: 5567

Answers (1)

stephen776
stephen776

Reputation: 9234

The solution that I have settled on(though i know there are other ways) was to add a bookmark to the document, find the bookmark using the SDK, and replaceing it with my list. Works great.

IDictionary<String, BookmarkStart> bookMarkMap = new Dictionary<String, BookmarkStart>();
            foreach (BookmarkStart bookMarkStart in wordDoc.MainDocumentPart.RootElement.Descendants<BookmarkStart>())
            {
                bookMarkMap[bookMarkStart.Name] = bookMarkStart;
            }

            foreach (BookmarkStart bookMarkStart in bookMarkMap.Values)
            {
                if (bookMarkStart.Name == "MyBookmarkName")
                {
                    //do insert here   
                    var parent = bookMarkStart.Parent;

                    //create paragraph to insert
                    parent.InsertAfter(MyNewParagraph);         
                }
            }

Upvotes: 3

Related Questions