如何使用 Java 在 Word 中创建书签

在本教程中,您将学习如何使用 Java 在 Word 中创建书签。它提供了有关库的使用、编写应用程序的编程逻辑以及用于在 Word 中使用 Java 添加书签的可运行示例代码的所有必要信息。还提供了在同一文档中添加多个嵌套书签然后根据要求将其保存为 DOCXDOC 的说明。

使用 Java 将书签添加到 Word 文档的步骤

  1. 建立环境添加Aspose.Words for Java插入书签
  2. 使用 Document 类对象创建一个新的 Word 文件并实例化 DocumentBuilder 类对象
  3. 创建书签并设置其名称
  4. 添加一些示例文本
  5. 创建另一个具有指定名称的嵌套书签,并在其下的文档中添加一些文本
  6. 关闭嵌套书签,然后关闭外部书签,然后将其保存到磁盘上

这些步骤描述了在 Word 中使用 Java 插入书签的过程。此处提供了所有必要的详细信息,包括环境设置、必要的类和添加书签的方法以及描述以添加一些示例文本以轻松测试该功能。此处的步骤适用于嵌套书签,但如果需要,您也可以只添加一个书签。

使用 Java 在 Word 中自动创建书签的代码

import com.aspose.words.Document;
import com.aspose.words.DocumentBuilder;
import com.aspose.words.License;
public class AsposeTest {
public static void main(String[] args) throws Exception {//Main function to insert bookmark using Java
// Instantiate the license
License lic = new License();
lic.setLicense("Aspose.Total.lic");
// Create the Document object
Document doc = new Document();
// Create a DocumentBuilder object
DocumentBuilder builder = new DocumentBuilder(doc);
// Create a bookmark
builder.startBookmark("Outer Bookmark");
// Add some text under this bookmark
builder.writeln("Text inside the outer bookmark.");
// Start another bookmark
builder.startBookmark("Nested Inner Bookmark");
// Add some text to the document under this nested bookmark
builder.writeln("Text inside a NestedBookmark.");
// End the nested bookmark
builder.endBookmark("Nested Inner Bookmark");
// Write text after the nested bookmark
builder.writeln("Text after Nested Bookmark.");
// End the outer bookmark
builder.endBookmark("Outer Bookmark");
// Save the resultant Word file with bookmarks
doc.save("Output.docx");
System.out.println("Done");
}
}

此代码演示了使用 Java 在 Word 中创建书签的过程。 DocumentBuilder 类对象用于插入文本,以及使用书签名称开始和结束书签。您不仅可以基于文本行添加书签,还可以通过提供书签名称使用 startColumnBookmark() 添加按列的书签。

本教程教我们在 Word 文件中添加一个或多个书签。如果您想了解在 Word 文件中添加水印的过程,请参阅 如何使用Java在Word中添加水印 上的文章。

 简体中文