Навігація з куратором

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

У короткому документі, що переміщається в документі, простий, як ви можете перемістити точку вставки навіть, використовуючи клавіші з стрілками клавіатури або натиснувши кнопку миші, щоб знайти точку вставки, де ви хочете. Але один раз у вас є великий документ, який має багато сторінок, ці основні методи будуть недостатньо.

Ця стаття пояснює, як перемістити в документі і навігувати віртуальним курсором на різні частини.

Виявлення позицій поточного квадроцикла

Перед тим як розпочати процес навігації через ваш документ, вам потрібно буде отримати вузол, який в даний час вибрано. Ви можете отримати точну позицію курсора на вибраному вершині, використовуючи 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-.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));