How to: Insert Bookmark or Hyperlink
- 2 minutes to read
The following example demonstrates how to create a bookmark or hyperlink in the document.
Create Hyperlink
To create a hyperlink, use the HyperlinkCollection.Create method. The newly created Hyperlink object will be automatically added to the document hyperlink collection, represented by the HyperlinkCollection instance.
Use the hyperlink’s Hyperlink.NavigateUri property to set a target URI. To specify a text for the tooltip displayed when the mouse hovers over a hyperlink, use the Hyperlink.ToolTip property.
Note
A complete sample project is available at https://github.com/DevExpress-Examples/word-processing-document-api-examples-t418535
Document document = server.Document;
DocumentPosition hPos = server.Document.Range.Start;
server.Document.Hyperlinks.Create(document.InsertText(hPos, "Follow me!"));
document.Hyperlinks[0].NavigateUri = "https://www.devexpress.com/Products/NET/Controls/WinForms/Rich_Editor/";
document.Hyperlinks[0].ToolTip = "WinForms Rich Text Editor";
Create Bookmark
To create a bookmark, use the BookmarkCollection.Create method. It creates a Bookmark object with the specified name and range (or position) and adds it to the BookmarkCollection. Use the Document.Bookmark property to get access to the collection.
A bookmark can be referenced by a hyperlink. To do that, set the hyperlink’s Hyperlink.Anchor property to the corresponding bookmark name, as in the code snippet below.
Note
A complete sample project is available at https://github.com/DevExpress-Examples/word-processing-document-api-examples-t418535
server.LoadDocument("Documents\\Grimm.docx", DocumentFormat.OpenXml);
server.BeginUpdate();
Document document = server.Document;
DocumentPosition pos = document.Range.Start;
document.Bookmarks.Create(server.Document.CreateRange(pos, 0), "Top");
//Insert the hyperlink anchored to the created bookmark:
DocumentPosition pos1 = document.CreatePosition((server.Document.Range.End).ToInt() + 25);
document.Hyperlinks.Create(server.Document.InsertText(pos1, "get to the top"));
document.Hyperlinks[0].Anchor = "Top";
server.EndUpdate();