Navegación con Cursor

Mientras trabaja con un documento, incluso si es corto o largo, deberá navegar por su documento. La navegación con un cursor virtual representa la capacidad de navegar entre diferentes nodos en un documento.

Dentro de un documento corto, moverse por un documento es simple, ya que puede mover el punto de inserción incluso usando las teclas de flecha del teclado o haciendo clic con el mouse para ubicar el punto de inserción donde desee. Pero una vez que tenga un documento grande que tenga muchas páginas, estas técnicas básicas serán insuficientes.

En este artículo se explica cómo moverse por un documento y navegar con un cursor virtual a diferentes partes del mismo.

Detección de La Posición Actual del Cursor

Antes de comenzar el proceso de navegación por su documento, deberá obtener el nodo que está seleccionado actualmente. Puede obtener la posición exacta del cursor en un nodo seleccionado utilizando la propiedad CurrentNode. Además, en lugar de obtener el nodo actual, puede obtener el párrafo seleccionado actualmente o la sección seleccionada actualmente utilizando las propiedades CurrentParagraph y CurrentSection.

Cualquier operación de inserción que realice con DocumentBuilder se insertará antes de CurrentNode. Cuando el párrafo actual está vacío o el cursor se coloca justo antes del final del párrafo, CurrentNode devuelve nullptr.

Cuando edite texto, es importante saber cómo navegar por su documento y dónde moverse exactamente en él. Aspose.Words le permite moverse por un documento y navegar a sus diferentes secciones y partes; esto es similar a la funcionalidad del Panel de navegación en Microsoft Word para ir a una página o encabezado en un documento de Word sin desplazarse.

El método principal es poder mover la posición del cursor a un nodo específico en su documento, puede lograrlo utilizando el método MoveTo.

El siguiente ejemplo de código muestra cómo mover el DocumentBuilder a diferentes nodos en un documento:

For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
auto doc = System::MakeObject<Document>();
auto builder = System::MakeObject<DocumentBuilder>(doc);
// Start a bookmark and add content to it using a DocumentBuilder.
builder->StartBookmark(u"MyBookmark");
builder->Writeln(u"Bookmark contents.");
builder->EndBookmark(u"MyBookmark");
// The node that the DocumentBuilder is currently at is past the boundaries of the bookmark.
ASSERT_EQ(doc->get_Range()->get_Bookmarks()->idx_get(0)->get_BookmarkEnd(), builder->get_CurrentParagraph()->get_FirstChild());
// If we wish to revise the content of our bookmark with the DocumentBuilder, we can move back to it like this.
builder->MoveToBookmark(u"MyBookmark");
// Now we're located between the bookmark's BookmarkStart and BookmarkEnd nodes, so any text the builder adds will be within it.
ASSERT_EQ(doc->get_Range()->get_Bookmarks()->idx_get(0)->get_BookmarkStart(), builder->get_CurrentParagraph()->get_FirstChild());
// 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->get_FirstSection()->get_Body()->get_FirstParagraph()->GetChildNodes(NodeType::Any, false)->idx_get(0));
ASSERT_EQ(NodeType::BookmarkStart, builder->get_CurrentNode()->get_NodeType());
ASSERT_TRUE(builder->get_IsAtStartOfParagraph());
// A shorter way of moving the very start/end of a document is with these methods.
builder->MoveToDocumentEnd();
ASSERT_TRUE(builder->get_IsAtEndOfParagraph());
builder->MoveToDocumentStart();
ASSERT_TRUE(builder->get_IsAtStartOfParagraph());

Pero además del método básico MoveTo, hay otros más específicos.

Vaya al Principio o al final de un Documento

Puede ir al principio o al final de su documento utilizando los métodos MoveToDocumentStart y MoveToDocumentEnd.

El siguiente ejemplo de código muestra cómo mover la posición del cursor al principio o al final de un documento:

For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
auto doc = System::MakeObject<Document>(inputDataDir + u"Document.docx");
auto builder = System::MakeObject<DocumentBuilder>(doc);
// Move the cursor position to the beginning of your document.
builder->MoveToDocumentStart();
builder->Writeln(u"This is the beginning of the document.");
// Move the cursor position to the end of your document.
builder->MoveToDocumentEnd();
builder->Writeln(u"This is the end of the document.");

Puede marcar un lugar que desee encontrar y volver a él fácilmente. Puede insertar tantos marcadores en su documento como desee y luego navegar a través de ellos identificando los marcadores con nombres únicos. Puede moverse a un marcador utilizando el método MoveToBookmark.

Los siguientes ejemplos de código muestran cómo mover una posición del cursor a un marcador:

For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
auto doc = System::MakeObject<Document>();
auto builder = System::MakeObject<DocumentBuilder>(doc);
// Start a bookmark and add content to it using a DocumentBuilder.
builder->StartBookmark(u"MyBookmark");
builder->Writeln(u"Bookmark contents.");
builder->EndBookmark(u"MyBookmark");
// If we wish to revise the content of our bookmark with the DocumentBuilder, we can move back to it like this.
builder->MoveToBookmark(u"MyBookmark");
// Now we're located between the bookmark's BookmarkStart and BookmarkEnd nodes, so any text the builder adds will be within it.
ASSERT_EQ(doc->get_Range()->get_Bookmarks()->idx_get(0)->get_BookmarkStart(), builder->get_CurrentParagraph()->get_FirstChild());
// 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->get_FirstSection()->get_Body()->get_FirstParagraph()->GetChildNodes(NodeType::Any, false)->idx_get(0));
ASSERT_EQ(NodeType::BookmarkStart, builder->get_CurrentNode()->get_NodeType());

Puede moverse a una celda de la tabla utilizando el método MoveToCell. Este método le permitirá navegar con el cursor a cualquier celda de una tabla específica. Además, puede especificar un índice para mover el cursor a cualquier posición o carácter especificado en una celda dentro del método MoveToCell.

El siguiente ejemplo de código muestra cómo mover una posición del cursor a una celda de tabla especificada:

For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
auto doc = System::MakeObject<Document>(inputDataDir + u"Tables.docx");
auto builder = System::MakeObject<DocumentBuilder>(doc);
// Move the builder to row 3, cell 4 of the first table.
builder->MoveToCell(0, 2, 3, 0);
builder->Write(u"\nCell contents added by DocumentBuilder");
auto table = System::DynamicCast<Tables::Table>(doc->GetChild(NodeType::Table, 0, true));
ASSERT_EQ(table->get_Rows()->idx_get(2)->get_Cells()->idx_get(3), builder->get_CurrentNode()->get_ParentNode()->get_ParentNode());
ASSERT_EQ(table->get_Rows()->idx_get(2)->get_Cells()->idx_get(2)->GetText().Trim(), u"Cell contents added by DocumentBuilderCell 3 contents\a");

Puede moverse a un campo específico en su documento utilizando el método MoveToField. Además, puede moverse a un campo de combinación específico utilizando el método MoveToMergeField.

El siguiente ejemplo de código muestra cómo mover el cursor del generador de documentos a un campo específico:

For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
auto doc = System::MakeObject<Document>();
auto builder = System::MakeObject<DocumentBuilder>(doc);
// Insert a field using the DocumentBuilder and add a run of text after it.
auto field = builder->InsertField(u"MERGEFIELD field");
builder->Write(u" Text after the field.");
// The builder's cursor is currently at end of the document.
ASSERT_EQ(builder->get_CurrentNode(), nullptr);
// 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_EQ(field->get_End(), builder->get_CurrentNode()->get_PreviousSibling());
builder->Write(u" Text immediately after the field.");

Puede moverse al principio de un encabezado o pie de página utilizando el método MoveToHeaderFooter.

El siguiente ejemplo de código muestra cómo mover el cursor del generador de documentos al encabezado o pie de página de un documento:

For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
auto doc = System::MakeObject<Document>();
auto builder = System::MakeObject<DocumentBuilder>(doc);
// Specify that we want headers and footers different for first, even and odd pages.
builder->get_PageSetup()->set_DifferentFirstPageHeaderFooter(true);
builder->get_PageSetup()->set_OddAndEvenPagesHeaderFooter(true);
// Create the headers.
builder->MoveToHeaderFooter(HeaderFooterType::HeaderFirst);
builder->Write(u"Header for the first page");
builder->MoveToHeaderFooter(HeaderFooterType::HeaderEven);
builder->Write(u"Header for even pages");
builder->MoveToHeaderFooter(HeaderFooterType::HeaderPrimary);
builder->Write(u"Header for all other pages");
// Create two pages in the document.
builder->MoveToSection(0);
builder->Writeln(u"Page1");
builder->InsertBreak(BreakType::PageBreak);
builder->Writeln(u"Page2");
System::String outputPath = outputDataDir + u"DocumentBuilderMovingCursor.HeadersAndFooters.doc";
doc->Save(outputPath);

Puede moverse a una sección o párrafo específico utilizando los métodos MoveToParagraph o MoveToSection. Además, puede especificar un índice para mover el cursor a cualquier posición o carácter especificado en un párrafo dentro del método MoveToParagraph.

El siguiente ejemplo de código muestra cómo moverse a una sección y un párrafo específicos en un documento:

For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// Create a blank document and append a section to it, giving it two sections.
auto doc = System::MakeObject<Document>();
doc->AppendChild(System::MakeObject<Section>(doc));
// Move a DocumentBuilder to the second section and add text.
auto builder = System::MakeObject<DocumentBuilder>(doc);
builder->MoveToSection(1);
builder->Writeln(u"Text added to the 2nd section.");
// Create document with paragraphs.
auto doc = System::MakeObject<Document>(inputDataDir + u"Paragraphs.docx");
auto paragraphs = doc->get_FirstSection()->get_Body()->get_Paragraphs();
ASSERT_EQ(paragraphs->get_Count(), 22);
// 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.
auto builder = System::MakeObject<DocumentBuilder>(doc);
ASSERT_EQ(paragraphs->IndexOf(builder->get_CurrentParagraph()), 0);
// You can move the cursor to any position in a paragraph.
builder->MoveToParagraph(0, 14);
ASSERT_EQ(paragraphs->IndexOf(builder->get_CurrentParagraph()), 2);
builder->Writeln(u"This is a new third paragraph. ");
ASSERT_EQ(paragraphs->IndexOf(builder->get_CurrentParagraph()), 3);