How to: Use Word Processing Document API to Convert a Static URI to a Hyperlink
- 3 minutes to read
The code sample below shows how to convert static URI to a hyperlink.
Call the SubDocument.StartSearch(Regex) method within the RichEditDocumentServer.DocumentLoaded event handler to find all URIs in a loaded document. If the found text is not a hyperlink (i.e., its range cannot be found in the HyperlinkCollection), call the HyperlinkCollection.Create(DocumentRange) method convert the text range to a hyperlink.
using DevExpress.XtraRichEdit;
using DevExpress.XtraRichEdit.API.Native;
using System;
using System.Text.RegularExpressions;
class Program
{
// A regular expression to find a static URI
private static Regex urlRegex =
new Regex(@"(?:[a-z][\w-]+:(?:/{1,3}([^./]*:[^./]*@){0,1})|www\d{0,3}[.]|ftp[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\([^\s<>]*\))+(?:\([^\s<>]*\)|[^\s`!()\[\]{};:'"".,<>?«»“”‘’])",
RegexOptions.IgnoreCase, TimeSpan.FromMilliseconds(250));
static void Main(string[] args)
{
using (var wordProcessor = new RichEditDocumentServer())
{
wordProcessor.DocumentLoaded += WordProcessor_DocumentLoaded;
// Load a document
wordProcessor.LoadDocument("Documents//test.docx");
//Save the result
wordProcessor.SaveDocument("Documents//hyperlinks.docx", DocumentFormat.OpenXml);
}
}
private static void WordProcessor_DocumentLoaded(object sender, EventArgs e)
{
// Convert text to hyperlinks in a loaded document
CreateHyperlinks(sender as RichEditDocumentServer);
}
private static void CreateHyperlinks(RichEditDocumentServer wordProcessor)
{
Document document = wordProcessor.Document;
// Start the document update
document.BeginUpdate();
IRegexSearchResult result;
// Search for URIs
result = document.StartSearch(urlRegex);
// Iterate search results
while (IsValidUri(result))
{
DocumentRange wordRange = result.CurrentResult;
// If the search result is not a hyperlink, convert
// the range to a hyperlink
if (!RangeHasHyperlink(wordRange, wordProcessor))
{
Hyperlink hyperlink = document.Hyperlinks.Create(wordRange);
// Use the found URI as the hyperlink address
hyperlink.NavigateUri = document.GetText(hyperlink.Range);
}
}
// Finalize the update
document.EndUpdate();
}
private static bool RangeHasHyperlink(DocumentRange documentRange, RichEditDocumentServer wordProcessor)
{
// Check whether the search result is already a hyperlink
foreach (Hyperlink h in wordProcessor.Document.Hyperlinks)
{
if (documentRange.Contains(h.Range.Start))
return true;
}
return false;
}
// Make sure that the application won't crash if the
// pattern-matching method execution exceeds its time-out interval
static bool IsValidUri(IRegexSearchResult result)
{
try
{
return result.FindNext();
}
catch (RegexMatchTimeoutException)
{
return false;
}
}
}