Hyperlink
Hyperlink

Hyperlink (9)

When working with Word documents, batch extraction of hyperlinks has significant practical applications. Manually extracting URLs from technical documents or product manuals is not only inefficient but also prone to omissions and errors. To address this, this article presents an automated solution using C# to accurately extract hyperlink anchor text, corresponding URLs, and screen tips by parsing document elements. The extracted hyperlink data can support data analysis, SEO optimization, and other applications. The following sections demonstrate how to use Spire.Doc for .NET to extract hyperlinks from a Word document with C# code in .NET programs.

Install Spire.Doc for .NET

To begin with, you need to add the DLL files included in the Spire.Doc for .NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.

PM> Install-Package Spire.Doc

Extracting All Hyperlinks from a Word Document Using C#

In a Word document, hyperlinks are stored as fields. To extract them, the first step is to identify all field objects by checking whether each document object is an instance of the Field class. Then, by checking whether the field object's Type property equals FieldType.FieldHyperlink, we can extract all hyperlink fields.

Once the hyperlinks are identified, we can use the Field.FieldText property to retrieve the hyperlink anchor text and the Field.GetFieldCode() method to obtain the full field code in the following format:

Hyperlink Type Field Code Example
Standard Hyperlink HYPERLINK "https://www.example.com/example"
Hyperlink with ScreenTip HYPERLINK "https://www.example.com/example" \o "ScreenTip"

By parsing the field code, we can extract both the hyperlink URL and the screen tip text, enabling complete retrieval of hyperlink information.

  • Create a Document object and use the Document.LoadFromFile() method to load the target Word document.
  • Iterate through all sections in the document using foreach (Section section in doc.Sections) to retrieve each section object.
  • For each section, iterate through its child objects using foreach (DocumentObject secObj in section.Body.ChildObjects) to access individual elements.
  • If a child object is of type Paragraph:
    • Iterate through the child objects within the paragraph using foreach (DocumentObject paraObj in paragraph.ChildObjects).
  • If a paragraph child object is of type Field and its Field.Type property value equals FieldType.FieldHyperlink, process the Field object.
  • For each Field object:
    • Extract the anchor text using the Field.FieldText property.
    • Retrieve the field code string using the Field.GetFieldCode() method.
  • Process the field code string:
    • Extract the URL enclosed in quotation marks after "HYPERLINK".
    • Check if the field code contains the \o parameter; if present, extract the screen tip text enclosed in double quotes.
  • Store the extracted hyperlinks and write them to an output file.
  • C#
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;

namespace ExtractWordHyperlink
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create an instance of Document
            Document doc = new Document();
            // Load a Word document
            doc.LoadFromFile("Sample.docx");

            // Create a string list to store the hyperlink information
            List<string> hyperlinkInfoList = new List<string>();

            // Iterate through the sections in the document
            foreach (Section section in doc.Sections)
            {
                // Iterate through the child objects in the section
                foreach (DocumentObject secObj in section.Body.ChildObjects)
                {
                    // Check if the current document object is a Paragraph instance
                    if (secObj is Paragraph paragraph )
                    {
                        // Iterate through the child objects in the paragraph
                        foreach (DocumentObject paraObj in paragraph.ChildObjects)
                        {
                            // Check if the current child object is a field
                            if (paraObj is Field field && field.Type == FieldType.FieldHyperlink)
                            {
                                string hyperlinkInfo = "";
                                // Get the anchor text
                                string anchorText = field.FieldText;

                                // Get the field code
                                string fieldCode = field.GetFieldCode();
                                // Get the URL from the field code
                                string url = fieldCode.Split('"')[1];
                                // Check if there is a ScreenTip
                                if (fieldCode.Contains("\\o"))
                                {
                                    // Get the ScreenTip text
                                    string screenTip = fieldCode.Split("\"")[3].Trim();
                                    // Consolidate the information
                                    hyperlinkInfo += $"Anchor Text: {anchorText}\nURL: {url}\nScreenTip: {screenTip}";
                                }
                                else
                                {
                                    hyperlinkInfo += $"Anchor Text: {anchorText}\nURL: {url}";
                                }
                                hyperlinkInfo += "\n";
                                // Append the hyperlink information to the list
                                hyperlinkInfoList.Add(hyperlinkInfo);

                            }
                        }
                    }
                }
            }

            // Write the extracted hyperlink information to a text file
            File.WriteAllLines("output/ExtractedHyperlinks.txt", hyperlinkInfoList);

            doc.Close();
        }
    }
}

Hyperlinks Extracted from Word Documents Using C#

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

In Word documents, hyperlinks can be added to images and shapes to link to external websites, files, or specific sections within the document. However, over time, the destination URLs or file paths may change due to updates in external resources or reorganization of the document. When this happens, it’s important to update the hyperlinks to ensure they continue to point to the correct locations. For example, if a website's URL changes, an image is moved to a new folder or a linked shape needs to connect to a different page, updating the hyperlinks is crucial to keep the document functional and user-friendly.

In this article, we will introduce how to programmatically update hyperlinks for images and shapes in Word documents in C# using Spire.Doc for .NET.

Install Spire.Doc for .NET

To begin with, you need to add the DLL files included in the Spire.Doc for .NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.

PM> Install-Package Spire.Doc

Update Hyperlinks for Images in Word in C#

Spire.Doc for .NET offers the DocPicture.HasHyperlink property which allows you to identify if an image contains a hyperlink. Once identified, you can use the DocPicture.HRef property to seamlessly update or modify the hyperlink as needed. The detailed steps are as follows.

  • Create an instance of the Document class.
  • Load a Word document using the Document.LoadFromFile() method.
  • Iterate through all sections in the document, all paragraphs in each section, and all objects in each paragraph.
  • Check if the object is a DocPicture.
  • Check if the DocPicture object has a hyperlink using the DocPicture.HasHyperlink property.
  • Modify the hyperlink of the DocPicture object using the DocPicture.HRef property.
  • Save the modified document using the Document.SaveToFile() method.
  • C#
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;

namespace UpdateHyperlinkForImage
{
    internal class Program
    {
        static void Main(string[] args) 
        {       
            // Create a Document instance
            Document doc = new Document();
            // Load a Word document
            doc.LoadFromFile("Sample1.docx");

            // Iterate through all sections in the document
            foreach (Section section in doc.Sections)
            {
                // Iterate through all paragraphs in the section
                foreach (Paragraph paragraph in section.Paragraphs)
                {
                    // Iterate through all objects in the paragraph
                    foreach (DocumentObject documentObject in paragraph.ChildObjects)
                    {
                        // Check if the object is a DocPicture (image)
                        if (documentObject is DocPicture)
                        {
                            DocPicture pic = documentObject as DocPicture;
                            // Check if the DocPicture object has a hyperlink
                            if (pic.HasHyperlink)
                            {
                                // Update the hyperlink (if you want to remove the hyperlink, set the value to null) 
                                pic.HRef = "https://www.e-iceblue.com/";

                            }
                        }
                    }
                }
            }

            // Save the modified document
            doc.SaveToFile("UpdateImageHyperlink.docx", FileFormat.Docx2016);
            doc.Close();
        }
    }
}

Update Hyperlinks for Images in Word in C#

Update Hyperlinks for Shapes in Word in C#

Similarly, you can check if a shape has a hyperlink using the ShapeObject.HasHyperlink property, and update or modify the hyperlink with the ShapeObject.HRef property. The detailed steps are as follows.

  • Create an instance of the Document class.
  • Load a Word document using the Document.LoadFromFile() method.
  • Iterate through all sections in the document, all paragraphs in each section, and all objects in each paragraph.
  • Check if the object is a ShapeObject.
  • Check if the ShapeObject object has a hyperlink using the ShapeObject.HasHyperlink property.
  • Modify the hyperlink of the ShapeObject object using the ShapeObject.HRef property.
  • Save the modified document using the Document.SaveToFile() method.
  • C#
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;

namespace UpdateHyperlinkForShape
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // Create a Document instance
            Document doc = new Document();
            // Load a Word document
            doc.LoadFromFile("Sample2.docx");

            // Iterate through all sections in the document
            foreach (Section section in doc.Sections)
            {
                // Iterate through all paragraphs in the section
                foreach (Paragraph paragraph in section.Paragraphs)
                {
                    // Iterate through all objects in the paragraph
                    foreach (DocumentObject documentObject in paragraph.ChildObjects)
                    {
                        // Check if the object is a ShapeObject
                        if (documentObject is ShapeObject)
                        {
                            ShapeObject shape = documentObject as ShapeObject;
                            // Check if the shape has a hyperlink
                            if (shape.HasHyperlink)
                            {
                                // Update the hyperlink (if you want to remove the hyperlink, set the value to null) 
                                shape.HRef = "https://www.e-iceblue.com/";
                            }
                        }
                    }
                }
            }

            // Save the modified document
            doc.SaveToFile("UpdateShapeHyperlink.docx", FileFormat.Docx2016);
            doc.Close();
        }
    }
}

Update Hyperlinks for Shapes in Word in C#

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

This article shows you how to create a hyperlink to a bookmark within the same Word document by using Spire.Doc with C# and VB.NET.

C#
using Spire.Doc;
using Spire.Doc.Documents;

namespace LinkToBookmark
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a Document object
            Document doc = new Document();

            //Add two sections
            Section section1 = doc.AddSection();
            Section section2 = doc.AddSection();

            //Insert a paragraph in section 2 and add a bookmark named "myBookmark" to it
            Paragraph bookmarkParagrapg = section2.AddParagraph();
            bookmarkParagrapg.AppendText("Here is a bookmark");
            BookmarkStart start = bookmarkParagrapg.AppendBookmarkStart("myBookmark");
            bookmarkParagrapg.Items.Insert(0, start);
            bookmarkParagrapg.AppendBookmarkEnd("myBookmark");

            //Link to the bookmark
            Paragraph paragraph = section1.AddParagraph();
            paragraph.AppendText("Link to a bookmark: ");
            paragraph.AppendHyperlink("myBookmark", "Jump to a location in this document", HyperlinkType.Bookmark);

            //Save to file
            doc.SaveToFile("LinkToBookmark.docx", FileFormat.Docx2013);
        }
    }
}
VB.NET
Imports Spire.Doc
Imports Spire.Doc.Documents

Namespace LinkToBookmark
    Class Program
        Shared  Sub Main(ByVal args() As String)
            'Create a Document object
            Document doc = New Document()
 
            'Add two sections
            Dim section1 As Section = doc.AddSection()
            Dim section2 As Section = doc.AddSection()
 
            'Insert a paragraph in section 2 and add a bookmark named "myBookmark" to it
            Dim bookmarkParagrapg As Paragraph = section2.AddParagraph()
            bookmarkParagrapg.AppendText("Here is a bookmark")
            Dim start As BookmarkStart = bookmarkParagrapg.AppendBookmarkStart("myBookmark")
            bookmarkParagrapg.Items.Insert(0, start)
            bookmarkParagrapg.AppendBookmarkEnd("myBookmark")
 
            'Link to the bookmark
            Dim paragraph As Paragraph = section1.AddParagraph()
            paragraph.AppendText("Link to a bookmark: ")
            paragraph.AppendHyperlink("myBookmark", "Jump to a location in this document", HyperlinkType.Bookmark)
 
            'Save to file
            doc.SaveToFile("LinkToBookmark.docx", FileFormat.Docx2013)
        End Sub
    End Class
End Namespace

Link to a Bookmark in a Word Document in C#/VB.NET

With linked images, you can direct users to a URL when they click the image. This article will show you how to create image hyperlinks in a Word document by using Spire.Doc.

Step 1: Create a Word document, add a section and a paragraph.

Document doc = new Document();
Section section = doc.AddSection();
Paragraph paragraph = section.AddParagraph();

Step 2: Load an image to a DocPicture object.

DocPicture picture = new DocPicture(doc);
picture.LoadImage(Image.FromFile("logo.png"));

Step 3: Add an image hyperlink to the paragraph.

paragraph.AppendHyperlink("www.e-iceblue.com", picture, HyperlinkType.WebLink);

Step 4: Save the file.

doc.SaveToFile("output.docx", FileFormat.Docx);

Output:

Create an Image Hyperlink in Word in C#, VB.NET

Full Code:

[C#]
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using System.Drawing;
namespace CreateLink
{
    class Program
    {

        static void Main(string[] args)
        {

            Document doc = new Document();
            Section section = doc.AddSection();

            Paragraph paragraph = section.AddParagraph();
            Image image = Image.FromFile("logo.png");
            DocPicture picture = new DocPicture(doc);
            picture.LoadImage(image);
            paragraph.AppendHyperlink("www.e-iceblue.com", picture, HyperlinkType.WebLink);

            doc.SaveToFile("output.docx", FileFormat.Docx);
        }
    }
}
[VB.NET]
Imports Spire.Doc
Imports Spire.Doc.Documents
Imports Spire.Doc.Fields
Imports System.Drawing
Namespace CreateLink
	Class Program

		Private Shared Sub Main(args As String())

			Dim doc As New Document()
			Dim section As Section = doc.AddSection()

			Dim paragraph As Paragraph = section.AddParagraph()
			Dim image__1 As Image = Image.FromFile("logo.png")
			Dim picture As New DocPicture(doc)
			picture.LoadImage(image__1)
			paragraph.AppendHyperlink("www.e-iceblue.com", picture, HyperlinkType.WebLink)

			doc.SaveToFile("output.docx", FileFormat.Docx)
		End Sub
	End Class
End Namespace

Hyperlinks in Word documents are clickable links that allow readers to navigate to a website or another document. While hyperlinks can provide valuable supplemental information, sometimes they can also be distracting or unnecessarily annoying, so you may want to remove them. In this article, you will learn how to remove hyperlinks from a Word document in C# and VB.NET using Spire.Doc for .NET.

Install Spire.Doc for .NET

To begin with, you need to add the DLL files included in the Spire.Doc for.NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.

PM> Install-Package Spire.Doc

Remove All the Hyperlinks in a Word Document

To delete all hyperlinks in a Word document at once, you'll need to find all the hyperlinks in the document and then create a custom method FlattenHyperlinks() to flatten them. The following are the detailed steps.

  • Create a Document object.
  • Load a sample Word document using Document.LoadFromFile() method.
  • Find all the hyperlinks in the document using custom method FindAllHyperlinks().
  • Loop through the hyperlinks and flatten all of them using custom method FlattenHyperlinks().
  • Save the result document using Document.SaveToFile() method.
  • C#
  • VB.NET
using System.Drawing;
using Spire.Doc;
using Spire.Doc.Documents;
using System.Collections.Generic;
using Spire.Doc.Fields;


namespace removeWordHyperlink
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a Document instance
            Document doc = new Document();

            //Load a sample Word document
            doc.LoadFromFile("Hyperlink.docx");

            //Find all hyperlinks
            List<Field> hyperlinks = FindAllHyperlinks(doc);

            //Flatten all hyperlinks
            for (int i = hyperlinks.Count - 1; i >= 0; i--)
            {
                FlattenHyperlinks(hyperlinks[i]);
            }

            //Save the result document
            doc.SaveToFile("RemoveHyperlinks.docx", FileFormat.Docx);

        }

        //Create a method FindAllHyperlinks() to get all the hyperlinks from the sample document
        private static List<Field> FindAllHyperlinks(Document document)
        {
            List<Field> hyperlinks = new List<Field>();

            //Iterate through the items in the sections to find all hyperlinks
            foreach (Section section in document.Sections)
            {
                foreach (DocumentObject sec in section.Body.ChildObjects)
                {
                    if (sec.DocumentObjectType == DocumentObjectType.Paragraph)
                    {
                        foreach (DocumentObject para in (sec as Paragraph).ChildObjects)
                        {
                            if (para.DocumentObjectType == DocumentObjectType.Field)
                            {
                                Field field = para as Field;

                                if (field.Type == FieldType.FieldHyperlink)
                                {
                                    hyperlinks.Add(field);
                                }
                            }
                        }
                    }
                }
            }
            return hyperlinks;
        }

        //Create a method FlattenHyperlinks() to flatten the hyperlink field
        private static void FlattenHyperlinks(Field field)
        {
            int ownerParaIndex = field.OwnerParagraph.OwnerTextBody.ChildObjects.IndexOf(field.OwnerParagraph);
            int fieldIndex = field.OwnerParagraph.ChildObjects.IndexOf(field);
            Paragraph sepOwnerPara = field.Separator.OwnerParagraph;
            int sepOwnerParaIndex = field.Separator.OwnerParagraph.OwnerTextBody.ChildObjects.IndexOf(field.Separator.OwnerParagraph);
            int sepIndex = field.Separator.OwnerParagraph.ChildObjects.IndexOf(field.Separator);
            int endIndex = field.End.OwnerParagraph.ChildObjects.IndexOf(field.End);
            int endOwnerParaIndex = field.End.OwnerParagraph.OwnerTextBody.ChildObjects.IndexOf(field.End.OwnerParagraph);
            FormatFieldResultText(field.Separator.OwnerParagraph.OwnerTextBody, sepOwnerParaIndex, endOwnerParaIndex, sepIndex, endIndex);

            field.End.OwnerParagraph.ChildObjects.RemoveAt(endIndex);

            for (int i = sepOwnerParaIndex; i >= ownerParaIndex; i--)
            {
                if (i == sepOwnerParaIndex && i == ownerParaIndex)
                {
                    for (int j = sepIndex; j >= fieldIndex; j--)
                    {
                        field.OwnerParagraph.ChildObjects.RemoveAt(j);

                    }
                }
                else if (i == ownerParaIndex)
                {
                    for (int j = field.OwnerParagraph.ChildObjects.Count - 1; j >= fieldIndex; j--)
                    {
                        field.OwnerParagraph.ChildObjects.RemoveAt(j);
                    }

                }
                else if (i == sepOwnerParaIndex)
                {
                    for (int j = sepIndex; j >= 0; j--)
                    {
                        sepOwnerPara.ChildObjects.RemoveAt(j);
                    }
                }
                else
                {
                    field.OwnerParagraph.OwnerTextBody.ChildObjects.RemoveAt(i);
                }
            }
        }

        //Create a method FormatFieldResultText() to remove the font color and underline format of the hyperlinks
        private static void FormatFieldResultText(Body ownerBody, int sepOwnerParaIndex, int endOwnerParaIndex, int sepIndex, int endIndex)
        {
            for (int i = sepOwnerParaIndex; i <= endOwnerParaIndex; i++)
            {
                Paragraph para = ownerBody.ChildObjects[i] as Paragraph;
                if (i == sepOwnerParaIndex && i == endOwnerParaIndex)
                {
                    for (int j = sepIndex + 1; j < endIndex; j++)
                    {
                        FormatText(para.ChildObjects[j] as TextRange);
                    }

                }
                else if (i == sepOwnerParaIndex)
                {
                    for (int j = sepIndex + 1; j < para.ChildObjects.Count; j++)
                    {
                        FormatText(para.ChildObjects[j] as TextRange);
                    }
                }
                else if (i == endOwnerParaIndex)
                {
                    for (int j = 0; j < endIndex; j++)
                    {
                        FormatText(para.ChildObjects[j] as TextRange);
                    }
                }
                else
                {
                    for (int j = 0; j < para.ChildObjects.Count; j++)
                    {
                        FormatText(para.ChildObjects[j] as TextRange);
                    }
                }
            }
        }

        //Create a method FormatText() to change the color of the text to black and remove the underline
        private static void FormatText(TextRange tr)
        {
            //Set the text color to black
            tr.CharacterFormat.TextColor = Color.Black;

            //Set the text underline style to none
            tr.CharacterFormat.UnderlineStyle = UnderlineStyle.None;
        }
    }
}

C#/VB.NET: Remove Hyperlinks in Word Documents

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

By default, hyperlink in Word shows up as blue and underlined. In some cases, users may want to modify the hyperlink style so as to get better looking with the whole document. This article is going to introduce how we can remove the underline or change the color of hyperlinks using Spire.Doc in C#.

Code Snippets:

Step 1: Create a new object of Document class, add a section to it.

Document document = new Document();
Section section = document.AddSection();

Step 2: Add a paragraph and append a hyperlink to the paragraph. In order to format the hyperlink, we return the value of hyperlink in a TextRange.

Paragraph para= section.AddParagraph();
TextRange txtRange = para1.AppendHyperlink("www.e-iceblue.com", "www.e-iceblue.com", HyperlinkType.WebLink);

Step 3: Format the hyperlink with the specified the font name, font size, color and underline style.

txtRange.CharacterFormat.FontName = "Times New Roman";
txtRange.CharacterFormat.FontSize = 12;
txtRange.CharacterFormat.TextColor = System.Drawing.Color.Red;
txtRange.CharacterFormat.UnderlineStyle = UnderlineStyle.None;

Step 4: Save the file.

document.SaveToFile("result.docx", FileFormat.Docx2013);

Output:

How to change the color or remove underline from hyperlink in Word with C#

Full Code:

using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;

namespace FormatHyperlink
{
    class Program
    {
        static void Main(string[] args)
        {
            Document document = new Document();
            Section section = document.AddSection();

            Paragraph para1= section.AddParagraph();
            para1.AppendText("Regular Link: ");
            TextRange txtRange1 = para1.AppendHyperlink("www.e-iceblue.com", "www.e-iceblue.com", HyperlinkType.WebLink);
            txtRange1.CharacterFormat.FontName = "Times New Roman";
            txtRange1.CharacterFormat.FontSize = 12;
            Paragraph blankPara1 = section.AddParagraph();

            Paragraph para2 = section.AddParagraph();
            para2.AppendText("Change Color: ");
            TextRange txtRange2 = para2.AppendHyperlink("www.e-iceblue.com", "www.e-iceblue.com", HyperlinkType.WebLink);
            txtRange2.CharacterFormat.FontName = "Times New Roman";
            txtRange2.CharacterFormat.FontSize = 12;
            txtRange2.CharacterFormat.TextColor = System.Drawing.Color.Red;
            Paragraph blankPara2 = section.AddParagraph();

            Paragraph para3 = section.AddParagraph();
            para3.AppendText("Remove Underline: ");
            TextRange txtRange3 = para3.AppendHyperlink("www.e-iceblue.com", "www.e-iceblue.com", HyperlinkType.WebLink);
            txtRange3.CharacterFormat.FontName = "Times New Roman";
            txtRange3.CharacterFormat.FontSize = 12;
            txtRange3.CharacterFormat.UnderlineStyle = UnderlineStyle.None;

            document.SaveToFile("result.docx", FileFormat.Docx2013);
            System.Diagnostics.Process.Start("result.docx");
        }
    }
}

C#/VB.NET: Edit Hyperlinks in Word

2023-01-29 08:50:00 Written by Koohji

In MS Word, a hyperlink is a clickable link that allows you to jump to a web page, a file, an email address, or even another location in the same document. It is undeniable that adding hyperlinks in Word documents is one of the most common operations in daily work, but there are times when you may also need to change the address or update the display text of an existing hyperlink. This article will demonstrate how to programmatically edit a hyperlink in a Word document using Spire.Doc for .NET.

Install Spire.Doc for .NET

To begin with, you need to add the DLL files included in the Spire.Doc for.NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.

PM> Install-Package Spire.Doc

Edit a Hyperlink in a Word Document in C# and VB.NET

A hyperlink consists of two basic parts: the hyperlink address (URL) and its display text. With Spire.Doc for .NET, you are allowed to modify both the address and display text of an existing hyperlink using Field.Code and Field.FieldText properties. The detailed steps are as follows.

  • Create a Document object.
  • Load a sample Word document using Document.LoadFromFile() method.
  • Create an object of List<Field>.
  • Traverse through all body child objects of sections in the sample document to find all hyperlinks.
  • Modify the address (URL) of a specified hyperlink using Field.Code property.
  • Modify the display text of a specified hyperlink using Field.FieldText property.
  • Save the document to another file using Document.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using System.Collections.Generic;

namespace ModifyHyperlink
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a Document object
            Document doc = new Document();

            //Load a sample Word document
            doc.LoadFromFile("Hyperlink.docx");

            //Create an object of List 
            List<Field> hyperlinks = new List<Field>();

            //Loop through the items in the sections to find all hyperlinks
            foreach (Section section in doc.Sections)
            {
                foreach (DocumentObject sec in section.Body.ChildObjects)
                {
                    if (sec.DocumentObjectType == DocumentObjectType.Paragraph)
                    {
                        //Loop through all paragraphs in the sections
                        foreach (DocumentObject para in (sec as Paragraph).ChildObjects)
                        {
                            if (para.DocumentObjectType == DocumentObjectType.Field)
                            {
                                Field field = para as Field;

                                if (field.Type == FieldType.FieldHyperlink)
                                {
                                    hyperlinks.Add(field);
                                }
                            }
                        }
                    }
                }
            }
            //Modify the address (URL) of the first hyperlink 
            hyperlinks[0].Code = "HYPERLINK \"" + "https://www.e-iceblue.com/Introduce/word-for-net-introduce.html" + "\"";

            //Modify the display text of the first hyperlink 
            hyperlinks[0].FieldText = "Spire.Doc for .NET";

            //Save the result document
            doc.SaveToFile("EditHyperlinks.docx", FileFormat.Docx);
        }
    }
}

C#/VB.NET: Edit Hyperlinks in Word

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

Hyperlinks can point to files, emails, websites, imagers or video when readers click on it. Hyperlinks are widely used in word document for it is very convenient to direct readers to related, useful content. By using Spire.Doc, developers can add hyperlinks, finding hyperlinks and modify hyperlinks. This article will show you how to find all the existing hyperlinks in a word document in C#.

Download and install Spire.Doc for .NET and then add Spire.Doc.dll as reference in the downloaded Bin folder though the below path: "..\Spire.Doc\Bin\NET4.0\ Spire.Doc.dll". Here comes to the details of how to finding hyperlinks in C#.

Firstly, view the word document which contains many hyperlinks:

Finding Hyperlinks in a word document

Please check the code of how to find all the hyperlinks in word document:

using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using System.Collections.Generic;
using System.Drawing;
namespace FindHyperlink
{
    class Program
    {
        static void Main(string[] args)
        {
            Document doc = new Document();
            doc.LoadFromFile("Spire.docx");
            List hyperlinks = new List();
            foreach (Section section in doc.Sections)
            {
                foreach (DocumentObject sec in section.Body.ChildObjects)
                {
                    if (sec.DocumentObjectType == DocumentObjectType.Paragraph)
                    {
                        foreach (DocumentObject para in (sec as Paragraph).ChildObjects)
                        {
                            if (para.DocumentObjectType == DocumentObjectType.Field)
                            {
                                Field field = para as Field;

                                if (field.Type == FieldType.FieldHyperlink)
                                {
                                    hyperlinks.Add(field);
                                }

                            }
                        }
                    }
                }
            }
        }

The effective screenshot of the finding hyperlinks:

Finding Hyperlinks in a word document

A hyperlink within a Word document enables readers to jump from its location to a different place within the document, or to a different file or website, or to a new email message. Hyperlinks make it quick and easy for readers to navigate to related information. This article demonstrates how to add hyperlinks to text or images in C# and VB.NET using Spire.Doc for .NET.

Install Spire.Doc for .NET

To begin with, you need to add the DLL files included in the Spire.Doc for.NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.

PM> Install-Package Spire.Doc

Insert Hyperlinks When Adding Paragraphs to Word

Spire.Doc offers the Paragraph.AppendHyperlink() method to add a web link, an email link, a file link, or a bookmark link to a piece of text or an image inside a paragraph. The following are the detailed steps.

  • Create a Document object.
  • Add a section and a paragraph to it.
  • Insert a hyperlink based on text using Paragraph.AppendHyerplink(string link, string text, HyperlinkType type) method.
  • Add an image to the paragraph using Paragraph.AppendPicture() method.
  • Insert a hyperlink based on the image using Paragraph.AppendHyerplink(string link, Spire.Doc.Fields.DocPicture picture, HyperlinkType type) method.
  • Save the document using Document.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Doc;
using Spire.Doc.Documents;
using System.Drawing;

namespace InsertHyperlinks
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a Word document
            Document doc = new Document();

            //Add a section
            Section section = doc.AddSection();

            //Add a paragraph
            Paragraph paragraph = section.AddParagraph();
            paragraph.AppendHyperlink("https://www-iceblue.com/", "Home Page", HyperlinkType.WebLink);

            //Append line breaks
            paragraph.AppendBreak(BreakType.LineBreak);
            paragraph.AppendBreak(BreakType.LineBreak);

            //Add an email link
            paragraph.AppendHyperlink("mailto:support@e-iceblue.com", "Mail Us", HyperlinkType.EMailLink);

            //Append line breaks
            paragraph.AppendBreak(BreakType.LineBreak);
            paragraph.AppendBreak(BreakType.LineBreak);

            //Add a file link
            string filePath = @"C:\Users\Administrator\Desktop\report.xlsx";
            paragraph.AppendHyperlink(filePath, "Click to open the report", HyperlinkType.FileLink);

            //Append line breaks
            paragraph.AppendBreak(BreakType.LineBreak);
            paragraph.AppendBreak(BreakType.LineBreak);

            //Add another section and create a bookmark 
            Section section2 = doc.AddSection();
            Paragraph bookmarkParagrapg = section2.AddParagraph();
            bookmarkParagrapg.AppendText("Here is a bookmark");
            BookmarkStart start = bookmarkParagrapg.AppendBookmarkStart("myBookmark");
            bookmarkParagrapg.Items.Insert(0, start);
            bookmarkParagrapg.AppendBookmarkEnd("myBookmark");

            //Link to the bookmark
            paragraph.AppendHyperlink("myBookmark", "Jump to a location inside this document", HyperlinkType.Bookmark);

            //Append line breaks
            paragraph.AppendBreak(BreakType.LineBreak);
            paragraph.AppendBreak(BreakType.LineBreak);

            //Add an image link
            Image image = Image.FromFile(@"C:\Users\Administrator\Desktop\logo.png");
            Spire.Doc.Fields.DocPicture picture = paragraph.AppendPicture(image);
            paragraph.AppendHyperlink("https://docs.microsoft.com/en-us/dotnet/", picture, HyperlinkType.WebLink);

            //Save to file
            doc.SaveToFile("InsertHyperlinks.docx", FileFormat.Docx2013);
        }
    }
}

C#/VB.NET: Insert Hyperlinks to Word Documents

Add Hyperlinks to Existing Text in Word

Adding hyperlinks to existing text in a document is a bit more complicated. You’ll need to find the target string first, and then replace it in the paragraph with a hyperlink field. The following are the steps.

  • Create a Document object.
  • Load a Word file using Document.LoadFromFile() method.
  • Find all the occurrences of the target string in the document using Document.FindAllString() method, and get the specific one by its index from the collection.
  • Get the string’s own paragraph and its position in it.
  • Remove the string from the paragraph.
  • Create a hyperlink field and insert it to position where the string is located.
  • Save the document to another file using Document.SaveToFle() method.
  • C#
  • VB.NET
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using Spire.Doc.Interface;

namespace AddHyperlinksToExistingText
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a Document object
            Document document = new Document();

            //Load a Word file
            document.LoadFromFile(@"C:\Users\Administrator\Desktop\sample.docx");

            //Find all the occurrences of the string ".NET Framework" in the document
            TextSelection[] selections = document.FindAllString(".NET Framework", true, true);

            //Get the second occurrence
            TextRange range = selections[1].GetAsOneRange();
      
            //Get its owner paragraph
            Paragraph parapgraph = range.OwnerParagraph;

            //Get its position in the paragraph
            int index = parapgraph.Items.IndexOf(range);

            //Remove it from the paragraph
            parapgraph.Items.Remove(range);

            //Create a hyperlink field
            Spire.Doc.Fields.Field field = new Spire.Doc.Fields.Field(document);
            field.Type = Spire.Doc.FieldType.FieldHyperlink;
            Hyperlink hyperlink = new Hyperlink(field);
            hyperlink.Type = HyperlinkType.WebLink;
            hyperlink.Uri = "https://en.wikipedia.org/wiki/.NET_Framework";
            parapgraph.Items.Insert(index, field);

            //Insert a field mark "start" to the paragraph
            IParagraphBase start = document.CreateParagraphItem(ParagraphItemType.FieldMark);
            (start as FieldMark).Type = FieldMarkType.FieldSeparator;
            parapgraph.Items.Insert(index + 1, start);
            
            //Insert a text range between two field marks
            ITextRange textRange = new Spire.Doc.Fields.TextRange(document);
            textRange.Text = ".NET Framework";
            textRange.CharacterFormat.Font = range.CharacterFormat.Font;
            textRange.CharacterFormat.TextColor = System.Drawing.Color.Blue;
            textRange.CharacterFormat.UnderlineStyle = UnderlineStyle.Single;
            parapgraph.Items.Insert(index + 2, textRange);

            //Insert a field mark "end" to the paragraph
            IParagraphBase end = document.CreateParagraphItem(ParagraphItemType.FieldMark);
            (end as FieldMark).Type = FieldMarkType.FieldEnd;
            parapgraph.Items.Insert(index + 3, end);

            //Save to file
            document.SaveToFile("AddHyperlink.docx", Spire.Doc.FileFormat.Docx);
        }
    }
}

C#/VB.NET: Insert Hyperlinks to Word Documents

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

page