Навигация с курсора

Докато работите с документ, дори и да е кратък или дълъг, ще трябва да се ориентирате чрез вашия документ. Навигацията с виртуален курсор представлява способността за навигация между различни възли в документ.

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

Тази статия обяснява как да се движите в документ и да се движите с виртуален курсор към различни части от него.

Откриване на текущата позиция на курсора

Преди да започнете процеса на навигация чрез вашия документ, ще трябва да получите възела, който в момента е избран. Можете да получите точната позиция на курсора в избран възел, като използвате 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-.NET
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.AreEqual(doc.Range.Bookmarks[0].BookmarkEnd, builder.CurrentParagraph.FirstChild);
// 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.AreEqual(doc.Range.Bookmarks[0].BookmarkStart, builder.CurrentParagraph.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.FirstSection.Body.FirstParagraph.GetChildNodes(NodeType.Any, false)[0]);
Assert.AreEqual(NodeType.BookmarkStart, builder.CurrentNode.NodeType);
Assert.IsTrue(builder.IsAtStartOfParagraph);
// A shorter way of moving the very start/end of a document is with these methods.
builder.MoveToDocumentEnd();
Assert.IsTrue(builder.IsAtEndOfParagraph);
builder.MoveToDocumentStart();
Assert.IsTrue(builder.IsAtStartOfParagraph);

Но освен основното MoveTo метод, има по-конкретни такива.

Навигация към начало или край на документ

Можете да отидете в началото или края на вашия документ с помощта на MoveToDocumentStart както и MoveToDocumentEnd методи.

Следният пример за код показва как да се премести позицията на курсора в началото или края на документа:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// Move the cursor position to the beginning of your document.
builder.MoveToDocumentStart();
Console.WriteLine("\nThis is the beginning of the document.");
// Move the cursor position to the end of your document.
builder.MoveToDocumentEnd();
Console.WriteLine("\nThis is the end of the document.");

Навигация с отметки

Можете да маркирате място, което искате да намерите и да се преместите отново. Можете да въведете колкото се може повече отметки във вашия документ, колкото искате, и след това да преминете през тях, като идентифицирате отметките с уникални имена. Можете да преминете към отметки с помощта на MoveToBookmark метод.

Следните примери за код показват как да преместите курсора в отметки:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
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.AreEqual(doc.Range.Bookmarks[0].BookmarkEnd, builder.CurrentParagraph.FirstChild);
// 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.AreEqual(doc.Range.Bookmarks[0].BookmarkStart, builder.CurrentParagraph.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.FirstSection.Body.FirstParagraph.GetChildNodes(NodeType.Any, false)[0]);

Навигация на клетките на таблицата

Можете да се преместите в клетка на маса с помощта на MoveToCell метод. Този метод ще ви позволи да навигирате курсора си във всяка клетка в определена таблица. В допълнение, можете да посочите индекс за преместване на курсора на всяка позиция или определен символ в клетка в рамките на MoveToCell метод.

Следният пример за код показва как да се премести позицията на курсора в определена таблица:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
Document doc = new Document(MyDir + "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.AreEqual(table.Rows[2].Cells[3], builder.CurrentNode.ParentNode.ParentNode);
Assert.AreEqual("Cell contents added by DocumentBuilderCell 3 contents\a", table.Rows[2].Cells[3].GetText().Trim());

Навигация в поле

Можете да преминете към определено поле във вашия документ чрез MoveToField метод. В допълнение, можете да преминете към определено сливане поле чрез използване на MoveToMergeField метод.

Следният пример за код показва как да преместите курсора на строителя на документи в определено поле:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
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.Null(builder.CurrentNode);
// 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.AreEqual(field.End, builder.CurrentNode.PreviousSibling);
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-.NET
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// Specify that we want headers and footers different for first, even and odd pages.
builder.PageSetup.DifferentFirstPageHeaderFooter = true;
builder.PageSetup.OddAndEvenPagesHeaderFooter = true;
// Create the headers.
builder.MoveToHeaderFooter(HeaderFooterType.HeaderFirst);
builder.Write("Header for the first page");
builder.MoveToHeaderFooter(HeaderFooterType.HeaderEven);
builder.Write("Header for even pages");
builder.MoveToHeaderFooter(HeaderFooterType.HeaderPrimary);
builder.Write("Header for all other pages");
// Create two pages in the document.
builder.MoveToSection(0);
builder.Writeln("Page1");
builder.InsertBreak(BreakType.PageBreak);
builder.Writeln("Page2");
doc.Save(ArtifactsDir + "AddContentUsingDocumentBuilder.MoveToHeadersFooters.docx");

Навигация на раздел или параграф

Можете да преминете към определен раздел или параграф, като използвате MoveToParagraph или MoveToSection методи. В допълнение, можете да посочите индекс за преместване на курсора на всяка позиция или определен символ в параграф в рамките на MoveToParagraph метод.

Следният пример за код показва как да се премине към конкретен раздел и конкретен параграф в документ:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
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(MyDir + "Paragraphs.docx");
ParagraphCollection paragraphs = doc.FirstSection.Body.Paragraphs;
Assert.AreEqual(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 = new DocumentBuilder(doc);
Assert.AreEqual(0, paragraphs.IndexOf(builder.CurrentParagraph));
// You can move the cursor to any position in a paragraph.
builder.MoveToParagraph(2, 10);
Assert.AreEqual(2, paragraphs.IndexOf(builder.CurrentParagraph));
builder.Writeln("This is a new third paragraph. ");
Assert.AreEqual(3, paragraphs.IndexOf(builder.CurrentParagraph));