Manage Hyperlinks and Bookmarks
- 8 minutes to read
A hyperlink opens a web page, a file, or a new email message. A hyperlink can also navigate to a bookmark in a document. A bookmark is a named document range (for example, a section heading that a table of contents entry references).
The Word Processing Document API stores hyperlinks as Hyperlink objects and bookmarks as Bookmark objects.
Insert a Hyperlink
To insert a hyperlink, create a Hyperlink object, specify the hyperlink destination, and add the object to the Paragraph.InlineElements collection. To insert a hyperlink at a position in document text, call the DocumentFragment.Insert(position, inline) method.
The following code snippet creates a document with hyperlinks to a web page and an email address:
using System.IO;
using DevExpress.Docs.Word;
using var document = new WordDocument();
// Add a hyperlink to a web page.
var paragraph = document.Body.AddParagraph("For product updates, visit the ");
paragraph.InlineElements.Add(new Hyperlink("DevExpress website")
{
Uri = "https://www.devexpress.com",
ToolTip = "Open the DevExpress website",
Target = "_blank"
});
paragraph.AddText(".");
// Add a hyperlink to an email address.
paragraph = document.Body.AddParagraph("Send questions to ");
paragraph.InlineElements.Add(new Hyperlink("our support team") { Uri = "mailto:support@example.com" });
paragraph.AddText(".");
Directory.CreateDirectory("output");
using var stream = File.Create(Path.Combine("output", "Document.docx"));
document.Save(stream, DocumentFormat.Docx);
Use the following properties to specify the hyperlink destination, content, and behavior:
| Property | Description |
|---|---|
| Uri | Specifies the URI of the linked web page or file, or an email address (for example, https://www.devexpress.com or mailto:support@example.com). |
| Anchor | Specifies the name of the bookmark to which the hyperlink navigates. |
| Target | Specifies the window or frame where a web browser opens the linked page (for example, _blank for a new window). |
| ToolTip | Specifies the text that a document viewer displays when a user hovers the mouse pointer over the hyperlink. |
| DisplayText | Specifies the hyperlink text if the hyperlink content consists of a single text fragment. |
| Content | Contains document elements that the document displays as the hyperlink (for example, text fragments). |
To link to a bookmark in the current document, specify the Anchor property only. If you specify Uri and Anchor properties, the hyperlink navigates to the bookmark in the linked document.
The API stores a hyperlink as a HYPERLINK field. Uri, Anchor, Target, and ToolTip properties specify the field code. The Content collection contains the field result.
Hyperlink Content
The Hyperlink.Content collection contains document elements that the document displays as the hyperlink. To display text fragments with different formatting settings in a hyperlink, add text fragments to the Content collection. The API does not apply the Hyperlink style to elements that you add to the Content collection.
If the Content collection contains a single text fragment, the Hyperlink.DisplayText property returns the fragment text. Otherwise, the DisplayText property returns null. Call the Hyperlink.GetText() method to get the text of all elements in the Content collection.
To customize the appearance of hyperlinks that use the Hyperlink style, retrieve the style from the WordDocument.CharacterStyles collection by name and modify the style settings.
Find and Modify Hyperlinks
To find hyperlinks in a document, iterate through inline elements in document paragraphs. Paragraphs can be in the document body, table cells, headers, footers, comments, and text boxes.
The following code snippet writes the text, URI, and bookmark name of each hyperlink in the document body to the console and replaces the domain name in hyperlink URIs:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using DevExpress.Docs.Word;
using var document = new WordDocument(File.ReadAllBytes("Document.docx"));
foreach (var hyperlink in GetHyperlinks(document.Body))
{
Console.WriteLine($"{hyperlink.GetText()} | URI: {hyperlink.Uri} | Bookmark: {hyperlink.Anchor}");
if (!string.IsNullOrEmpty(hyperlink.Uri))
hyperlink.Uri = hyperlink.Uri.Replace("www.example.com", "portal.example.com");
}
Directory.CreateDirectory("output");
using var stream = File.Create(Path.Combine("output", "Document.docx"));
document.Save(stream, DocumentFormat.Docx);
// Get hyperlinks from paragraphs and table cells.
static IEnumerable<Hyperlink> GetHyperlinks(IEnumerable<Block> blocks)
{
foreach (var block in blocks)
{
if (block is Paragraph paragraph)
{
foreach (var hyperlink in paragraph.InlineElements.OfType<Hyperlink>())
yield return hyperlink;
}
else if (block is Table table)
{
foreach (var row in table.Rows)
foreach (var cell in row.Cells)
foreach (var hyperlink in GetHyperlinks(cell.Content))
yield return hyperlink;
}
}
}
Remove Hyperlinks
To remove a hyperlink and the hyperlink text, call the InlineElementCollection.Remove(item) method.
To remove a hyperlink and keep the hyperlink text, replace the Hyperlink object in the Paragraph.InlineElements collection with a TextFragment object that contains the hyperlink text. Use the InlineElementCollection[index] indexer to replace the element.
The following code snippet replaces hyperlinks in document body paragraphs with plain text:
using System.IO;
using System.Linq;
using DevExpress.Docs.Word;
using var document = new WordDocument(File.ReadAllBytes("Document.docx"));
foreach (var paragraph in document.Body.OfType<Paragraph>())
{
foreach (var hyperlink in paragraph.InlineElements.OfType<Hyperlink>().ToList())
{
var index = paragraph.InlineElements.IndexOf(hyperlink);
paragraph.InlineElements[index] = new TextFragment(hyperlink.GetText());
}
}
Directory.CreateDirectory("output");
using var stream = File.Create(Path.Combine("output", "Document.docx"));
document.Save(stream, DocumentFormat.Docx);
Create a Bookmark and Link to It
To create a bookmark, call the BookmarkCollection.Create(range, name) method for the WordDocument.Bookmarks collection. To create a bookmark for a document element (for example, a paragraph), pass the range returned by the DocumentFragment.GetRange(element) method to the Create method.
Note: Bookmark names must be unique in a document.
To create a hyperlink that navigates to the bookmark, set the Hyperlink.Anchor property to the bookmark name.
The following code snippet creates a bookmark for a heading and adds a hyperlink that navigates to the bookmark:
using System.IO;
using DevExpress.Docs.Word;
using var document = new WordDocument();
var intro = document.Body.AddParagraph("For quarter results, refer to the ");
var heading = document.Body.AddParagraph("Summary");
document.Body.AddParagraph("The project remains on schedule and within budget.");
// Create a bookmark for the heading.
var bookmark = document.Bookmarks.Create(document.Body.GetRange(heading), "Summary");
// Add a hyperlink that navigates to the bookmark.
intro.InlineElements.Add(new Hyperlink("Summary") { Anchor = bookmark.Name });
intro.AddText(" section.");
Directory.CreateDirectory("output");
using var stream = File.Create(Path.Combine("output", "Document.docx"));
document.Save(stream, DocumentFormat.Docx);
Access, Rename, and Remove Bookmarks
Use the following members to manage bookmarks:
| Member | Description |
|---|---|
| BookmarkCollection[name] | Gets the bookmark with the specified name, or null if the document does not contain the bookmark. |
| Name | Specifies the bookmark name. |
| Range | Specifies the document range of the bookmark. Assign a new range to move the bookmark. Pass the range to the DocumentFragment.GetText(range) method to get the bookmark text. |
| BookmarkCollection.Remove(bookmark) | Removes the bookmark and keeps the bookmark text. |
Note
If you rename or remove a bookmark, the API does not update hyperlinks that navigate to the bookmark. Update the Hyperlink.Anchor property of affected hyperlinks.
The following code snippet writes the name and text of each bookmark to the console, renames the ExecutiveSummary bookmark, and updates hyperlinks that navigate to the bookmark:
using System;
using System.IO;
using System.Linq;
using DevExpress.Docs.Word;
using var document = new WordDocument(File.ReadAllBytes("Document.docx"));
foreach (var bookmark in document.Bookmarks)
Console.WriteLine($"{bookmark.Name}: {bookmark.DocumentFragment.GetText(bookmark.Range)}");
document.Bookmarks["ExecutiveSummary"].Name = "Summary";
foreach (var paragraph in document.Body.OfType<Paragraph>())
foreach (var hyperlink in paragraph.InlineElements.OfType<Hyperlink>().Where(h => h.Anchor == "ExecutiveSummary"))
hyperlink.Anchor = "Summary";