A bookmark marks a specific location in a document for referencing and assigns a name to that location so that the user can easily navigate to that particular location. DsWord provides you Bookmark class which represents a bookmark range in the content. Using DsWord, you can add bookmarks in a document with Add method of the BookmarkCollection class and delete them using Delete method of the Bookmark class.
To add a bookmark:
C# |
Copy Code |
---|---|
var section = doc.Body.Sections.First; // Add the first paragraph var p = section.GetRange().Paragraphs.Add("A bookmark marks a specific location" + " in a document for referencing and assigns a name to that location so that" + " the user can easily navigate to that particular location."); //Add a paragraph to the section for (var pr = 1; pr <= 30; pr++) { section.GetRange().Paragraphs.Add("Section1: Test Paragraph"); } //Define bookmark name var bmk = "Bookmark1"; // Add a paragraph var pb = section.GetRange().Paragraphs.Add($"{bmk} points here."); //Mark the paragraph with a bookmark pb.GetRange().Bookmarks.Add(bmk); //Create hyperlink text to jump to the bookmark location(paragraph) p.GetRange().Runs.Add("Jump to"); p.GetRange().Hyperlinks.Add(bmk, $"{bmk}"); p.GetRange().Runs.Add("at the end of the document."); //Save the document doc.Save("AddBookmark.docx"); |
To modify a bookmark:
C# |
Copy Code |
---|---|
doc.Load("AddBookmark.docx"); //Modify the bookamrk name var newBmk = "TestBookmark"; Bookmark bmark = doc.Body.Sections.First.GetRange().Paragraphs.Last.GetRange().Bookmarks.First; bmark.Name = newBmk; //Update the bookmark name in the hyperlink created for the bookmark Hyperlink hyperlink_bookmark = doc.Body.Sections.First.GetRange().Paragraphs.First.GetRange().Hyperlinks.First; hyperlink_bookmark.Anchor = newBmk; hyperlink_bookmark.GetRange().Texts[0].Value = newBmk; //Save the document doc.Save("ModifyBookmark.docx"); |
To delete a bookmark, access the bookmark from the bookmark collection using Bookmarks property of the RangeBase class and delete it using the Delete method.
C# |
Copy Code |
---|---|
//Load the existing word document doc.Load("AddBookmark.docx"); //Delete bookmark Bookmark bmark = doc.Body.Sections.First.GetRange().Paragraphs.Last.GetRange().Bookmarks.First; bmark.Delete(); //Delete hyperlink to bookmark doc.Body.Sections.First.GetRange().Paragraphs.First.GetRange().Runs[1].Delete(); doc.Body.Sections.First.GetRange().Paragraphs.First.GetRange().Hyperlinks.First.Delete(); doc.Body.Sections.First.GetRange().Paragraphs.First.GetRange().Runs.Last.Delete(); //Save the document doc.Save("DeleteBookmark.docx"); |
For more information on how to implement bookmarks using DsWord, see DsWord sample browser.