How to Modify Hypertext in Word Document

Hyperlinks have two basic parts: the address (URL) of a certain object and the display text. As an essential element in electronic document, hyperlinks are frequently used in Word to redirect to large amount of information without occupying much space. However, Word doesn't always get the hyperlink correct. In this article, I'll introduce you how to change the displayed text of a hyperlink in C# via Spire.Doc for .NET.

Here is a Word document that makes a brief introduction about Spire.Doc, but as you can see from the picture below, the first hyperlink has been embedded with a wrong text description.

Modify Hyperlinks in Word Document

Now, we are able to change the hypertext as "Spire.Doc component" by using the following method.

Step 1: Create a new instance of Word document and load the sample file.

Document document = new Document();
document.LoadFromFile("..\\..\\Spire.Doc.docx");

Step 2: Call FindAllHyperlinks() method to find all hyperlinks in the Word document.

static List FindAllHyperlinks(Document document)
        {
            List hyperlinks = new List();
            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);
                                }
                            }
                        }
                    }
                }
            }

Step 3: Reset the property of hyperlinks[0].FieldText by using the index of the hyperlink.

hyperlinks[0].FieldText = "Spire.Doc component";

string outfile="result.doc";
document.SaveToFile(outfile,FileFormat.Doc);
System.Diagnostics.Process.Start(outfile);

Result:

Modify Hyperlinks in Word Document