Document .Net - How to replace a hyperlink URL by a new address

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


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)
        {
            ReplaceHyperlinksURL();
            ReplaceHyperlinksByText();
        }

        /// <summary>
        /// How to replace a hyperlink URL by a new address.
        /// </summary>
        /// <remarks>
        /// Details: https://sautinsoft.com/products/document/examples/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/examples/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)
			ReplaceHyperlinksURL()
			ReplaceHyperlinksByText()
		End Sub

		''' <summary>
		''' How to replace a hyperlink URL by a new address.
		''' </summary>
		''' <remarks>
		''' Details: https://sautinsoft.com/products/document/examples/hyperlinks-replace-url-csharp-vb-net.php
		''' </remarks>		
		Public Shared Sub 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.

			Dim inpFile As String = "..\Hyperlinks example.docx"
			Dim outFile As String = "Result - URL.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)
				hpl.Address = customURL
			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 replace a hyperlink content and formatting. 
		''' </summary>
		''' <remarks>
		''' Details: https://sautinsoft.com/products/document/examples/hyperlinks-replace-url-csharp-vb-net.php
		''' </remarks>		
		Public Shared Sub 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.

			Dim inpFile As String = "..\Hyperlinks example.docx"
			Dim outFile As String = "Result - Replace By 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 "Inline" objects.
			For Each hpl As Hyperlink In dc.GetChildElements(True, ElementType.Hyperlink).Reverse()
				' Check that the Hyperlink is specified for a text element.
				If hpl.DisplayInlines IsNot Nothing AndAlso hpl.DisplayInlines.Count > 0 AndAlso TypeOf hpl.DisplayInlines(0) Is Run Then
					' 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 red font color, remove underline.
						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
				End If
			Next hpl

			' Save our 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.