C++ Create and Find Hyperlinks in Word

Hyperlinks point text or images in a document to a web page, a mail address or a file location. Inside the document a link is stored as a field: the text the reader sees belongs to the field result, and the target address is written in the field code. Creating links programmatically, rather than inserting them by hand, allows a uniform address rule to be applied and prevents omissions when documents are generated in batches.

Spire.Doc for C++ creates hyperlinks with Paragraph->AppendHyperlink(), which offers overloads for text and for pictures. The link type is set with HyperlinkType: web addresses use WebLink, and mail addresses use EMailLink. To read links, the code walks the Field objects in the paragraphs, tests each one with FieldType::FieldHyperlink, and calls GetFieldText() to obtain the display text. All processing runs in the local process, and the document does not need to be uploaded to any service.

This article covers three features:

The find example uses the "Employee Service Portal" template (HyperlinkSample.docx). The document occupies the first page of the body and contains eight hyperlinks, pointing to the company website, the help center, ticket submission, the download center, developer documentation, service status, the user community and the feedback mailbox:

No. Display text Target address Type
1 www.example.com https://www.example.com Web
2 help.example.com https://help.example.com Web
3 [email protected] mailto:[email protected] Mail
4 www.example.com/download https://www.example.com/download Web
5 docs.example.com https://docs.example.com Web
6 status.example.com https://status.example.com Web
7 community.example.com https://community.example.com Web
8 [email protected] mailto:[email protected] Mail

The sample document containing eight hyperlinks

Install Spire.Doc for C++

There are two ways to integrate Spire.Doc for C++ into your application. One way is to install it through NuGet; the other is to download the package from our website and copy the libraries into your program. Installing through NuGet is simpler and is the recommended approach.

  • In Visual Studio, open the NuGet Package Manager, search for Spire.Doc.Cpp, and install it.
  • Alternatively, run nuget install Spire.Doc.Cpp in the project directory, and then add the package's include and lib folders to the project.

An integrated project needs to reference the corresponding import library and to ensure that dependency files such as SpireDocCpp.dll and Spire.Doc.Base.dll are present in the run directory. For detailed configuration instructions, refer to How to Integrate Spire.Doc for C++ in a C++ Application.

Create Text Hyperlinks

The first argument of Paragraph->AppendHyperlink(link, text, type) is the target address, the second is the display text, and the third specifies the link type. Web addresses use HyperlinkType::WebLink and mail addresses use HyperlinkType::EMailLink. The method returns a Field object, and Field derives from TextRange, so GetCharacterFormat() can be used to set the font, font size and color of the link text.

Operation Method
Create a web link Paragraph->AppendHyperlink(url, text, HyperlinkType::WebLink)
Create a mail link Paragraph->AppendHyperlink(url, text, HyperlinkType::EMailLink)
Append plain text Paragraph->AppendText(text)
Obtain the link format Field->GetCharacterFormat()

The detailed steps are as follows.

  • Create a Document object and call AddSection() to add a section.
  • Add the title paragraph, and set bold, font size and color.
  • Add the four paragraphs "Company Website", "Contact Email", "User Community" and "Downloads" in turn, writing the label with AppendText() and appending the link with AppendHyperlink().
  • Use WebLink for web addresses; mail addresses start with mailto: and use EMailLink.
  • Call Document->SaveToFile() to save the result document.

The code for creating text hyperlinks is shown below.

#include <iostream>
#include <string>
#include "Spire/Doc/pch.h"
#ifdef LoadImage
#undef LoadImage
#endif
#define LoadImage LoadImageA
#ifdef DocumentProperties
#undef DocumentProperties
#endif
#define DocumentProperties DocumentPropertiesA
#include "Spire/Doc/Collections/SectionCollection.h"
#include "Spire/Doc/Document.h"
#include "Spire/Doc/Documents/HyperlinkType.h"
#include "Spire/Doc/Documents/Paragraph.h"
#include "Spire/Doc/Documents/UnderlineStyle.h"
#include "Spire/Doc/Fields/DocPicture.h"
#include "Spire/Doc/Fields/Field.h"
#include "Spire/Doc/Fields/TextRange.h"
#include "Spire/Doc/FileFormat.h"
#include "Spire/Doc/Formatting/CharacterFormat.h"
#include "Spire/Doc/Section.h"
#include "Spire/Doc/common/h/Color.h"
#include "Spire/Doc/common/h/Stream.h"
using namespace std;
using namespace Spire::Doc;
using namespace Spire::Doc::Collections;
using namespace Spire::Doc::Common;
using namespace Spire::Doc::Documents;
using namespace Spire::Doc::Fields;
using namespace Spire::Doc::Formatting;

int main()
{
    //Create a new document and add a section
    intrusive_ptr<Document> document = new Document();
    intrusive_ptr<Section> section = document->AddSection();
    SetConsoleOutputCP(CP_UTF8);

    //Add the title
    intrusive_ptr<Paragraph> title = section->AddParagraph();
    intrusive_ptr<TextRange> titleRange = title->AppendText("Enterprise Service Portal");
    titleRange->GetCharacterFormat()->SetBold(true);
    titleRange->GetCharacterFormat()->SetFontSize(16);
    titleRange->GetCharacterFormat()->SetTextColor(Color::FromArgbRGB(31, 56, 100));
    titleRange->GetCharacterFormat()->SetFontName("Calibri");
    titleRange->GetCharacterFormat()->SetFontNameFarEast("Calibri");

    //Web link: the address and the display text can differ
    intrusive_ptr<Paragraph> webPara = section->AddParagraph();
    webPara->AppendText("Company Website: ");
    webPara->AppendHyperlink("https://www.example.com", "www.example.com", HyperlinkType::WebLink);

    //Mail link: the address starts with mailto
    intrusive_ptr<Paragraph> mailPara = section->AddParagraph();
    mailPara->AppendText("Contact Email: ");
    mailPara->AppendHyperlink("mailto:[email protected]", "[email protected]", HyperlinkType::EMailLink);

    //Community and download links
    intrusive_ptr<Paragraph> forumPara = section->AddParagraph();
    forumPara->AppendText("User Community: ");
    forumPara->AppendHyperlink("https://community.example.com", "community.example.com", HyperlinkType::WebLink);

    intrusive_ptr<Paragraph> downloadPara = section->AddParagraph();
    downloadPara->AppendText("Downloads: ");
    downloadPara->AppendHyperlink("https://www.example.com/download", "www.example.com/download", HyperlinkType::WebLink);

    //Image hyperlink: the image itself is the visible content of the link
    intrusive_ptr<Paragraph> imagePara = section->AddParagraph();
    imagePara->AppendText("Image Link: ");
    intrusive_ptr<DocPicture> picture = imagePara->AppendPicture("logo.png");
    imagePara->AppendHyperlink("https://www.example.com", picture, HyperlinkType::WebLink);

    //Save and close the document
    document->SaveToFile("Output/CreateHyperlinks.docx", FileFormat::Docx);
    document->Close();
    return 0;
}

The four text links and the single image link in the new document follow the paragraph order, and the link text is shown in blue with an underline:

The web links, mail link and image link that were created

Target Address and Display Text Are Independent

The first argument of AppendHyperlink() is the link target, and the second is the text the reader sees on the page. In the example the target addresses carry the https:// prefix while the display text omits the protocol, and the two are allowed to differ. The display text does not have to match the address, but the address must be complete and valid; otherwise the target page cannot be opened when the link is clicked.

Mail Links Require the mailto Prefix

A mail link uses a target address that starts with mailto: and the link type HyperlinkType::EMailLink. Without the prefix, the reader treats the address as an ordinary web address. The display text may be the mail address itself or a description such as "Contact Support"; when the link is clicked, the system starts the default mail client.

Link Appearance Comes from the Hyperlink Style

A newly inserted text link uses blue text and a single underline by default, and both come from the hyperlink character style in the document. The example code sets the character format of the title only and does not modify the appearance of the links. To change the color, font or underline of a link, obtain the CharacterFormat of the object returned by AppendHyperlink(); the procedure is described in C++ Modify, Format, and Remove Hyperlinks in Word.

Create Image Hyperlinks

An image hyperlink uses a picture as the field result, so clicking the picture opens the target address. There are two ways to create one: call Paragraph->AppendPicture() to insert a picture into the paragraph and obtain a DocPicture directly, or create a DocPicture object, call LoadImage() to load the image, and pass the object to the picture overload of AppendHyperlink(). The latter allows picture properties to be set before the link is created.

Operation Method
Insert a picture from a file Paragraph->AppendPicture(path)
Create a picture object new DocPicture(document)
Load an image file DocPicture->LoadImage(path)
Create an image link Paragraph->AppendHyperlink(url, picture, HyperlinkType::WebLink)

The detailed steps are as follows.

  • Create a Document object and call LoadFromFile() to load the template document.
  • Obtain the first section, add a paragraph and write the descriptive text.
  • Create a DocPicture object and pass the current document as its owner.
  • Call LoadImage() to load the image from a file.
  • Call the picture overload of AppendHyperlink() to append the picture as the link content.
  • Call Document->SaveToFile() to save the result document.

The code for creating an image hyperlink is shown below.

#include <iostream>
#include <string>
#include "Spire/Doc/pch.h"
#ifdef LoadImage
#undef LoadImage
#endif
#define LoadImage LoadImageA
#ifdef DocumentProperties
#undef DocumentProperties
#endif
#define DocumentProperties DocumentPropertiesA
#include "Spire/Doc/Collections/SectionCollection.h"
#include "Spire/Doc/Document.h"
#include "Spire/Doc/Documents/HyperlinkType.h"
#include "Spire/Doc/Documents/Paragraph.h"
#include "Spire/Doc/ExportOptions.h"
#include "Spire/Doc/Fields/DocPicture.h"
#include "Spire/Doc/Fields/Field.h"
#include "Spire/Doc/FileFormat.h"
#include "Spire/Doc/Importing/ImportOptions.h"
#include "Spire/Doc/Section.h"
#include "Spire/Doc/common/h/Stream.h"
using namespace std;
using namespace Spire::Doc;
using namespace Spire::Doc::Collections;
using namespace Spire::Doc::Common;
using namespace Spire::Doc::Documents;
using namespace Spire::Doc::Fields;
using namespace Spire::Doc::Importing;

int main()
{
    //Load an existing document as the template
    intrusive_ptr<Document> document = new Document();
    document->LoadFromFile("BlankTemplate.docx");

    intrusive_ptr<Section> section = document->GetSections()->GetItem(0);

    //Add the descriptive text
    intrusive_ptr<Paragraph> paragraph = section->AddParagraph();
    paragraph->AppendText("Click the image below to open the company portal: ");

    //Create a picture object and load the image from a file
    intrusive_ptr<DocPicture> picture = new DocPicture(document);
    picture->LoadImage("logo.png");

    //Append the picture as the content of the hyperlink
    paragraph->AppendHyperlink("https://www.example.com", picture, HyperlinkType::WebLink);

    //Save and close the document
    document->SaveToFile("Output/CreateImageHyperlink.docx", FileFormat::Docx);
    document->Close();
    return 0;
}

The paragraph added to the template document contains the descriptive text and the picture, and the picture itself is the clickable area:

An image hyperlink added to the template document

Difference Between the Two Ways of Adding a Picture

AppendPicture() inserts the picture and returns the object in a single step, which suits cases where the picture uses the default size and position. new DocPicture(document) followed by LoadImage() performs the same work in two steps, and the picture's width, height or text wrapping can be set before AppendHyperlink() is called. Both approaches produce a DocPicture that can be passed to the picture overload of AppendHyperlink().

The Picture Itself Is the Clickable Area

An image hyperlink has no separate text result, and the clickable range of the link is exactly the area the picture occupies. A small picture therefore gives a small click target. The example uses logo.png, a horizontal wordmark, and the picture keeps its original aspect ratio after insertion. When another picture is substituted, its size should be adjusted to the width of the layout.

Sections and Page Setup of the Template Are Preserved

The example opens the template with LoadFromFile() and appends content at the end of the first section; the existing sections, page size, margins and styles are all retained. If the template contains several sections, the target section is selected with GetSections()->GetItem(index). To insert an image link into a header or footer, the header or footer object of the corresponding section must be accessed instead of the body paragraph collection.

Find Hyperlinks

In the document object model a hyperlink appears as a Field whose type is FieldType::FieldHyperlink. The search traverses sections, body objects and paragraph child objects in turn: the child objects of a body object are examined only when the object type is Paragraph, and the field type is tested only when a child object is of type Field. Once the target field is obtained, GetFieldText() returns its display text.

Operation Method
Traverse the sections Document->GetSections()->GetItem(index)
Obtain the body objects Section->GetBody()->GetChildObjects()
Test for a paragraph DocumentObjectType::Paragraph
Test for a field object DocumentObjectType::Field
Test for a hyperlink field Field->GetType() == FieldType::FieldHyperlink
Read the display text Field->GetFieldText()

The detailed steps are as follows.

  • Create a Document object and call LoadFromFile() to load the sample document.
  • Traverse all sections, and then the child objects of the body in each section.
  • For objects of type Paragraph, traverse their child objects and select the items of type Field.
  • Test whether Field->GetType() is FieldType::FieldHyperlink, and add matching fields to a collection.
  • Call GetFieldText() to obtain the display text, print it to the console and write it to a TXT file.
  • Close the document.

The code for finding hyperlinks is shown below.

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include "Spire/Doc/pch.h"
#ifdef DocumentProperties
#undef DocumentProperties
#endif
#define DocumentProperties DocumentPropertiesA
#include "Spire/Doc/Body.h"
#include "Spire/Doc/Collections/DocumentObjectCollection.h"
#include "Spire/Doc/Collections/SectionCollection.h"
#include "Spire/Doc/Document.h"
#include "Spire/Doc/DocumentObject.h"
#include "Spire/Doc/Documents/DocumentObjectType.h"
#include "Spire/Doc/Documents/Paragraph.h"
#include "Spire/Doc/FieldType.h"
#include "Spire/Doc/Fields/Field.h"
#include "Spire/Doc/Section.h"
#include "Spire/Doc/common/h/Object.h"
#include "Spire/Doc/common/h/Stream.h"
using namespace std;
using namespace Spire::Doc;
using namespace Spire::Doc::Collections;
using namespace Spire::Doc::Common;
using namespace Spire::Doc::Documents;
using namespace Spire::Doc::Fields;

int main()
{
    SetConsoleOutputCP(CP_UTF8);

    //Load the sample document that contains hyperlinks
    intrusive_ptr<Document> document = new Document();
    document->LoadFromFile("HyperlinkSample.docx");

    //Walk every body object and every paragraph looking for hyperlink fields
    vector<intrusive_ptr<Field>> hyperlinks;
    string hyperlinksText = "";
    for (int i = 0; i < document->GetSections()->GetCount(); i++)
    {
        intrusive_ptr<Section> section = document->GetSections()->GetItem(i);
        for (int j = 0; j < section->GetBody()->GetChildObjects()->GetCount(); j++)
        {
            intrusive_ptr<DocumentObject> docObj = section->GetBody()->GetChildObjects()->GetItem(j);
            if (docObj->GetDocumentObjectType() == DocumentObjectType::Paragraph)
            {
                intrusive_ptr<Paragraph> para = Object::Dynamic_cast<Paragraph>(docObj);
                for (int k = 0; k < para->GetChildObjects()->GetCount(); k++)
                {
                    intrusive_ptr<DocumentObject> obj = para->GetChildObjects()->GetItem(k);
                    if (obj->GetDocumentObjectType() == DocumentObjectType::Field)
                    {
                        intrusive_ptr<Field> field = Object::Dynamic_cast<Field>(obj);
                        if (field->GetType() == FieldType::FieldHyperlink)
                        {
                            hyperlinks.push_back(field);
                            //Read the display text and strip the trailing line break
                            string text = field->GetFieldText();
                            while (!text.empty() && (text.back() == '\n' || text.back() == '\r'))
                            {
                                text.pop_back();
                            }
                            hyperlinksText.append(text).append("\n");
                            cout << hyperlinks.size() << "  " << text << endl;
                        }
                    }
                }
            }
        }
    }
    cout << "Hyperlink count: " << hyperlinks.size() << endl;

    //Write all link texts to a TXT file
    ofstream write("Output/FindHyperlinks.txt");
    write << hyperlinksText;
    write.close();

    document->Close();
    return 0;
}

The eight links in the sample document are output in body order, and the trailing line break returned by GetFieldText() is removed before the text is written:

1  www.example.com
2  help.example.com
3  [email protected]
4  www.example.com/download
5  docs.example.com
6  status.example.com
7  community.example.com
8  [email protected]
Hyperlink count: 8

The Traversal Must Cover Every Level of the Body

Hyperlinks may be located in body paragraphs, in table cells or in nested tables. The example processes only the paragraphs under Section->GetBody(), which suits documents whose links are all in the body. Links in a table require the rows and cells to be traversed first and the search to continue with the paragraphs inside each cell. Links in a header or footer are reached through the header and footer objects of the section.

GetFieldText Returns the Field Result

GetFieldText() returns the display text of the link, that is, the field result, and does not include the target address in the field code. The display text may end with a line break, and the example removes \r and \n character by character before writing the result to the TXT file, so that each line corresponds to one link. To read the target address, the field code must be accessed instead of the field result.

Finding Hyperlinks Does Not Modify the Document

The search only reads the types and text of the sections, paragraphs and fields and does not change document content. The example closes the document after writing the TXT file and does not call SaveToFile(). If later changes to the links are to be kept within the same program, the document must be saved after those changes are complete.

Get a Free License

If you want to remove the evaluation message from the generated documents, or to get rid of the function limitations, please apply for a 30-day temporary license.