How to replace a hyperlink URL by a new address in C# and .NET

  1. Add SautinSoft.Document from Nuget.
  2. Load a DOCX document.
  3. Find all hyperlinks.
  4. Replace the address in the hyperlinks.

This code example contains two methods for working with hyperlinks.

In the first case we've to replace all hyperlink URLs by the custom.

In the second method we replace all hyperlinks by their text and keep formatting (change only text color to red).

Complete code

using System.Text;
using System.Linq;
using SautinSoft.Document;

namespace Sample
{
    class Sample
    {
        static void Main(string[] args)
        {
            // Get your free 100-day key here:   
            // https://sautinsoft.com/start-for-free/

            ReplaceHyperlinksURL();
            ReplaceHyperlinksByText();
        }

        /// <summary>
        /// How to replace a hyperlink URL by a new address.
        /// </summary>
        /// <remarks>
        /// Details: https://sautinsoft.com/products/document/help/net/developer-guide/hyperlinks-replace-url-csharp-vb-net.php
        /// </remarks>		
        public static void ReplaceHyperlinksURL()
        {
            // Let us say, we've a DOCX document.
            // And we've to replace the all URLs by the custom.
            // Furthermore, let's save the result as PDF.

            string inpFile = @"..\..\..\Hyperlinks example.docx";
            string outFile = @"Result - URL.pdf";

            // Let's open our document.
            DocumentCore dc = DocumentCore.Load(inpFile);

            // Specify the custom URL.
            string customURL = "https://www.sautinsoft.com";

            // Loop by all hyperlinks and replace the URL (address).
            foreach (Hyperlink hpl in dc.GetChildElements(true, ElementType.Hyperlink))
            {
                hpl.Address = customURL;
            }

            // Save our document back, but in PDF format.
            dc.Save(outFile, new PdfSaveOptions() { Compliance = PdfCompliance.PDF_14 });

            // Open the result for demonstration purposes.
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(outFile) { UseShellExecute = true });
        }
        /// <summary>
        /// How to replace a hyperlink content and formatting. 
        /// </summary>
        /// <remarks>
        /// Details: https://sautinsoft.com/products/document/help/net/developer-guide/hyperlinks-replace-url-csharp-vb-net.php
        /// </remarks>		
        public static void ReplaceHyperlinksByText()
        {
            // Let us say, we've a DOCX document.
            // And we need to replace all hyperlinks by their text, color this text by red.
            // Also we have to preserve the rest formatting: font family, size and so on.

            string inpFile = @"..\..\..\Hyperlinks example.docx";
            string outFile = @"Result - Replace By Text.docx";

            // Let's open our document.
            DocumentCore dc = DocumentCore.Load(inpFile);

            // Loop by all hyperlinks in a reverse, to remove the "Hyperlink" objects 
            // and replace them by "Inline" objects.
            foreach (Hyperlink hpl in dc.GetChildElements(true, ElementType.Hyperlink).Reverse())
            {
                // Check that the Hyperlink is specified for a text element.
                if (hpl.DisplayInlines != null && hpl.DisplayInlines.Count > 0 && hpl.DisplayInlines[0] is Run)
                {
                    // Get the "Hyperlink" index in the parent collection.
                    InlineCollection parentCollection = hpl.ParentCollection;
                    int index = parentCollection.IndexOf(hpl);

                    // Get the "Hyperlink" text as the Inline collection.
                    InlineCollection textInlines = hpl.DisplayInlines;

                    // Remove the "Hyperlink" object from the parent collection by index.
                    parentCollection.RemoveAt(index);

                    // Insert the text (collection of Inlines) instead of the removed "Hyperlink" object 
                    // into the parent collection.
                    for (int i = 0; i < textInlines.Count; i++)
                    {
                        // Set the red font color, remove underline.
                        if (textInlines[i] is Run)
                        {
                            (textInlines[i] as Run).CharacterFormat.FontColor = Color.Red;
                            (textInlines[i] as Run).CharacterFormat.UnderlineStyle = UnderlineType.None;
                        }
                        parentCollection.Insert(index + i, textInlines[i].Clone(true));
                    }
                }
            }

            // Save our document back.
            dc.Save(outFile);

            // Open the result for demonstration purposes.
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(outFile) { UseShellExecute = true });
        }
    }
}

Download

Imports System.Text
Imports System.Linq
Imports SautinSoft.Document

Namespace Sample
	Friend Class Sample
		Shared Sub Main(ByVal args() As String)
			DeleteHyperlinksObjects()
			DeleteHyperlinksURL()
		End Sub
                ''' Get your free 100-day key here:   
                ''' https://sautinsoft.com/start-for-free/
		''' <summary>
		''' How to delete all hyperlink objects.
		''' </summary>
		''' <remarks>
		''' Details: https://sautinsoft.com/products/document/help/net/developer-guide/hyperlinks-delete-url-csharp-vb-net.php
		''' </remarks>		
		Public Shared Sub DeleteHyperlinksObjects()
			' Let us say, we've a DOCX document.
			' And we've to remove the hyperlink objects.

			Dim inpFile As String = "..\..\..\Hyperlinks example.docx"
			Dim outFile As String = "Result - Delete Hyperlinks completely.pdf"

			' Let's open our document.
			Dim dc As DocumentCore = DocumentCore.Load(inpFile)

			' Specify the custom URL.
			Dim customURL As String = "https://www.sautinsoft.com"

			' Loop by all hyperlinks and replace the URL (address).
			For Each hpl As Hyperlink In dc.GetChildElements(True, ElementType.Hyperlink).Reverse()
				hpl.ParentCollection.Remove(hpl)
			Next hpl

			' Save our document back, but in PDF format.
			dc.Save(outFile, New PdfSaveOptions() With {.Compliance = PdfCompliance.PDF_14})

			' Open the result for demonstration purposes.
			System.Diagnostics.Process.Start(New System.Diagnostics.ProcessStartInfo(outFile) With {.UseShellExecute = True})
		End Sub
		''' <summary>
		''' How to delete all hyperlinks and leave only their text.
		''' </summary>
		''' <remarks>
		''' Details: https://sautinsoft.com/products/document/help/net/developer-guide/hyperlinks-delete-url-csharp-vb-net.php
		''' </remarks>		
		Public Shared Sub DeleteHyperlinksURL()
			' Let us say, we've a DOCX document.
			' And we've to remove all hyperlinks, leave only their text.

			' Note, we can't make the property 'Hyperlink.Address' empty, this is not allowed.
			' Therefore we have to remove the all 'Hyperlinks' object and 
			' insert the text objects 'Inline' instead of them.

			Dim inpFile As String = "..\..\..\Hyperlinks example.docx"
			Dim outFile As String = "Result - delete links and leave text.docx"

			' Let's open our document.
			Dim dc As DocumentCore = DocumentCore.Load(inpFile)

			' Loop by all hyperlinks in a reverse, to remove the "Hyperlink" objects 
			' and replace them by their text ("Inline" objects).
			For Each hpl As Hyperlink In dc.GetChildElements(True, ElementType.Hyperlink).Reverse()
				' Get the "Hyperlink" index in the parent collection.
				Dim parentCollection As InlineCollection = hpl.ParentCollection
				Dim index As Integer = parentCollection.IndexOf(hpl)

				' Get the "Hyperlink" text as the Inline collection.
				Dim textInlines As InlineCollection = hpl.DisplayInlines

				' Remove the "Hyperlink" object from the parent collection by index.
				parentCollection.RemoveAt(index)

				' Insert the text (collection of Inlines) instead of the removed "Hyperlink" object 
				' into the parent collection.
				For i As Integer = 0 To textInlines.Count - 1
					' Set the Auto font color (Black for the most cases) and remove the underline.
					' Hide these lines if you want to leave the formatting the same as the hyperlink had.
					If TypeOf textInlines(i) Is Run Then
						TryCast(textInlines(i), Run).CharacterFormat.FontColor = Color.Red
						TryCast(textInlines(i), Run).CharacterFormat.UnderlineStyle = UnderlineType.None
					End If
					parentCollection.Insert(index + i, textInlines(i).Clone(True))
				Next i
			Next hpl
			' Save the document back.
			dc.Save(outFile)

			' Open the result for demonstration purposes.
			System.Diagnostics.Process.Start(New System.Diagnostics.ProcessStartInfo(outFile) With {.UseShellExecute = True})
		End Sub
	End Class
End Namespace

Download


If you need a new code example or have a question: email us at support@sautinsoft.com or ask at Online Chat (right-bottom corner of this page) or use the Form below:



Questions and suggestions from you are always welcome!

We are developing .Net components since 2002. We know PDF, DOCX, RTF, HTML, XLSX and Images formats. If you need any assistance with creating, modifying or converting documents in various formats, we can help you. We will write any code example for you absolutely free.