使用书签

书签在Microsoft Word文档中标识您命名并标识以供将来参考的位置或片段。 例如,您可以使用书签来标识要稍后修改的文本。 您可以使用"书签"对话框来查找文本,而不是滚动文档以查找文本。

使用Aspose.Words,您可以使用报表或文档中的书签将一些数据插入书签或对其内容应用特殊格式。 您还可以使用书签从文档中的某个位置检索文本。

使用Aspose.Words可以使用书签执行的操作与使用Microsoft Word可以执行的操作相同。 您可以插入新书签,删除,移动到书签,获取或设置书签名称,获取或设置包含在其中的文本。

插入书签

使用startBookmarkendBookmark通过分别标记书签的开始和结束来创建书签。 不要忘记将相同的书签名称传递给这两种方法。 文档中的书签可以重叠并跨越任何范围。 保存文档时,格式错误的书签或名称重复的书签将被忽略。

下面的代码示例演示如何创建新书签:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(CreateBookmark.class);
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.startBookmark("MyBookmark");
builder.writeln("Text inside a bookmark.");
builder.endBookmark("MyBookmark");
builder.startBookmark("Nested Bookmark");
builder.writeln("Text inside a NestedBookmark.");
builder.endBookmark("Nested Bookmark");
builder.writeln("Text after Nested Bookmark.");
builder.endBookmark("My Bookmark");
PdfSaveOptions options = new PdfSaveOptions();
options.getOutlineOptions().setDefaultBookmarksOutlineLevel(1);
options.getOutlineOptions().setDefaultBookmarksOutlineLevel(2);
doc.save(dataDir + "output.pdf", options);
System.out.println("\nBookmark created successfully.");

获取书签

有时需要获取书签集合以遍历书签或用于其他目的。 使用返回表示此节点中包含的文档部分的Range对象的任何文档节点公开的Node.getRange属性。 使用此对象检索BookmarkCollection,然后使用集合索引器获取特定书签。

下面的代码示例演示如何从书签集合中获取书签:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(AccessBookmarks.class);
Document doc = new Document(dataDir + "Bookmark.doc");
Bookmark bookmark1 = doc.getRange().getBookmarks().get(0);
Bookmark bookmark = doc.getRange().getBookmarks().get("MyBookmark");
doc.save(dataDir + "output.doc");
System.out.println("\nTable bookmarked successfully.\nFile saved at " + dataDir);

下面的代码示例演示如何获取或设置书签名称和文本:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(BookmarkNameAndText.class);
Document doc = new Document(dataDir + "Bookmark.doc");
// Use the indexer of the Bookmarks collection to obtain the desired bookmark.
Bookmark bookmark = doc.getRange().getBookmarks().get("MyBookmark");
// Get the name and text of the bookmark.
String name = bookmark.getName();
String text = bookmark.getText();
// Set the name and text of the bookmark.
bookmark.setName("RenamedBookmark");
bookmark.setText("This is a new bookmarked text.");
System.out.println("\nBookmark name and text set successfully.");

下面的代码示例演示如何为表添加书签:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
//Create empty document
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// We call this method to start building the table.
builder.startTable();
builder.insertCell();
// Start bookmark here after calling InsertCell
builder.startBookmark("MyBookmark");
builder.write("Row 1, Cell 1 Content.");
// Build the second cell
builder.insertCell();
builder.write("Row 1, Cell 2 Content.");
// Call the following method to end the row and start a new row.
builder.endRow();
// Build the first cell of the second row.
builder.insertCell();
builder.write("Row 2, Cell 1 Content");
// Build the second cell.
builder.insertCell();
builder.write("Row 2, Cell 2 Content.");
builder.endRow();
// Signal that we have finished building the table.
builder.endTable();
//End of bookmark
builder.endBookmark("MyBookmark");
doc.save(dataDir + "output.doc");
System.out.println("\nTable bookmarked successfully.\nFile saved at " + dataDir);

如果将书签的名称更改为文档中已存在的名称,则不会生成错误,并且在保存文档时只存储第一个书签。

请注意,文档中的某些书签被分配给表单字段。 移动到这样的书签并在那里插入文本将文本插入表单字段代码中。 虽然这不会使表单字段无效,但插入的文本将不可见,因为它成为字段代码的一部分。

下面的代码示例演示如何访问已添加书签的表的列:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
// Create empty document
Document doc = new Document(dataDir + "Bookmark.Table_out.doc");
for (Bookmark bookmark : doc.getRange().getBookmarks())
{
System.out.printf("Bookmark: {0}{1}", bookmark.getName(), bookmark.isColumn() ? " (Column)" : "");
if (bookmark.isColumn())
{
Row row = (Row) bookmark.getBookmarkStart().getAncestor(NodeType.ROW);
if (row != null && bookmark.getFirstColumn() < row.getCells().getCount())
System.out.print(row.getCells().get(bookmark.getFirstColumn()).getText());
}
}

移动到书签

如果您需要将丰富内容(不仅仅是纯文本)插入书签,则应使用moveToBookmark将光标移动到书签,然后使用DocumentBuilder方法和属性插入内容。

显示隐藏书签内容

整个书签(including the bookmarked content)可以使用Aspose.Words封装在IF字段的真实部分中。 IF字段在表达式(Left of Operator)中包含嵌套的合并字段,并且根据合并字段的值,IF字段显示或隐藏Word文档中的书签内容。

下面的代码示例演示如何显示/隐藏书签。

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(ShowHideBookmarks.class);
Document doc = new Document(dataDir + "Bookmark.doc");
showHideBookmarkedContent(doc,"MyBookmark",false);
doc.save(dataDir + "Updated_Document.docx");
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
public static void showHideBookmarkedContent(Document doc, String bookmarkName, boolean showHide) throws Exception {
DocumentBuilder builder = new DocumentBuilder(doc);
Bookmark bm = doc.getRange().getBookmarks().get(bookmarkName);
builder.moveToDocumentEnd();
// {IF "{MERGEFIELD bookmark}" = "true" "" ""}
Field field = builder.insertField("IF \"", null);
builder.moveTo(field.getStart().getNextSibling().getNextSibling());
builder.insertField("MERGEFIELD " + bookmarkName + "", null);
builder.write("\" = \"true\" ");
builder.write("\"");
builder.write("\"");
builder.write(" \"\"");
Node currentNode = field.getStart();
boolean flag = true;
while (currentNode != null && flag) {
if (currentNode.getNodeType() == NodeType.RUN)
if (currentNode.toString(SaveFormat.TEXT).trim().equals("\""))
flag = false;
Node nextNode = currentNode.getNextSibling();
bm.getBookmarkStart().getParentNode().insertBefore(currentNode, bm.getBookmarkStart());
currentNode = nextNode;
}
Node endNode = bm.getBookmarkEnd();
flag = true;
while (currentNode != null && flag) {
if (currentNode.getNodeType() == NodeType.FIELD_END)
flag = false;
Node nextNode = currentNode.getNextSibling();
bm.getBookmarkEnd().getParentNode().insertAfter(currentNode, endNode);
endNode = currentNode;
currentNode = nextNode;
}
doc.getMailMerge().execute(new String[]{bookmarkName}, new Object[]{showHide});
//In case, you do not want to use MailMerge then you may use the following lines of code.
//builder.moveToMergeField(bookmarkName);
//builder.write(showHide ? "true" : "false");
}