Adam O'Neil
Adam O'Neil

Reputation: 134

Microsoft Word VSTO Addin - Replacing bookmarks without deleting them

I am working on a Word 2010 addin for a word template we are using. I have several bookmarks in the page, and their content can be changed using various wizards in the addin.

I need to add images and tables to the bookmarks now - and this works fine, but deletes the bookmark immediately afterwards. I am using the following code, passing in the bookmark.Range as a parameter.

Adding a table:

bookmark.Range.Tables.Add(bookmark.Range, rowCount, columnCount, ref _objectMissing, ref _objectMissing);

Adding an image:

InlineShape shape = bookmark.Range.InlineShapes.AddPicture(path, ref _objectMissing, ref _objectMissing, ref _objectMissing);

I need to be able to do this without deleting the bookmark, so that I can go back and replace the image if the user runs the wizard again. Any ideas how to do this would be greatly appreciated!

Upvotes: 1

Views: 1980

Answers (1)

GTG
GTG

Reputation: 4954

Both InlineShape and Table objects have a Range property that you can use to restore the bookmark, like this:

// Keep the name of the bookmark
string bookmarkName = bookmark.Name;
// Insert your image, as before
InlineShape shape = bookmark.Range.InlineShapes.AddPicture(path, ref _objectMissing, ref _objectMissing, ref _objectMissing);
// Restore the bookmark
Object range = shape.Range;
yourDocumentVariable.Bookmarks.Add(bookmarkName, ref range);

Upvotes: 2

Related Questions