添加或修改超链接
Microsoft Word 文档中的超链接是 HYPERLINK
字段。在 Aspose.Words 中,超链接是通过 FieldHyperlink 类实现的。
插入超链接
使用 InsertHyperlink 方法将超链接插入到文档中。该方法接受三个参数:
- 文档中显示的链接文本
- 链接目的地(文档内的 URL 或书签名称)
3.布尔参数,如果
URL
是文档内书签的名称,则应为true
InsertHyperlink 方法始终在 URL 的开头和结尾添加撇号。
Font
属性显式指定超链接显示文本的字体格式。
以下代码示例演示如何使用 DocumentBuilder 将超链接插入到文档中:
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET | |
Document doc = new Document(); | |
DocumentBuilder builder = new DocumentBuilder(doc); | |
builder.Write("Please make sure to visit "); | |
builder.Font.Color = Color.Blue; | |
builder.Font.Underline = Underline.Single; | |
builder.InsertHyperlink("Aspose Website", "http://www.aspose.com", false); | |
builder.Font.ClearFormatting(); | |
builder.Write(" for more information."); | |
doc.Save(ArtifactsDir + "AddContentUsingDocumentBuilder.InsertHyperlink.docx"); |
替换或修改超链接
Microsoft Word 文档中的超链接是一个字段。正如我们前面所说,Word文档中的字段是一个由多个节点组成的复杂结构,这些节点包括字段开始、字段代码、字段分隔符、字段结果和字段结束。字段可以嵌套、包含丰富的内容并跨越文档中的多个段落或部分。
要替换或修改超链接,需要在文档中查找超链接并替换其文本、URL 或两者。
以下代码示例演示如何查找Word文档中的所有超链接并更改其URL
和显示名称:
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET | |
Document doc = new Document(MyDir + "Hyperlinks.docx"); | |
foreach (Field field in doc.Range.Fields) | |
{ | |
if (field.Type == FieldType.FieldHyperlink) | |
{ | |
FieldHyperlink hyperlink = (FieldHyperlink) field; | |
// Some hyperlinks can be local (links to bookmarks inside the document), ignore these. | |
if (hyperlink.SubAddress != null) | |
continue; | |
hyperlink.Address = "http://www.aspose.com"; | |
hyperlink.Result = "Aspose - The .NET & Java Component Publisher"; | |
} | |
} | |
doc.Save(ArtifactsDir + "WorkingWithFields.ReplaceHyperlinks.docx"); |