Навігація за допомогою курсору
При роботі з документом, навіть якщо він короткий або довгий, вам потрібно буде переміщатися по ньому. Навігація за допомогою віртуального курсору являє собою можливість переміщатися між різними вузлами документа.
У короткому документі легко переміщатися по тексту, оскільки ви можете переміщати точку вставки, навіть використовуючи клавіші зі стрілками на клавіатурі або клацаючи мишею, щоб знайти точку вставки в потрібному місці. Але якщо у вас великий документ з великою кількістю сторінок, цих основних методів буде недостатньо.
У цій статті пояснюється, як переміщатися по документу та переміщатися за допомогою віртуального курсору до різних його частин.
Визначення поточного положення курсору
Перш ніж почати процес навігації по документу, вам потрібно буде вказати вузол, який обраний в даний момент. Ви можете отримати точне положення курсору на вибраному вузлі, використовуючи властивість CurrentNode. Крім того, замість отримання поточного вузла ви можете отримати поточний вибраний абзац або поточний вибраний розділ, використовуючи властивості CurrentParagraph та CurrentSection.
Усі операції вставки, які ви виконуєте за допомогою DocumentBuilder, будуть вставлені перед CurrentNode. Якщо поточний абзац порожній або курсор встановлений безпосередньо перед кінцем абзацу, CurrentNode повертає значення nullptr.
Методи навігації по документу
Коли ви редагуєте текст, важливо знати, як переміщатися по документу і куди саме переміщатися в ньому. Aspose.Words дозволяє переміщатися по документу і переходити до його різних розділів і частин – це аналогічно функціональності панелі навігації в Microsoft Word для переходу до сторінки або заголовка в документі Word без прокрутки.
Основний метод полягає в тому, щоб мати можливість перемістити положення курсору до певного вузла у вашому документі, ви можете досягти цього за допомогою методу MoveTo.
Наступний приклад коду показує, як перемістити DocumentBuilder до різних вузлів документа:
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()); |
Але крім базового методу MoveTo, є і більш специфічні.
Перейдіть до початку або кінця документа
Ви можете перейти до початку або кінця документа, використовуючи методи MoveToDocumentStart та MoveToDocumentEnd.
Наступний приклад коду показує, як перемістити курсор на початок або кінець документа:
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."); |
Навігація за допомогою закладок
Ви можете позначити місце, яке хочете знайти, і легко перейти до нього знову. Ви можете вставити в документ скільки завгодно закладок, а потім переміщатися по них, присвоюючи закладкам унікальні назви. Ви можете перейти до закладки, використовуючи метод MoveToBookmark.
Наступні приклади коду показують, як перемістити курсор на закладку:
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()); |
Перейдіть до клітинок таблиці
Ви можете перейти до комірки таблиці, використовуючи метод MoveToCell. Цей метод дозволить вам перемістити курсор до будь-якої комірки певної таблиці. Крім того, ви можете вказати індекс для переміщення курсору в будь-яку позицію або на вказаний символ у комірці за допомогою методу MoveToCell.
Наступний приклад коду показує, як перемістити курсор до вказаної комірки таблиці:
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"); |
Перейдіть до поля
Ви можете перейти до певного поля у вашому документі, використовуючи метод MoveToField. Крім того, ви можете перейти до певного поля об’єднання, використовуючи метод MoveToMergeField.
Наступний приклад коду показує, як перемістити курсор конструктора документів на певне поле:
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."); |
Перейдіть до верхнього або нижнього колонтитула
Ви можете перейти до початку верхнього або нижнього колонтитула, використовуючи метод MoveToHeaderFooter.
Наступний приклад коду показує, як перемістити курсор конструктора документів у верхній або нижній колонтитул документа:
Перейдіть до розділу або абзацу
Ви можете перейти до певного розділу або абзацу, використовуючи методи MoveToParagraph або MoveToSection. Крім того, ви можете вказати індекс для переміщення курсору в будь-яку позицію або на вказаний символ в абзаці за допомогою методу MoveToParagraph.
Наступний приклад коду показує, як перейти до певного розділу та певного абзацу в документі:
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); |