Back to Devexpress

How to: Use Word Processing Document API to Convert a Static URI to a Hyperlink

officefileapi-403676-word-processing-document-api-examples-document-elements-how-to-convert-static-uri-to-hyperlink.md

latest6.4 KB
Original Source

How to: Use Word Processing Document API to Convert a Static URI to a Hyperlink

  • Feb 21, 2025
  • 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.

csharp
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.Docx);
    }
  }

  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;
     }
  }
}
vb
Imports DevExpress.XtraRichEdit
Imports DevExpress.XtraRichEdit.API.Native
Imports System
Imports System.Text.RegularExpressions

Friend Class Program
  ' A regular expression to find a static URI
  Private Shared urlRegex As 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))

  Shared Sub Main(ByVal args() As String)
      Using wordProcessor = New RichEditDocumentServer()
          AddHandler wordProcessor.DocumentLoaded, AddressOf WordProcessor_DocumentLoaded

          ' Load a document
          wordProcessor.LoadDocument("Documents//test.docx")

          'Save the result
          wordProcessor.SaveDocument("Documents//hyperlinks.docx", DocumentFormat.Docx)
      End Using
  End Sub

  Private Shared Sub WordProcessor_DocumentLoaded(ByVal sender As Object, ByVal e As EventArgs)
      ' Convert text to hyperlinks in a loaded document
      CreateHyperlinks(TryCast(sender, RichEditDocumentServer))
  End Sub

  Private Shared Sub CreateHyperlinks(ByVal wordProcessor As RichEditDocumentServer)
      Dim document As Document = wordProcessor.Document

      ' Start the document update
      document.BeginUpdate()
      Dim result As IRegexSearchResult

      ' Search for URIs
      result = document.StartSearch(urlRegex)

      ' Iterate search results
      Do While IsValidUri(result)
          Dim wordRange As DocumentRange = result.CurrentResult
          ' If the search result is not a hyperlink, convert 
          ' the range to a hyperlink
          If Not RangeHasHyperlink(wordRange, wordProcessor) Then
              Dim hyperlink As Hyperlink = document.Hyperlinks.Create(wordRange)
              ' Use the found URI as the hyperlink address
              hyperlink.NavigateUri = document.GetText(hyperlink.Range)
          End If
      Loop
      ' Finalize the update
      document.EndUpdate()
  End Sub

  Private Shared Function RangeHasHyperlink(ByVal documentRange As DocumentRange, ByVal wordProcessor As RichEditDocumentServer) As Boolean
      ' Check whether the search result is already a hyperlink
      For Each h As Hyperlink In wordProcessor.Document.Hyperlinks
          If documentRange.Contains(h.Range.Start) Then
              Return True
          End If
      Next h

      Return False
  End Function

  ' Make sure that the application won't crash if the
  ' pattern-matching method execution exceeds its time-out interval
  Private Shared Function IsValidUri(ByVal result As IRegexSearchResult) As Boolean
      Try
          Return result.FindNext()
      Catch e1 As RegexMatchTimeoutException
          Return False
      End Try
  End Function
End Class