News Category

Hyperlink

Hyperlink (8)

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");
        }
    }
}

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

Word hyperlink can guide users to get other related information to contents. It can be Email address, website link or even other documents. When inserting hyperlink, users can add for specified text or enter link address directly.

Spire.Doc for Silverlight, a powerful component on manipulating Word documents with Silverlight, enables users to insert hyperlink in Word with Silverlight. This guide will show the method to realize inserting word hyperlinks in Silverlight. Users can invoke paragraph.AppendHyperlink(link string, text string, hyperlink type) method which is provided by Spire.Doc for Silverlight directly to insert hyperlink in Word.

Download Spire.Doc for Silverlight. Create a Silverlight application. Add a button in MainPage.xaml, and then double it to use the following code to insert hyperlink.

The following screenshot demonstrates the result after inserting hyperlink to Word in Silverlight. The hyperlink is located at the bottom of the picture.

Insert Word Hyperlink

Sample code:

[C#]
using System;
using System.Windows;
using System.Windows.Controls;
using System.IO;
using System.Reflection;
using Spire.Doc;
using Spire.Doc.Documents;

namespace InsertHyperlink
{
    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            //Declare SaveFileDialog
            SaveFileDialog save = new SaveFileDialog();
            save.Filter = "Word Document(*.docx)|*.docx";

            //Load Document
            Document document = new Document();
            Assembly assembly = this.GetType().Assembly;
            foreach (String name in assembly.GetManifestResourceNames())
            {
                if (name.EndsWith("Spire.Doc for Silverlight.docx"))
                {
                    using (Stream docStream = assembly.GetManifestResourceStream(name))
                    {
                        document = new Document(docStream, FileFormat.Docx);
                    }
                }
            }

            //Add Hyperlink
            Section section = document.Sections[0];
            Paragraph LinkPara = section.AddParagraph();
            LinkPara.AppendHyperlink("http://www.e-iceblue.com/Introduce/word-for-silverlight-introduce.html", "Learn More about Spire.Doc for Siverlight", HyperlinkType.WebLink);

            //Set Paragrah Style
            ParagraphStyle style = new ParagraphStyle(document);
            style.Name = "LinkStyle";
            style.CharacterFormat.FontName = "Britannic Bold";
            style.CharacterFormat.FontSize = 13;
            style.ParagraphFormat.LineSpacingRule = LineSpacingRule.Multiple;
            style.ParagraphFormat.LineSpacing = 15F;
            document.Styles.Add(style);
            LinkPara.ApplyStyle(style.Name);

            //Save Document
            bool? result = save.ShowDialog();
            if (result.HasValue && result.Value)
            {
                using (Stream stream = save.OpenFile())
                {
                    document.SaveToStream(stream, FileFormat.Docx);
                }
            }  
        }
    }
}
[VB.NET]
Imports System.IO
Imports System.Reflection
Imports System.Drawing
Imports Spire.Doc
Imports Spire.Doc.Documents

Partial Public Class MainPage
    Inherits UserControl

    Public Sub New()
        InitializeComponent()
    End Sub

    Private Sub Button1_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles Button1.Click
        'Declare SaveFileDialog
        Dim save As New SaveFileDialog()
        save.Filter = "Word Document(*.docx)|*.docx"

        'Load Document
        Dim document As New Document()
        Dim [assembly] As System.Reflection.Assembly = Me.GetType().Assembly
        For Each name As String In [assembly].GetManifestResourceNames()
            If name.EndsWith("Spire.Doc for Silverlight.docx") Then
                Using docStream As Stream = [assembly].GetManifestResourceStream(name)
                    document = New Document(docStream, FileFormat.Docx)
                End Using
            End If
        Next name

        'Add Hyperlink
        Dim section As Section = document.Sections(0)
        Dim LinkPara As Paragraph = section.AddParagraph()
        LinkPara.AppendHyperlink("http://www.e-iceblue.com/Introduce/word-for-silverlight-introduce.html", "Learn More about Spire.Doc for Siverlight", HyperlinkType.WebLink)

        'Set Paragrah Style
        Dim style As New ParagraphStyle(document)
        style.Name = "LinkStyle"
        style.CharacterFormat.FontName = "Britannic Bold"
        style.CharacterFormat.FontSize = 13
        style.ParagraphFormat.LineSpacingRule = LineSpacingRule.Multiple
        style.ParagraphFormat.LineSpacing = 15.0F
        document.Styles.Add(style)
        LinkPara.ApplyStyle(style.Name)

        'Save Document
        Dim result? As Boolean = save.ShowDialog()
        If result.HasValue AndAlso result.Value Then
            Using stream As Stream = save.OpenFile()
                document.SaveToStream(stream, FileFormat.Docx)
            End Using
        End If
    End Sub
End Class

Spire.Doc is an Microsoft Word component which enables users to perform a wide range of Word document processing tasks directly, such as generate, read, write and modify Word document in WPF.NET and Silverlight.

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.