C++ Move the Cursor with DocumentNavigator to the Document, Headers and Footers, and Paragraphs

DocumentNavigator works on a document in the manner of a cursor. The MoveTo* methods move the cursor to a specified position, Write() and Writeln() write text at the cursor, and the inserted content lands at the current position while the following content shifts back in document order. Compared with accessing the paragraph collection directly, the navigator is better suited to generating content by page position and document order.

Spire.Doc for C++ locates the start and end of the whole document through MoveToDocumentStart() and MoveToDocumentEnd(), locates headers and footers through MoveToSection() and MoveToHeaderFooter(), and locates a character position within a paragraph through MoveToParagraph(). All processing is completed in the local process, and the document does not need to be uploaded to any service.

This article covers three features:

The example uses the "Smart Warehousing Management Platform Project Brief" (ProjectBrief.docx). The document is one page and contains a header, a footer, and seven body paragraphs, in the following order:

Paragraph index Content
0 Document title "Smart Warehousing Management Platform Project Brief"
1 Level-1 heading "1. Project Background"
2 Body paragraph "As the scale of warehousing continues to grow..."
3 Level-1 heading "2. Objectives"
4 Body paragraph "The platform is to go live within six months..."
5 Level-1 heading "3. Implementation Scope"
6 Body paragraph "Phase one covers the East China and South China regional warehouses..."

The positioning and writing methods of the navigator are listed below:

Operation Method
Move to the start of the document MoveToDocumentStart()
Move to the end of the document MoveToDocumentEnd()
Move to a specified section MoveToSection(index)
Move to a header or footer MoveToHeaderFooter(type)
Move to a specified paragraph MoveToParagraph(paragraphIndex, characterIndex)
Write text Write(text) / Writeln(text)
Insert a paragraph mark Writeln()

Install Spire.Doc for C++

There are two ways to integrate Spire.Doc for C++ into your application. One way is to install it through NuGet; the other is to download the package from our website and copy the libraries into your program. Installing through NuGet is simpler and is the recommended approach.

  • In Visual Studio, open the NuGet Package Manager, search for Spire.Doc.Cpp, and install it.
  • Alternatively, run nuget install Spire.Doc.Cpp in the project directory, and then add the package's include and lib folders to the project.

An integrated project needs to reference the corresponding import library and to ensure that dependency files such as SpireDocCpp.dll and Spire.Doc.Base.dll are present in the run directory. For detailed configuration instructions, refer to How to Integrate Spire.Doc for C++ in a C++ Application.

Move to the Start and End of the Document

MoveToDocumentStart() places the cursor before the first paragraph of the whole document, and MoveToDocumentEnd() places the cursor at the end of the last paragraph. After positioning, call Writeln() to write text and start a new line; the parameterless Writeln() inserts only a paragraph mark, which is used to begin a new paragraph at the end of the document.

The detailed steps are as follows.

  • Create a Document object and call LoadFromFile() to load the sample document.
  • Create a DocumentNavigator object.
  • Call MoveToDocumentStart() to position at the start of the document, adjust the character and paragraph formatting, and call Writeln() to write the opening note.
  • Call MoveToDocumentEnd() to position at the end of the document, call the parameterless Writeln() to start a new line, and then write the closing note.
  • Save the result document with Document->SaveToFile().

The code for moving to the start and end of the document is shown below.

#include <iostream>
#include <string>
#include "Spire/Doc/pch.h"
#ifdef DocumentProperties
#undef DocumentProperties
#endif
#define DocumentProperties DocumentPropertiesA
#include "Spire/Doc/Document.h"
#include "Spire/Doc/Documents/DocumentNavigator.h"
#include "Spire/Doc/Documents/Paragraph.h"
#include "Spire/Doc/Documents/HorizontalAlignment.h"
#include "Spire/Doc/Formatting/CharacterFormat.h"
#include "Spire/Doc/Formatting/ParagraphFormat.h"
#include "Spire/Doc/common/h/Color.h"
#include "Spire/Doc/FileFormat.h"
using namespace std;
using namespace Spire::Doc;
using namespace Spire::Doc::Documents;
using namespace Spire::Doc::Formatting;
using namespace Spire::Doc::Common;

int main() {

    //Load the project brief document
    intrusive_ptr<Document> document = new Document();
    document->LoadFromFile("ProjectBrief.docx");

    intrusive_ptr<DocumentNavigator> navigator = new DocumentNavigator(document);

    //Move to the start of the document, restore body formatting, then write
    navigator->MoveToDocumentStart();
    navigator->GetCharacterFormat()->SetBold(false);
    navigator->GetCharacterFormat()->SetFontSize(10.5);
    navigator->GetCharacterFormat()->SetTextColor(Color::FromArgbRGB(51, 51, 51));
    navigator->Writeln("[Document Start] This document is maintained by the Project Management Department.");

    //The new paragraph inherits the title alignment; change it to left alignment
    navigator->MoveToParagraph(0, 0);
    navigator->GetParagraphFormat()->SetHorizontalAlignment(HorizontalAlignment::Left);

    //Move to the end of the document, start a new line, then write
    navigator->MoveToDocumentEnd();
    navigator->Writeln();
    navigator->Writeln("[Document End] If any of the above content changes, the latest version shall prevail.");

    //Save the document as docx
    document->SaveToFile("Output/MoveDocument.docx", FileFormat::Docx);
    document->Close();
    return 0;
}

After writing, the opening note appears before the title and the closing note appears after the body text, while the original paragraphs remain unchanged:

Content written at the start and end of the document

Writeln behavior at the end of the document

Writeln(text) writes text at the cursor and inserts a paragraph mark. When the cursor is at the end of the last paragraph, the text is appended after the content of that paragraph and before the paragraph mark, and the new paragraph starts on the next line. If the closing content is to occupy a paragraph of its own, call the parameterless Writeln() to insert a paragraph mark first and then write the text. The example follows this order, so the closing note forms a separate paragraph.

Write inserts at the cursor instead of overwriting

Write(text) inserts text from the current cursor position, and the original text shifts back without being replaced. When existing content is to be removed, the corresponding text should be deleted or the whole paragraph replaced; Write() cannot be relied on to overwrite. This differs from the "replace selection" semantics of some document processing interfaces, and programs that generate content by position need to take account of it.

New content inherits the formatting of the paragraph at the insertion point

A newly written paragraph and its text inherit the formatting of the paragraph in which the insertion point lies. In the example, the insertion point at the start of the document lies in the title paragraph, so writing directly would produce the title's font size and center alignment. The code first adjusts the font size, bold attribute, and color through GetCharacterFormat(), and then changes the alignment of the new paragraph to left alignment through MoveToParagraph(0, 0); the formatting of the original title is not affected.

Cursor position and document structure

MoveToDocumentStart() and MoveToDocumentEnd() position at the start and end of the whole document and are not affected by sections, headers, or footers. A header or footer requires positioning in a section first and then calling MoveToHeaderFooter(); the detailed steps are given in the next section.

Position the Header and Footer

MoveToSection(index) places the cursor in a specified section, and MoveToHeaderFooter(type) then positions at the header or footer of that section. Headers and footers belong to a section, so MoveToSection() should be called before switching to a header or footer each time.

The values of HeaderFooterType are listed below:

Type Position
HeaderEven Header on even pages
HeaderOdd Header on odd pages
FooterEven Footer on even pages
FooterOdd Footer on odd pages
HeaderFirstPage Header on the first page
FooterFirstPage Footer on the first page

The detailed steps are as follows.

  • Create a Document object and call LoadFromFile() to load the sample document.
  • Call Document->GetLastSection()->GetPageSetup()->SetDifferentFirstPageHeaderFooter(true) to enable a different header and footer on the first page.
  • Create a DocumentNavigator object and call MoveToSection(0) to position in the first section.
  • Call MoveToHeaderFooter(HeaderFooterType::HeaderFirstPage) to position at the first-page header and write text.
  • Call MoveToSection(0) and MoveToHeaderFooter(HeaderFooterType::FooterFirstPage) again to position at the first-page footer and write text.
  • Save the result document with Document->SaveToFile().

The code for writing the header and footer is shown below.

#include <iostream>
#include <string>
#include "Spire/Doc/pch.h"
#ifdef DocumentProperties
#undef DocumentProperties
#endif
#define DocumentProperties DocumentPropertiesA
#include "Spire/Doc/Document.h"
#include "Spire/Doc/Section.h"
#include "Spire/Doc/PageSetup.h"
#include "Spire/Doc/Documents/DocumentNavigator.h"
#include "Spire/Doc/Documents/Paragraph.h"
#include "Spire/Doc/Documents/HeaderFooterType.h"
#include "Spire/Doc/FileFormat.h"
using namespace std;
using namespace Spire::Doc;
using namespace Spire::Doc::Documents;

int main() {

    //Load the project brief document
    intrusive_ptr<Document> document = new Document();
    document->LoadFromFile("ProjectBrief.docx");

    intrusive_ptr<DocumentNavigator> navigator = new DocumentNavigator(document);

    //Enable a different header and footer on the first page
    document->GetLastSection()->GetPageSetup()->SetDifferentFirstPageHeaderFooter(true);

    //Move to the first-page header and write
    navigator->MoveToSection(0);
    navigator->MoveToHeaderFooter(HeaderFooterType::HeaderFirstPage);
    navigator->Write("Project Brief · First Page");

    //Move to the first-page footer and write
    navigator->MoveToSection(0);
    navigator->MoveToHeaderFooter(HeaderFooterType::FooterFirstPage);
    navigator->Write("Internal Document · Page 1");

    //Save the document as docx
    document->SaveToFile("Output/MoveHeaderFooter.docx", FileFormat::Docx);
    document->Close();
    return 0;
}

After writing, the header on the first page shows "Project Brief · First Page", and the footer shows "Internal Document · Page 1":

The project brief after the first-page header and footer are written

Headers and footers belong to sections

A header or footer is not an object shared by the whole document but belongs to its own section. MoveToSection(index) must be called before positioning at a header or footer; otherwise, the navigator remains in the section that was positioned last. A multi-section document requires positioning section by section and setting the header and footer of each section separately.

First-page and odd/even types require the corresponding option

A first-page header and footer and an even-page header and footer do not exist independently by default. Call SetDifferentFirstPageHeaderFooter(true) to enable a different first page before using HeaderFirstPage and FooterFirstPage, and call SetDifferentOddAndEvenPagesHeaderFooter(true) to enable different odd and even pages before using HeaderEven and FooterEven. Without the option, the corresponding type may have no independent content, and the written result will not appear on the expected page.

Headers and footers are saved separately from the body

The text in a header or footer is independent of the body. Paragraph indices in the body do not include header or footer content, and MoveToParagraph() does not position in a header or footer either. After the document is saved as docx, the header and footer remain with the section to which they belong; after a different first page is enabled, the header and footer of the original template continue to apply to the remaining pages.

Position a Specified Paragraph

MoveToParagraph(paragraphIndex, characterIndex) places the cursor at a specified character position in a specified paragraph. paragraphIndex starts at 0 and counts body paragraphs in the order in which they appear in the section; characterIndex is the character offset within the paragraph, and 0 means the start of the paragraph. After positioning, call Write() or Writeln() to write content at the cursor.

The detailed steps are as follows.

  • Create a Document object and call LoadFromFile() to load the sample document.
  • Create a DocumentNavigator object.
  • Call MoveToParagraph(2, 0) to position at the start of the third paragraph.
  • Call Write() to write the position marker.
  • Call GetCurrentParagraph()->GetText() to read the current paragraph and verify the written result.
  • Save the result document with Document->SaveToFile().

The code for positioning a paragraph is shown below.

#include <iostream>
#include <string>
#include "Spire/Doc/pch.h"
#ifdef DocumentProperties
#undef DocumentProperties
#endif
#define DocumentProperties DocumentPropertiesA
#include "Spire/Doc/Document.h"
#include "Spire/Doc/Documents/DocumentNavigator.h"
#include "Spire/Doc/Documents/Paragraph.h"
#include "Spire/Doc/FileFormat.h"
using namespace std;
using namespace Spire::Doc;
using namespace Spire::Doc::Documents;

int main() {

    //Load the project brief document
    intrusive_ptr<Document> document = new Document();
    document->LoadFromFile("ProjectBrief.docx");

    intrusive_ptr<DocumentNavigator> navigator = new DocumentNavigator(document);

    //Move to the first character of the third paragraph
    navigator->MoveToParagraph(2, 0);
    navigator->Write("[Navigator Position]");

    //Print the located paragraph to verify the result
    cout << "Current paragraph text: " << navigator->GetCurrentParagraph()->GetText() << endl;

    //Save the document as docx
    document->SaveToFile("Output/MoveParagraph.docx", FileFormat::Docx);
    document->Close();
    return 0;
}

The console output is shown below:

Current paragraph text: [Navigator Position]As the scale of warehousing continues to grow, the existing system can no longer meet business needs in terms of response speed during inbound receiving, stocktaking, and transfer. This project will build a unified warehousing management platform covering location management, batch traceability, and work scheduling.

The inserted text appears at the start of the third paragraph, and the original content of the paragraph shifts back as a whole:

Text written at the start of the third paragraph

Paragraph indices start at 0

MoveToParagraph(2, 0) in the example positions the third paragraph (index 2), which is the body paragraph after "1. Project Background". The index counts body paragraphs in the order in which they appear in the section; headings and body paragraphs are counted alike, and headers and footers are not included.

characterIndex controls the insertion position within the paragraph

When characterIndex is 0, the cursor is positioned at the start of the paragraph; when it is greater than 0, the cursor is positioned after the corresponding character. The example uses 0, so the text is inserted at the start of the paragraph; to append to the end of the paragraph, pass the length of the paragraph text. The character offset should be within the length of the paragraph text; if the offset exceeds that range, the positioning result is unreliable.

Text written by Write merges with the paragraph text

Text inserted by Write() merges with the original text into the same paragraph, and the paragraph formatting remains unchanged. The text inserted in the example inherits the first-line indent of the body paragraph and does not create a new paragraph. Reading GetCurrentParagraph()->GetText() verifies the insertion result, and other paragraphs can also be positioned and written before the document is saved.

Apply for a Temporary License

If you want to remove the evaluation message from the result document or lift the feature limitations, request a 30-day trial license.