Manipulate Bookmarks in Word Programmatically
Word bookmark is a useful tool for identifying key words, phrases and locations within a document, which provides the reader with a quick way to navigate through long documents. You may have a project that requires Microsoft Office to automatically insert, edit and remove bookmarks, and you are searching for a fast solution. Don't worry, Spire.Doc allows you to complete your application without wasting time or losing quality.
Introduction
Word bookmark is a useful tool for identifying key words, phrases and locations within a document, which provides the reader with a quick way to navigate through long documents. You may have a project that requires Microsoft Office to automatically insert, edit and remove bookmarks, and you are searching for a fast solution. Don't worry, Spire.Doc allows you to complete your application without wasting time or losing quality.
Using the code
In this article we are going to see how to insert bookmarks, edit and remove it in a pretty easy method to use the free library. So the first step you need to do is downloading Spire.Doc from the following link.
https://freeword.codeplex.com/
Then, we create an application console and include the following libraries.
using Spire.Doc;
using Spire.Doc.Documents;
Then, we initial a document object and add a new section and several paragraphs, finally we add the bookmark where we want.
Document doc = new Document();
Section sec = doc.AddSection();
Paragraph p1 = sec.AddParagraph();
p1.AppendText("This is paragraph 1");
Paragraph p2 = sec.AddParagraph();
p2.AppendText("This is paragraph 2");
Paragraph p3 = sec.AddParagraph();
p3.AppendText("This is paragraph 3");
sec.Paragraphs[1].AppendBookmarkStart("Bookmark");
sec.Paragraphs[1].AppendBookmarkEnd("Bookmark");
doc.SaveToFile("Bookmark.docx",Spire.Doc.FileFormat.Docx);
And you can open the Bookmark document and see that the bookmark has been added in the second paragraph.
After we added the bookmark to where we want, we can modify or replace the content at the bookmark location.
Document doc = new Document();
doc.LoadFromFile("Bookmark.docx");
BookmarksNavigator bn = new BookmarksNavigator(doc);
bn.MoveToBookmark("Bookmark", true, true);
Paragraph paragraph = new Paragraph(doc);
Image image = Image.FromFile("1.PNG");
DocPicture picture = paragraph.AppendPicture(image);
bn.InsertParagraph(paragraph);
doc.SaveToFile("ChangeContent.docx", Spire.Doc.FileFormat.Docx);
Effect Screenshot
Finally, the library provides the method to remove the bookmark you don't wanna preserve according to the index or bookmark.
Document doc = new Document();
doc.LoadFromFile("Bookmark.docx");
doc.Bookmarks.RemoveAt(0);
doc.SaveToFile("RemoveBookmark.docx",FileFormat.Docx);