新增或修改超連結
Microsoft Word 文件中的超連結是 HYPERLINK
欄位。 在 Aspose.Words 中,超連結是透過 FieldHyperlink 類別來實作的。
插入超連結
利用 InsertHyperlink 方法將超連結插入至文件中。 此方法接受三個參數:
- 將要顯示在文件中的連結文字
- 連結目的地(網址或文書內存取的書籤名稱)
- 布林參數應該是 true,如果
URL
是檔案中書籤的名稱。
InsertHyperlink這個方法總是將引號加上去網址的开頭與結尾。
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 文檔中的字段,正如之前所說的,是由多個節點組成的複雜結構,這些節點包括字段開始、字段程式碼、字段分隔符、字段結果和字段結束。 欄位可以嵌套、包含豐富內容、在文件中跨多段或多個分節。
若要替換或修改超連結,則須在文件中找到超連結,再將其文字、網址或兩者替換。
以下範例示範了如何在 Microsoft 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"); |