Как заменить URL-адрес гиперссылки новым адресом в C# и .NET

  1. Добавьте SautinSoft.Document из Nuget.
  2. Загрузите документ DOCX.
  3. Найдите все гиперссылки.
  4. Замените адрес в гиперссылках.

Этот пример кода содержит два метода для работы с гиперссылками.

В первом случае мы должны заменить все URL-адреса гиперссылок пользовательскими.

Во втором методе мы заменяем все гиперссылки их текстом и сохраняем форматирование (меняем только цвет текста на красный).

Полный код

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


Если вам нужен пример кода или у вас есть вопрос: напишите нам по адресу support@sautinsoft.com или спросите в онлайн-чате (правый нижний угол этой страницы) или используйте форму ниже:



Вопросы и предложения всегда приветствуются!

Мы разрабатываем компоненты .Net с 2002 года. Мы знаем форматы PDF, DOCX, RTF, HTML, XLSX и Images. Если вам нужна помощь в создании, изменении или преобразовании документов в различных форматах, мы можем вам помочь. Мы напишем для вас любой пример кода абсолютно бесплатно.