Как удалить все объекты гиперссылок в C# и .NET

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

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

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

Во втором методе мы удаляем все гиперссылки, но сохраняем только их текст.

Полный код

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/

            DeleteHyperlinksObjects();
            DeleteHyperlinksURL();
        }

        /// <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 static void DeleteHyperlinksObjects()
        {
            // Let us say, we've a DOCX document.
            // And we've to remove the hyperlink objects.

            string inpFile = @"..\..\..\Hyperlinks example.docx";
            string outFile = @"Result - Delete Hyperlinks completely.pdf";
           
            // Let's open our document.
            DocumentCore dc = DocumentCore.Load(inpFile);

            // Loop by all hyperlinks and replace the URL (address).
            foreach (Hyperlink hpl in dc.GetChildElements(true, ElementType.Hyperlink).Reverse())
                hpl.ParentCollection.Remove(hpl);

            // 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 delete all hyperlinks but preserve only their text.
        /// </summary>
        /// <remarks>
        /// Details: https://sautinsoft.com/products/document/help/net/developer-guide/hyperlinks-delete-url-csharp-vb-net.php
        /// </remarks>		
        public static void DeleteHyperlinksURL()
        {
            // Let us say, we've a DOCX document.
            // And we've to remove all hyperlinks, preserve 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.

            string inpFile = @"..\..\..\Hyperlinks example.docx";
            string outFile = @"Result - delete links and preserve 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 their text ("Inline" objects).
            foreach (Hyperlink hpl in dc.GetChildElements(true, ElementType.Hyperlink).Reverse())
            {
                // 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 Auto font color (Black for the most cases) and remove the underline.
                    // Hide these lines if you want to preserve the formatting the same as the hyperlink had.
                    if (textInlines[i] is Run)
                    {
                        (textInlines[i] as Run).CharacterFormat.FontColor = Color.Auto;
                        (textInlines[i] as Run).CharacterFormat.UnderlineStyle = UnderlineType.None;
                    }
                    parentCollection.Insert(index + i, textInlines[i].Clone(true));
                }
            }
            // Save the 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)

			' 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 but preserve 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, preserve 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 preserve 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 preserve the formatting the same as the hyperlink had.
					If TypeOf textInlines(i) Is Run Then
						TryCast(textInlines(i), Run).CharacterFormat.FontColor = Color.Auto
						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


Если вам нужен пример кода или у вас есть вопрос: напишите нам по адресу [email protected] или спросите в онлайн-чате (правый нижний угол этой страницы) или используйте форму ниже:



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

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