Nawigacja za pomocą kursora

Podczas pracy z dokumentem, nawet jeśli jest on krótki lub długi, będziesz musiał poruszać się po dokumencie. Nawigacja za pomocą wirtualnego kursora reprezentuje możliwość poruszania się pomiędzy różnymi węzłami w dokumencie.

W krótkim dokumencie poruszanie się po dokumencie jest proste, ponieważ punkt wstawiania można przesuwać nawet za pomocą klawiszy strzałek na klawiaturze lub klikając myszą, aby umieścić punkt wstawiania w dowolnym miejscu. Ale gdy masz duży dokument, który ma wiele stron, te podstawowe techniki okażą się niewystarczające.

W tym artykule wyjaśniono, jak poruszać się po dokumencie i nawigować wirtualnym kursorem do różnych jego części.

Wykrywanie aktualnej pozycji kursora

Przed rozpoczęciem procesu nawigacji po dokumencie musisz uzyskać aktualnie wybrany węzeł. Dokładną pozycję kursora w wybranym węźle można uzyskać za pomocą właściwości CurrentNode. Ponadto zamiast pobierać bieżący węzeł, można uzyskać aktualnie wybrany akapit lub aktualnie wybraną sekcję, korzystając z właściwości CurrentParagraph i CurrentSection.

Wszelkie operacje wstawiania wykonane przy użyciu DocumentBuilder zostaną wstawione przed CurrentNode. Gdy bieżący akapit jest pusty lub kursor znajduje się tuż przed końcem akapitu, format CurrentNode zwraca wartość null.

Nawigowanie po metodach w dokumencie

Podczas edycji tekstu ważne jest, aby wiedzieć, jak poruszać się po dokumencie i gdzie dokładnie się w nim poruszać. Aspose.Words umożliwia poruszanie się po dokumencie i przechodzenie do jego różnych sekcji i części – jest to podobne do funkcjonalności okienka nawigacji w Microsoft Word, umożliwiającego przejście do strony lub nagłówka w dokumencie Word bez przewijania.

Główną metodą jest możliwość przeniesienia pozycji kursora do określonego węzła w dokumencie. Można to osiągnąć za pomocą metody MoveTo.

Poniższy przykład kodu pokazuje, jak przenieść DocumentBuilder do różnych węzłów w dokumencie:

// 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);

Ale oprócz podstawowej metody MoveTo istnieją bardziej szczegółowe.

Przejdź do początku lub końca dokumentu

Możesz przejść na początek lub na koniec dokumentu, korzystając z metod MoveToDocumentStart i MoveToDocumentEnd.

Poniższy przykład kodu pokazuje, jak przenieść pozycję kursora na początek lub na koniec dokumentu:

// 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.");

Nawiguj za pomocą zakładek

Możesz zaznaczyć miejsce, które chcesz znaleźć i łatwo do niego ponownie przenieść. Możesz wstawić do dokumentu dowolną liczbę zakładek, a następnie przeglądać je, identyfikując zakładki za pomocą unikalnych nazw. Do zakładki można przejść metodą MoveToBookmark.

Poniższy przykład kodu pokazuje, jak przenieść pozycję kursora do zakładki:

// 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]);

Przejdź do komórek tabeli

Do komórki tabeli można przejść za pomocą metody MoveToCell. Ta metoda umożliwia nawigację kursorem do dowolnej komórki w określonej tabeli. Ponadto możesz określić indeks, aby przenieść kursor do dowolnej pozycji lub określonego znaku w komórce w ramach metody MoveToCell.

Poniższy przykład kodu pokazuje, jak przenieść pozycję kursora do określonej komórki tabeli:

// 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());

Przejdź do pola

Do konkretnego pola w dokumencie możesz przejść korzystając z metody MoveToField. Ponadto możesz przejść do konkretnego pola scalania, korzystając z metody MoveToMergeField.

Poniższy przykład kodu pokazuje, jak przenieść kursor narzędzia do tworzenia dokumentów do określonego pola:

// 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.");

Przejdź do nagłówka lub stopki

Możesz przejść na początek nagłówka lub stopki, korzystając z metody MoveToHeaderFooter

Poniższy przykład kodu pokazuje, jak przenieść kursor narzędzia do tworzenia dokumentów do nagłówka lub stopki dokumentu:

// 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");

Przejdź do sekcji lub akapitu

Możesz przejść do określonej sekcji lub akapitu, korzystając z metod MoveToParagraph lub MoveToSection. Ponadto można określić indeks, aby przenieść kursor do dowolnej pozycji lub określonego znaku w akapicie w ramach metody MoveToParagraph.

Poniższy przykład kodu pokazuje, jak przejść do określonej sekcji i konkretnego akapitu w dokumencie:

// 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));