Add or Modify Hyperlinks
A hyperlink in Microsoft Word documents is the HYPERLINK
field. In Aspose.Words, hyperlinks are implemented through the FieldHyperlink class.
Inserting a Hyperlink
Use the InsertHyperlink method to insert a hyperlink into the document. This method accepts three parameters:
- Text of the link to be displayed in the document
- Link destination (URL or a name of a bookmark inside the document)
- Boolean parameter that should be true if the
URL
is a name of a bookmark inside the document
The InsertHyperlink method always adds apostrophes at the beginning and end of the URL.
Font
property.
The following code example shows how to insert a hyperlink into a document using DocumentBuilder:
//For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C | |
auto doc = MakeObject<Document>(); | |
auto builder = MakeObject<DocumentBuilder>(doc); | |
builder->Write(u"Please make sure to visit "); | |
builder->get_Font()->set_Color(System::Drawing::Color::get_Blue()); | |
builder->get_Font()->set_Underline(Underline::Single); | |
builder->InsertHyperlink(u"Aspose Website", u"http://www.aspose.com", false); | |
builder->get_Font()->ClearFormatting(); | |
builder->Write(u" for more information."); | |
doc->Save(ArtifactsDir + u"AddContentUsingDocumentBuilder.InsertHyperlink.docx"); |
Replace or Modify Hyperlinks
Hyperlink in Microsoft Word documents is a field. A field in a Word document is a complex structure consisting of multiple nodes that include field start, field code, field separator, field result and field end. Fields can be nested, contain rich content and span multiple paragraphs or sections in a document.
The FieldHyperlink
class implements the HYPERLINK
field.
The following code example shows how to find all hyperlinks in Word document and changes their URL
and display name:
//For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C | |
auto doc = MakeObject<Document>(MyDir + u"Hyperlinks.docx"); | |
for (const auto& field : System::IterateOver(doc->get_Range()->get_Fields())) | |
{ | |
if (field->get_Type() == FieldType::FieldHyperlink) | |
{ | |
auto hyperlink = System::DynamicCast<FieldHyperlink>(field); | |
// Some hyperlinks can be local (links to bookmarks inside the document), ignore these. | |
if (hyperlink->get_SubAddress() != nullptr) | |
{ | |
continue; | |
} | |
hyperlink->set_Address(u"http://www.aspose.com"); | |
hyperlink->set_Result(u"Aspose - The .NET & Java Component Publisher"); | |
} | |
} | |
doc->Save(ArtifactsDir + u"WorkingWithFields.ReplaceHyperlinks.docx"); |