How to get a list of bookmarks from a Word document

Problem

You want to get a list of all the bookmarks in a document using WordWriter.

Solution

WordTemplate

The WordTemplate.Boomarks will return the names of all the bookmarks in a WordWriter template. This can be useful for binding data to the template with SetRepeatBlock, which requires the name of the bookmark for the repeatblock.

WordApplication

Use the GetElements method to retrieve all the elements of a particular type. In this case, the Element.Type is “Bookmark”.

For example, to retreive an array of all the bookmarks in a document:

Element[] eArray = document.GetElements(Element.Type.Bookmark);
//Get a handle on the first bookmark in the document
Bookmark bookmrk = (Bookmark)eArray[0];

If you need to retrieve a particular bookmark, use Document.GetBookmark(string), which returns the Bookmark object with the specified name.

Related posts: