Навигация с курсор
Докато работите с документ, дори и да е кратък или дълъг, ще трябва да навигирате чрез документа си. Навигация с виртуален курсор представлява способността за навигация между различни възли в документ.
В рамките на кратък документ, преместване около в документ е лесно, тъй като можете да преместите точката за вмъкване дори с помощта на клавишите със стрелки на клавиатурата или като кликнете върху мишката, за да намерите точката за вмъкване, където искате. Но след като имате голям документ, който има много страници, тези основни техники ще бъдат недостатъчни.
Тази статия обяснява как да се движите в документ и да се движите с виртуален курсор към различни части от него.
Определяне на текущата позиция на курсора
Преди да започнете процеса на навигация чрез вашия документ, ще трябва да получите възела, който в момента е избран. Можете да получите точната позиция на курсора в избран възел чрез използване на CurrentNode собственост. В допълнение, вместо да получите текущия възел, можете да получите текущо избрания параграф или текущо избрания раздел чрез използване на CurrentParagraph както и CurrentSection имоти.
Всички операции по вмъкване, които извършвате с помощта на DocumentBuilder ще се въведе преди CurrentNode. Когато настоящият параграф е празен или курсорът е разположен точно преди края на параграфа, CurrentNode Връща се нула.
Навигиране на методи в документ
Когато редактирате текст, е важно да знаете как да навигирате вашия документ и къде точно да се движите в него. 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 метод
Следният пример за код показва как да преместите курсора на документа в заглавна част на документа или кракера:
Навигация към раздел или параграф
Можете да преминете към определен раздел или параграф, като използвате 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())); |