Tag Archives: using bookmarks in wordtemplate

How to delete extra pages from a document with WordApplication

Problem

Extra pages in a template document can sometimes be useful in making a template more versatile. For instance, a company could use a generic employment contract with unique pages describing each position, but with common pages on company policy.

This post covers how to delete extra pages from a template document using WordApplication

Solution

In order to delete unneeded pages from a template document, you should use bookmarks to identify the pages that you wish to delete. Then, use the Bookmark.DeleteElement() method, which is inherited from our Element object. Calling DeleteElement() on a bookmark in WordWriter will delete not only the bookmark, but its contents.

1. Place each extra page within a bookmark in your template file. Remember to include the page break within the bookmark so that it is removed when you remove the bookmark.

2. Before filling the template with data, open the file using the WordApplication object and delete the extra pages using the Bookmark.DeleteElement() method.

Document doc = wa.Open(@"..\\..\\templates\templatefile.doc");
Bookmark bm = doc.get_Bookmark("Bookmark");
bm.DeleteElement();

3. Pass the Document back to the WordTemplate object and bind with data.