添加或修改超链接
Microsoft Word文档中的超链接是HYPERLINK
字段。 在Aspose.Words中,超链接是通过FieldHyperlink类实现的。
插入超链接
使用InsertHyperlink方法将超链接插入到文档中。 此方法接受三个参数:
- 要在文档中显示的链接的文本
- 链接目标(URL或文档内书签的名称)
- 如果
URL
是文档中书签的名称,则应为true的布尔参数
InsertHyperlink方法始终在URL的开头和结尾添加撇号。
Font
属性显式指定超链接显示文本的字体格式。
下面的代码示例演示如何使用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"); |
替换或修改超链接
Microsoft Word文档中的超链接是一个字段。 Word文档中的字段是由多个节点组成的复杂结构,这些节点包括字段开始、字段代码、字段分隔符、字段结果和字段结束。 字段可以嵌套,包含丰富的内容,并跨越文档中的多个段落或部分。
FieldHyperlink
类实现HYPERLINK
字段。
下面的代码示例演示如何查找Word文档中的所有超链接并更改其URL
和显示名称:
//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"); |