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/winforms-richedit-document-api-e5219
DocumentPosition hPos = document.Range.Start;
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/winforms-richedit-document-api-e5219
document.LoadDocument("Grimm.docx",DocumentFormat.OpenXml);
document.BeginUpdate();
DocumentPosition pos = document.Range.Start;
document.Bookmarks.Create(document.CreateRange(pos, 0), "Top");
//Insert the hyperlink anchored to the created bookmark:
DocumentPosition pos1 = document.CreatePosition((document.Range.End).ToInt()+25);
document.Hyperlinks.Create(document.InsertText(pos1, "get to the top"));
document.Hyperlinks[0].Anchor = "Top";
document.EndUpdate();