添加或修改超链接
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-Java | |
Document doc = new Document(); | |
DocumentBuilder builder = new DocumentBuilder(doc); | |
builder.write("Please make sure to visit "); | |
builder.getFont().setColor(Color.BLUE); | |
builder.getFont().setUnderline(Underline.SINGLE); | |
builder.insertHyperlink("Aspose Website", "http://www.aspose.com", false); | |
builder.getFont().clearFormatting(); | |
builder.write(" for more information."); | |
doc.save(getArtifactsDir() + "AddContentUsingDocumentBuilder.InsertHyperlink.docx"); |
替换或修改超链接
Microsoft Word文档中的超链接是一个字段。 Word文档中的字段,正如我们前面所说,是一个复杂的结构,由多个节点组成,包括字段开始,字段代码,字段分隔符,字段结果和字段结束。 字段可以嵌套,包含丰富的内容,并跨越文档中的多个段落或部分。
要替换或修改超链接,需要在文档中找到超链接并替换它们的文本、URLs或两者。
下面的代码示例演示如何查找Word文档中的所有超链接并更改其URL
和显示名称:
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java | |
Document doc = new Document(getMyDir() + "Hyperlinks.docx"); | |
for (Field field : doc.getRange().getFields()) | |
{ | |
if (field.getType() == FieldType.FIELD_HYPERLINK) | |
{ | |
FieldHyperlink hyperlink = (FieldHyperlink) field; | |
// Some hyperlinks can be local (links to bookmarks inside the document), ignore these. | |
if (hyperlink.getSubAddress() != null) | |
continue; | |
hyperlink.setAddress("http://www.aspose.com"); | |
hyperlink.setResult("Aspose - The .NET & Java Component Publisher"); | |
} | |
} | |
doc.save(getArtifactsDir() + "WorkingWithFields.ReplaceHyperlinks.docx"); |