Навигация с помощью курсора

При работе с документом, даже если он короткий или длинный, вам нужно будет перемещаться по нему. Навигация с помощью виртуального курсора представляет собой возможность перемещаться между различными узлами документа.

В коротком документе легко перемещаться по тексту, поскольку вы можете перемещать точку вставки, даже используя клавиши со стрелками на клавиатуре или щелкая мышью, чтобы найти точку вставки в нужном месте. Но если у вас большой документ с большим количеством страниц, этих базовых методов будет недостаточно.

В этой статье объясняется, как перемещаться по документу и перемещаться с помощью виртуального курсора к различным его частям.

Определение текущего положения курсора

Прежде чем начать процесс навигации по документу, вам нужно будет указать узел, который выбран в данный момент. Вы можете получить точное положение курсора на выбранном узле, используя свойство CurrentNode. Кроме того, вместо получения текущего узла вы можете получить текущий выбранный абзац или текущий выбранный раздел, используя свойства CurrentParagraph и CurrentSection.

Все операции вставки, которые вы выполняете с помощью DocumentBuilder, будут вставлены перед CurrentNode. Если текущий абзац пуст или курсор установлен непосредственно перед концом абзаца, CurrentNode возвращает значение null.

Методы навигации по документу

Когда вы редактируете текст, важно знать, как перемещаться по документу и куда именно перемещаться в нем. Aspose.Words позволяет перемещаться по документу и переходить к его различным разделам и частям – это аналогично функциональности панели навигации в Microsoft Word для перехода к странице или заголовку в документе Word без прокрутки.

Основной метод заключается в том, чтобы иметь возможность перемещать положение курсора на определенный узел в вашем документе, вы можете добиться этого, используя метод MoveTo.

В следующем примере кода показано, как переместить 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);
// Start a bookmark and add content to it using a DocumentBuilder.
builder.startBookmark("MyBookmark");
builder.writeln("Bookmark contents.");
builder.endBookmark("MyBookmark");
// The node that the DocumentBuilder is currently at is past the boundaries of the bookmark.
Assert.assertEquals(doc.getRange().getBookmarks().get(0).getBookmarkEnd(), builder.getCurrentParagraph().getFirstChild());
// If we wish to revise the content of our bookmark with the DocumentBuilder, we can move back to it like this.
builder.moveToBookmark("MyBookmark");
// Now we're located between the bookmark's BookmarkStart and BookmarkEnd nodes, so any text the builder adds will be within it.
Assert.assertEquals(doc.getRange().getBookmarks().get(0).getBookmarkStart(), builder.getCurrentParagraph().getFirstChild());
// We can move the builder to an individual node,
// which in this case will be the first node of the first paragraph, like this.
builder.moveTo(doc.getFirstSection().getBody().getFirstParagraph().getChildNodes(NodeType.ANY, false).get(0));
Assert.assertEquals(NodeType.BOOKMARK_START, builder.getCurrentNode().getNodeType());
Assert.assertTrue(builder.isAtStartOfParagraph());
// A shorter way of moving the very start/end of a document is with these methods.
builder.moveToDocumentEnd();
Assert.assertTrue(builder.isAtEndOfParagraph());
builder.moveToDocumentStart();
Assert.assertTrue(builder.isAtStartOfParagraph());

Но помимо базового метода MoveTo, есть и более специфичные.

Перейдите к началу или концу документа

Вы можете перейти к началу или концу вашего документа, используя методы MoveToDocumentStart и MoveToDocumentEnd.

В следующем примере кода показано, как переместить курсор в начало или конец документа:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
String dataDir = Utils.getDataDir(DocumentBuilderMoveToDocumentStartEnd.class);
Document doc = new Document(dataDir + "Document.docx");
DocumentBuilder builder = new DocumentBuilder(doc);
// Move the cursor position to the beginning of your document.
builder.moveToDocumentStart();
builder.writeln("This is the beginning of the document.");
// Move the cursor position to the end of your document.
builder.moveToDocumentEnd();
builder.writeln("This is the end of the document.");

Навигация с помощью закладок

Вы можете отметить место, которое хотите найти, и легко перейти к нему снова. Вы можете вставить в документ столько закладок, сколько захотите, а затем перемещаться по ним, присваивая закладкам уникальные названия. Вы можете перейти к закладке, используя метод MoveToBookmark.

В следующих примерах кода показано, как переместить курсор на закладку:

// 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);
// Start a bookmark and add content to it using a DocumentBuilder.
builder.startBookmark("MyBookmark");
builder.writeln("Bookmark contents.");
builder.endBookmark("MyBookmark");
// If we wish to revise the content of our bookmark with the DocumentBuilder, we can move back to it like this.
builder.moveToBookmark("MyBookmark");
// Now we're located between the bookmark's BookmarkStart and BookmarkEnd nodes, so any text the builder adds will be within it.
Assert.assertEquals(doc.getRange().getBookmarks().get(0).getBookmarkStart(), builder.getCurrentParagraph().getFirstChild());
// We can move the builder to an individual node,
// which in this case will be the first node of the first paragraph, like this.
builder.moveTo(doc.getFirstSection().getBody().getFirstParagraph().getChildNodes(NodeType.ANY, false).get(0));
Assert.assertEquals(NodeType.BOOKMARK_START, builder.getCurrentNode().getNodeType());

Перейдите к ячейкам таблицы

Вы можете перейти к ячейке таблицы, используя метод MoveToCell. Этот метод позволит вам переместить курсор в любую ячейку определенной таблицы. Кроме того, вы можете указать индекс для перемещения курсора в любую позицию или на указанный символ в ячейке с помощью метода MoveToCell.

В следующем примере кода показано, как переместить курсор в указанную ячейку таблицы:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
String dataDir = Utils.getDataDir(DocumentBuilderMoveToTableCell.class);
Document doc = new Document(dataDir + "Tables.docx");
DocumentBuilder builder = new DocumentBuilder(doc);
// Move the builder to row 3, cell 4 of the first table.
builder.moveToCell(0, 2, 3, 0);
builder.write("\nCell contents added by DocumentBuilder");
Table table = (Table)doc.getChild(NodeType.TABLE, 0, true);
Assert.assertEquals(table.getRows().get(2).getCells().get(3), builder.getCurrentNode().getParentNode().getParentNode());
Assert.assertEquals("Cell contents added by DocumentBuilderCell 3 contents\u0007", table.getRows().get(2).getCells().get(3).getText().trim());

Перейдите к полю

Вы можете перейти к определенному полю в вашем документе, используя метод MoveToField. Кроме того, вы можете перейти к определенному полю объединения, используя метод MoveToMergeField.

В следующем примере кода показано, как переместить курсор конструктора документов на определенное поле:

// 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);
// Insert a field using the DocumentBuilder and add a run of text after it.
Field field = builder.insertField("MERGEFIELD field");
builder.write(" Text after the field.");
// The builder's cursor is currently at end of the document.
Assert.assertNull(builder.getCurrentNode());
// We can move the builder to a field like this, placing the cursor at immediately after the field.
builder.moveToField(field, true);
// Note that the cursor is at a place past the FieldEnd node of the field, meaning that we are not actually inside the field.
// If we wish to move the DocumentBuilder to inside a field,
// we will need to move it to a field's FieldStart or FieldSeparator node using the DocumentBuilder.MoveTo() method.
Assert.assertEquals(field.getEnd(), builder.getCurrentNode().getPreviousSibling());
builder.write(" Text immediately after the field.");

Перейдите к верхнему или нижнему колонтитулу

Вы можете перейти к началу верхнего или нижнего колонтитула, используя метод MoveToHeaderFooter.

В следующем примере кода показано, как переместить курсор конструктора документов в верхний или нижний колонтитул документа:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
String dataDir = Utils.getDataDir(DocumentBuilderHeadersAndFooters.class);
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// Specify that we want headers and footers different for first, even and odd pages.
builder.getPageSetup().setDifferentFirstPageHeaderFooter(true);
builder.getPageSetup().setOddAndEvenPagesHeaderFooter(true);
// Create the headers.
builder.moveToHeaderFooter(HeaderFooterType.HEADER_FIRST);
builder.write("Header for the first page");
builder.moveToHeaderFooter(HeaderFooterType.HEADER_EVEN);
builder.write("Header for even pages");
builder.moveToHeaderFooter(HeaderFooterType.HEADER_PRIMARY);
builder.write("Header for all other pages");
// Create two pages in the document.
builder.moveToSection(0);
builder.writeln("Page1");
builder.insertBreak(BreakType.PAGE_BREAK);
builder.writeln("Page2");
doc.save(dataDir + "DocumentBuilder.HeadersAndFooters.docx");

Перейдите к разделу или абзацу

Вы можете перейти к определенному разделу или абзацу, используя методы MoveToParagraph или MoveToSection. Кроме того, вы можете указать индекс для перемещения курсора в любую позицию или на указанный символ в абзаце с помощью метода MoveToParagraph.

В следующем примере кода показано, как перейти к определенному разделу и конкретному абзацу в документе:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
String dataDir = Utils.getDataDir(DocumentBuilderMoveToSectionParagraph.class);
// Create a blank document and append a section to it, giving it two sections.
Document doc = new Document();
doc.appendChild(new Section(doc));
// Move a DocumentBuilder to the second section and add text.
DocumentBuilder builder = new DocumentBuilder(doc);
builder.moveToSection(1);
builder.writeln("Text added to the 2nd section.");
// Create document with paragraphs.
doc = new Document(dataDir + "Paragraphs.docx");
ParagraphCollection paragraphs = doc.getFirstSection().getBody().getParagraphs();
Assert.assertEquals(22, paragraphs.getCount());
// When we create a DocumentBuilder for a document, its cursor is at the very beginning of the document by default,
// and any content added by the DocumentBuilder will just be prepended to the document.
builder = new DocumentBuilder(doc);
Assert.assertEquals(0, paragraphs.indexOf(builder.getCurrentParagraph()));
// You can move the cursor to any position in a paragraph.
builder.moveToParagraph(0, 14);
Assert.assertEquals(2, paragraphs.indexOf(builder.getCurrentParagraph()));
builder.writeln("This is a new third paragraph. ");
Assert.assertEquals(3, paragraphs.indexOf(builder.getCurrentParagraph()));