Introduction
A bookmark identifies a location or a selection of the text, which you name and identify for future reference. In Word, when we add a bookmark to a block of text, the text will be surrounded with square brackets. Now, we can locate the text by using the bookmark instead of scrolling through the document. In this article, I will demonstrate how to add, replace and remove bookmarks programmatically in C#, using a .NET Word library.
Implementation
Adding a bookmark
This library provides two methods, which are AppendBookmarkStart (string name) and AppendBookmarkEnd (string name) in the Paragraph class to help us add a bookmark to the specific paragraph. BookmarkStart represents the start point of a bookmark and BookmarkEnd represents the end point of a bookmark.
-
- Document document = new Document();
- document.LoadFromFile(@"test.docx");
-
-
- Section section = document.Sections[0];
- section.Paragraphs[2].AppendBookmarkStart("bookmark");
- section.Paragraphs[3].AppendBookmarkEnd("bookmark");
-
-
- document.SaveToFile("Bookmark.docx", FileFormat.Docx);
Replacing a bookmark
BookmarkNavigator is used for navigating to a bookmark in a Word document. We can retrieve, replace and delete the contents of a specified bookmark by using BookmarkNavigator. With this library, it’s also possible to replace a bookmark with formatting by setting the saveFormatting argument as true in ReplaceBookmarkContent (TextBodyPart bodyPart, bool isKeepSourceFirstParaFormat, bool saveFormatting) method.
-
- Document document = new Document();
- document.LoadFromFile(@"Bookmark.docx");
-
-
- Section sec = document.AddSection();
- sec.AddParagraph().AppendText("Welcome Back, ");
- sec.AddParagraph().AppendText("Friend! ");
-
-
- ParagraphBase firstReplacementParagraph = sec.Paragraphs[0].Items.FirstItem as ParagraphBase;
- ParagraphBase lastReplacementParagraph = sec.Paragraphs[sec.Paragraphs.Count - 1].Items.LastItem as ParagraphBase;
- TextBodySelection selection = new TextBodySelection(firstReplacementParagraph, lastReplacementParagraph);
- TextBodyPart part = new TextBodyPart(selection);
-
-
- BookmarksNavigator bookmarkNavigator = new BookmarksNavigator(document);
- bookmarkNavigator.MoveToBookmark("bookmark", true, true);
- bookmarkNavigator.DeleteBookmarkContent(true);
-
-
- bookmarkNavigator.ReplaceBookmarkContent(part, true, true);
-
-
- document.Sections.Remove(sec);
- document.SaveToFile("ReplaceBookmark.docx");
Removing the bookmark
Every Word document contains a collection of bookmarks, which are accessible through the Bookmarks property of Document class. We can find and remove specific bookmark by using the Bookmarks property.
-
- Document document = new Document();
- document.LoadFromFile(@"Bookmark.docx");
- Bookmark bookmark = document.Bookmarks.FindByName("bookmark");
-
- document.Bookmarks.Remove(bookmark);
-
- document.SaveToFile("RemoveBookmark.docx", FileFormat.Docx);