Навигация с курсора
Докато работите с документ, дори и да е кратък или дълъг, ще трябва да се ориентирате чрез вашия документ. Навигацията с виртуален курсор представлява способността за навигация между различни възли в документ.
В рамките на кратък документ, преместване около в документ е лесно, тъй като можете да преместите точката за вмъкване дори с помощта на клавишите със стрелки на клавиатурата или като кликнете върху мишката, за да намерите точката за вмъкване, където искате. Но след като имате голям документ, който има много страници, тези основни техники ще бъдат недостатъчни.
Тази статия обяснява как да се движите в документ и да се движите с виртуален курсор към различни части от него.
Откриване на текущата позиция на курсора
Преди да започнете процеса на навигация чрез вашия документ, ще трябва да получите възела, който в момента е избран. Можете да получите точната позиция на курсора в избран възел, като използвате current_node собственост. В допълнение, вместо да получите текущия възел, можете да получите текущо избрания параграф или текущо избрания раздел чрез използване на current_paragraph както и current_section имоти.
Всички операции по вмъкване, които извършвате с помощта на DocumentBuilder ще бъде поставен преди current_node. Когато настоящият параграф е празен или курсорът е разположен точно преди края на параграфа, current_node Не се връща.
Навигация на методите в документ
Когато редактирате текст, важно е да знаете как да навигирате вашия документ и къде точно да се движите в него. Aspose.Words Позволява ви да се движите в документ и да се движите към различните си секции и части, това е подобно на функционалността на Навигационната пана в Microsoft Word да отидете на страница или заглавие в документ на Word без превъртане.
Основният метод е да можете да преместите позицията на курсора към определен възел във вашия документ, можете да постигнете това чрез използване на move_to метод.
Следният пример с код показва как да преместите DocumentBuilder до различни възли в документ:
# For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Python-via-.NET | |
doc = aw.Document() | |
builder = aw.DocumentBuilder(doc) | |
# Start a bookmark and add content to it using a DocumentBuilder. | |
builder.start_bookmark("MyBookmark") | |
builder.writeln("Bookmark contents.") | |
builder.end_bookmark("MyBookmark") | |
# The node that the DocumentBuilder is currently at is past the boundaries of the bookmark. | |
self.assertEqual(doc.range.bookmarks[0].bookmark_end, builder.current_paragraph.first_child) | |
# If we wish to revise the content of our bookmark with the DocumentBuilder, we can move back to it like this. | |
builder.move_to_bookmark("MyBookmark") | |
# Now we're located between the bookmark's BookmarkStart and BookmarkEnd nodes, so any text the builder adds will be within it. | |
self.assertEqual(doc.range.bookmarks[0].bookmark_start, builder.current_paragraph.first_child) | |
# 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.move_to(doc.first_section.body.first_paragraph.get_child_nodes(aw.NodeType.ANY, False)[0]) | |
self.assertEqual(aw.NodeType.BOOKMARK_START, builder.current_node.node_type) | |
self.assertTrue(builder.is_at_start_of_paragraph) | |
# A shorter way of moving the very start/end of a document is with these methods. | |
builder.move_to_document_end() | |
self.assertTrue(builder.is_at_end_of_paragraph) | |
builder.move_to_document_start() | |
self.assertTrue(builder.is_at_start_of_paragraph) |
Но освен основното move_to метод, има по-конкретни такива.
Навигация към начало или край на документ
Можете да отидете в началото или края на вашия документ с помощта на move_to_document_start както и move_to_document_end методи.
Следният пример за код показва как да се премести позицията на курсора в началото или края на документа:
# For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Python-via-.NET | |
doc = aw.Document() | |
builder = aw.DocumentBuilder(doc) | |
# Move the cursor position to the beginning of your document. | |
builder.move_to_document_start() | |
print("\nThis is the beginning of the document.") | |
# Move the cursor position to the end of your document. | |
builder.move_to_document_end() | |
print("\nThis is the end of the document.") |
Навигация с отметки
Можете да маркирате място, което искате да намерите и да се преместите отново. Можете да въведете колкото се може повече отметки във вашия документ, колкото искате, и след това да преминете през тях, като идентифицирате отметките с уникални имена. Можете да преминете към отметки с помощта на move_to_bookmark метод.
Следните примери за код показват как да преместите курсора в отметки:
# For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Python-via-.NET | |
doc = aw.Document() | |
builder = aw.DocumentBuilder(doc) | |
# Start a bookmark and add content to it using a DocumentBuilder. | |
builder.start_bookmark("MyBookmark") | |
builder.writeln("Bookmark contents.") | |
builder.end_bookmark("MyBookmark") | |
# The node that the DocumentBuilder is currently at is past the boundaries of the bookmark. | |
self.assertEqual(doc.range.bookmarks[0].bookmark_end, builder.current_paragraph.first_child) | |
# If we wish to revise the content of our bookmark with the DocumentBuilder, we can move back to it like this. | |
builder.move_to_bookmark("MyBookmark") | |
# Now we're located between the bookmark's BookmarkStart and BookmarkEnd nodes, so any text the builder adds will be within it. | |
self.assertEqual(doc.range.bookmarks[0].bookmark_start, builder.current_paragraph.first_child) | |
# 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.move_to(doc.first_section.body.first_paragraph.get_child_nodes(aw.NodeType.ANY, False)[0]) |
Навигация на клетките на таблицата
Можете да се преместите в клетка на маса с помощта на move_to_cell метод. Този метод ще ви позволи да навигирате курсора си във всяка клетка в определена таблица. В допълнение, можете да посочите индекс за преместване на курсора на всяка позиция или определен символ в клетка в рамките на move_to_cell метод.
Следният пример за код показва как да се премести позицията на курсора в определена таблица:
# For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Python-via-.NET | |
doc = aw.Document(docs_base.my_dir + "Tables.docx") | |
builder = aw.DocumentBuilder(doc) | |
# Move the builder to row 3, cell 4 of the first table. | |
builder.move_to_cell(0, 2, 3, 0) | |
builder.write("\nCell contents added by DocumentBuilder") | |
table = doc.get_child(aw.NodeType.TABLE, 0, True).as_table() | |
self.assertEqual(table.rows[2].cells[3], builder.current_node.parent_node.parent_node) | |
self.assertEqual("Cell contents added by DocumentBuilderCell 3 contents\a", table.rows[2].cells[3].get_text().strip()) |
Навигация в поле
Можете да преминете към определено поле във вашия документ чрез move_to_field метод. В допълнение, можете да преминете към определено сливане поле чрез използване на move_to_merge_field метод.
Следният пример за код показва как да преместите курсора на строителя на документи в определено поле:
# For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Python-via-.NET | |
doc = aw.Document() | |
builder = aw.DocumentBuilder(doc) | |
# Insert a field using the DocumentBuilder and add a run of text after it. | |
field = builder.insert_field("MERGEFIELD field") | |
builder.write(" Text after the field.") | |
# The builder's cursor is currently at end of the document. | |
self.assertIsNone(builder.current_node) | |
# We can move the builder to a field like this, placing the cursor at immediately after the field. | |
builder.move_to_field(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.move_to() method. | |
self.assertEqual(field.end, builder.current_node.previous_sibling) | |
builder.write(" Text immediately after the field.") |
Навигация към заглавна част или стъпало
Можете да преминете към началото на заглавна част или стъпало чрез използване на move_to_header_footer метод
Следният пример за код показва как да преместите курсора на документа към заглавна част на документа или стъпало:
Навигация на раздел или параграф
Можете да преминете към определен раздел или параграф, като използвате move_to_paragraph или move_to_section методи. В допълнение, можете да посочите индекс за преместване на курсора на всяка позиция или определен символ в параграф в рамките на move_to_paragraph метод.
Следният пример за код показва как да се премине към конкретен раздел и конкретен параграф в документ:
# For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Python-via-.NET | |
doc = aw.Document() | |
doc.append_child(aw.Section(doc)) | |
# Move a DocumentBuilder to the second section and add text. | |
builder = aw.DocumentBuilder(doc) | |
builder.move_to_section(1) | |
builder.writeln("Text added to the 2nd section.") | |
# Create document with paragraphs. | |
doc = aw.Document(docs_base.my_dir + "Paragraphs.docx") | |
paragraphs = doc.first_section.body.paragraphs | |
self.assertEqual(22, paragraphs.count) | |
# 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 = aw.DocumentBuilder(doc) | |
self.assertEqual(0, paragraphs.index_of(builder.current_paragraph)) | |
# You can move the cursor to any position in a paragraph. | |
builder.move_to_paragraph(2, 10) | |
self.assertEqual(2, paragraphs.index_of(builder.current_paragraph)) | |
builder.writeln("This is a new third paragraph. ") | |
self.assertEqual(3, paragraphs.index_of(builder.current_paragraph)) |