C++ Insert, Configure, and Remove Footnotes and Endnotes in Word

Footnotes and endnotes provide supplementary explanations of the body text. Footnotes are placed at the bottom of the page by default, and endnotes are placed at the end of a section or document; the exact position is determined by the options. Both appear as a pair consisting of a reference marker and note text, and their numbering format, restart rule, and print position are controlled by the section's FootnoteOptions and EndnoteOptions.

Spire.Doc for C++ inserts a footnote or endnote into a paragraph through Paragraph->AppendFootnote(), adds note text through Footnote->GetTextBody(), sets the marker format through Footnote->GetMarkerCharacterFormat(), and adjusts numbering and position through Section->GetFootnoteOptions() and Section->GetEndnoteOptions().

This article covers three features:

The example uses the "Technical Specification for Smart Warehousing Equipment Procurement and Acceptance" (TechnicalSpecification.docx). The document has two pages and contains an equipment technical requirements table, an acceptance process, and after-sales service terms. Four technical clauses close with the warranty period, electrical control, test report, and software upgrade respectively, and serve as the anchors for inserting the notes.

The technical specification before footnotes and endnotes are inserted

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.

Insert a Footnote

Paragraph->AppendFootnote(FootnoteType::Footnote) appends a footnote object at the end of the current paragraph; a numbered marker appears in the body text and a note area appears at the bottom of the page. GetTextBody()->AddParagraph() returns the body paragraph of the footnote, to which text can be appended and character formatting applied; GetMarkerCharacterFormat() controls the font, font size, and weight of the marker independently.

Operation Method
Insert a footnote Paragraph->AppendFootnote(FootnoteType::Footnote)
Add footnote text Footnote->GetTextBody()->AddParagraph()->AppendText(text)
Set the note text format TextRange->GetCharacterFormat()
Set the marker format Footnote->GetMarkerCharacterFormat()
Read the note type Footnote->GetFootnoteType()

The detailed steps are as follows.

  • Create a Document object and call LoadFromFile() to load the sample document.
  • Traverse the body objects and locate the warranty period and electrical control clauses by keyword.
  • Call AppendFootnote() to insert a footnote at the end of the clause paragraph.
  • Append the note text through GetTextBody()->AddParagraph(), and set the font and font size.
  • Set the marker font and bold through GetMarkerCharacterFormat().
  • Save the document with SaveToFile().

The code for inserting footnotes 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/Body.h"
#include "Spire/Doc/DocumentObject.h"
#include "Spire/Doc/Collections/SectionCollection.h"
#include "Spire/Doc/Collections/DocumentObjectCollection.h"
#include "Spire/Doc/Documents/Paragraph.h"
#include "Spire/Doc/Fields/Footnote.h"
#include "Spire/Doc/Fields/TextRange.h"
#include "Spire/Doc/Formatting/CharacterFormat.h"
#include "Spire/Doc/FootnoteType.h"
#include "Spire/Doc/FileFormat.h"
using namespace std;
using namespace Spire::Doc;
using namespace Spire::Doc::Collections;
using namespace Spire::Doc::Documents;
using namespace Spire::Doc::Fields;

//Insert a footnote at the end of the paragraph that contains the keyword
static bool AddFootnoteAt(intrusive_ptr<Document> document, const string& keyword,
                          const string& note)
{
    intrusive_ptr<Section> section = document->GetSections()->GetItem(0);
    intrusive_ptr<DocumentObjectCollection> bodyItems = section->GetBody()->GetChildObjects();

    for (int i = 0; i < bodyItems->GetCount(); i++)
    {
        intrusive_ptr<DocumentObject> item = bodyItems->GetItem(i);
        if (!Object::CheckType<Paragraph>(item))
            continue;

        intrusive_ptr<Paragraph> paragraph = Object::Dynamic_cast<Paragraph>(item);
        if (paragraph->GetText().find(keyword) == string::npos)
            continue;

        //Append the footnote at the end of the paragraph; the marker follows the quoted text
        intrusive_ptr<Footnote> footnote = paragraph->AppendFootnote(FootnoteType::Footnote);

        //Add the footnote text and set its character format
        intrusive_ptr<TextRange> text = footnote->GetTextBody()->AddParagraph()->AppendText(note);
        text->GetCharacterFormat()->SetFontName("Arial");
        text->GetCharacterFormat()->SetFontSize(9);

        //Set the character format of the footnote marker in the body text
        footnote->GetMarkerCharacterFormat()->SetFontName("Calibri");
        footnote->GetMarkerCharacterFormat()->SetBold(true);
        return true;
    }
    return false;
}

int main() {

    //Load the equipment technical specification
    intrusive_ptr<Document> document = new Document();
    document->LoadFromFile("TechnicalSpecification.docx");

    //Insert a footnote after the warranty clause
    int added = 0;
    if (AddFootnoteAt(document, "not less than twenty-four months",
                      "In accordance with Appendix II, Quality Assurance Terms, of the contract, "
                      "the warranty period is calculated from the date of acceptance."))
        added++;

    //Insert a second footnote after the electrical control clause
    if (AddFootnoteAt(document, "electrical control system shall comply with",
                      "GB/T 5226.1 is a series of standards for the electrical safety of "
                      "machinery; the current edition is the 2019 edition."))
        added++;

    cout << "Inserted " << added << " footnotes" << endl;

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

The two footnotes are inserted at the end of the warranty period and electrical control clauses respectively. Numbers 1 and 2 and the corresponding note text appear at the bottom of the page, and the body markers match the note numbers. The console output is as follows.

Inserted 2 footnotes

Footnotes inserted after the clauses and notes at the bottom of the page

Insertion position determines marker position

AppendFootnote() appends the footnote marker to the end of the paragraph. The example selects clause paragraphs that end with the referenced content, so the marker follows the end of the sentence. To place the marker in the middle of a paragraph, obtain the index of the target text after appending and insert the footnote object at that position; the example does not demonstrate moving it within a paragraph.

Footnote text and marker are formatted separately

The format of the note text is set through TextRange->GetCharacterFormat(), and the number marker in the body text and at the bottom of the page is set through GetMarkerCharacterFormat(). The two do not affect each other, and different fonts and font sizes can be used for each.

Footnote count reflects the saved document

Document->GetFootnotes() returns the collection of footnotes that have been saved in the document. In this verification, a footnote that had just been appended and not yet saved was not counted in the return value; the example reports the result with an insertion counter. After the document is saved and reloaded, the collection returns two footnotes.

Insert Endnotes and Set Numbering and Position

Endnotes are inserted through AppendFootnote(FootnoteType::Endnote); the marker in the body text and the note text are located at the reference position and at the end of the section or document, respectively. The numbering rules for footnotes and endnotes are controlled by section options, and GetFootnoteOptions() and GetEndnoteOptions() return FootEndnoteOptions objects of the same type.

Operation Method
Insert an endnote Paragraph->AppendFootnote(FootnoteType::Endnote)
Read the footnote options Section->GetFootnoteOptions()
Read the endnote options Section->GetEndnoteOptions()
Set the numbering format SetNumberFormat(FootnoteNumberFormat::...)
Set the restart rule SetRestartRule(FootnoteRestartRule::...)
Set the print position SetPosition(FootnotePosition::...)

The detailed steps are as follows.

  • Create a Document object and load AddFootnotes.docx produced in the previous section.
  • Traverse the body objects and locate the test report and software upgrade clauses.
  • Call AppendFootnote() to insert two endnotes and add their text.
  • Obtain the section's footnote options and set upper-case Roman numerals, restart on each page, and bottom of page.
  • Obtain the section's endnote options and set lower-case Roman numerals, restart in each section, and end of section.
  • Save the document with SaveToFile().

The code for inserting endnotes and setting their numbering 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/Body.h"
#include "Spire/Doc/DocumentObject.h"
#include "Spire/Doc/FootEndnoteOptions.h"
#include "Spire/Doc/Collections/SectionCollection.h"
#include "Spire/Doc/Collections/DocumentObjectCollection.h"
#include "Spire/Doc/Documents/Paragraph.h"
#include "Spire/Doc/Fields/Footnote.h"
#include "Spire/Doc/Fields/TextRange.h"
#include "Spire/Doc/Formatting/CharacterFormat.h"
#include "Spire/Doc/FootnoteType.h"
#include "Spire/Doc/FootnoteNumberFormat.h"
#include "Spire/Doc/FootnotePosition.h"
#include "Spire/Doc/FootnoteRestartRule.h"
#include "Spire/Doc/FileFormat.h"
using namespace std;
using namespace Spire::Doc;
using namespace Spire::Doc::Collections;
using namespace Spire::Doc::Documents;
using namespace Spire::Doc::Fields;

//Insert an endnote at the end of the paragraph that contains the keyword
static bool AddEndnoteAt(intrusive_ptr<Document> document, const string& keyword,
                         const string& note)
{
    intrusive_ptr<Section> section = document->GetSections()->GetItem(0);
    intrusive_ptr<DocumentObjectCollection> bodyItems = section->GetBody()->GetChildObjects();

    for (int i = 0; i < bodyItems->GetCount(); i++)
    {
        intrusive_ptr<DocumentObject> item = bodyItems->GetItem(i);
        if (!Object::CheckType<Paragraph>(item))
            continue;

        intrusive_ptr<Paragraph> paragraph = Object::Dynamic_cast<Paragraph>(item);
        if (paragraph->GetText().find(keyword) == string::npos)
            continue;

        //Insert the endnote and add its text
        intrusive_ptr<Footnote> endnote = paragraph->AppendFootnote(FootnoteType::Endnote);
        intrusive_ptr<TextRange> text = endnote->GetTextBody()->AddParagraph()->AppendText(note);
        text->GetCharacterFormat()->SetFontName("Arial");
        text->GetCharacterFormat()->SetFontSize(9);
        return true;
    }
    return false;
}

int main() {

    //Load the specification document that already contains footnotes
    intrusive_ptr<Document> document = new Document();
    document->LoadFromFile("Output/AddFootnotes.docx");

    //Insert endnotes after the test report and software upgrade clauses
    int added = 0;
    if (AddEndnoteAt(document, "third-party testing agency",
                     "The test report shall be issued by an agency with CMA accreditation and "
                     "shall remain valid for no more than twelve months."))
        added++;
    if (AddEndnoteAt(document, "version upgrade service period",
                     "Upgrade services include major-version and patch updates; major upgrades "
                     "require thirty days' prior notice."))
        added++;

    intrusive_ptr<Section> section = document->GetSections()->GetItem(0);

    //Footnote numbers use upper-case Roman numerals, restart on each page, and print at the bottom of the page
    intrusive_ptr<FootEndnoteOptions> footnoteOptions = section->GetFootnoteOptions();
    footnoteOptions->SetNumberFormat(FootnoteNumberFormat::UpperCaseRoman);
    footnoteOptions->SetRestartRule(FootnoteRestartRule::RestartPage);
    footnoteOptions->SetPosition(FootnotePosition::PrintAtBottomOfPage);
    footnoteOptions->SetStartNumber(1);

    //Endnote numbers use lower-case Roman numerals, restart in each section, and print at the end of the section
    intrusive_ptr<FootEndnoteOptions> endnoteOptions = section->GetEndnoteOptions();
    endnoteOptions->SetNumberFormat(FootnoteNumberFormat::LowerCaseRoman);
    endnoteOptions->SetRestartRule(FootnoteRestartRule::RestartSection);
    endnoteOptions->SetPosition(FootnotePosition::PrintAsEndOfSection);
    endnoteOptions->SetStartNumber(1);

    cout << "Footnotes in document: " << document->GetFootnotes().size()
         << ", endnotes inserted in this section: " << added << endl;

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

The two footnotes in the document use upper-case Roman numerals I and II, and the two endnotes use lower-case Roman numerals i and ii; the endnote text is placed at the end of the document. The console output is as follows.

Footnotes in document: 2, endnotes inserted in this section: 2

Endnotes numbered with lower-case Roman numerals

Footnotes and endnotes use separate option objects

Section->GetFootnoteOptions() affects only footnotes, and Section->GetEndnoteOptions() affects only endnotes. The two are of the same type but cannot substitute for each other: a position set through the footnote options does not apply to endnotes.

Numbering and position apply per section

RestartPage restarts numbering on each page, RestartSection restarts numbering in each section, and DoNotRestart keeps numbering continuous throughout the document. PrintAtBottomOfPage prints footnotes at the bottom of the page, and PrintAsEndOfSection and PrintAsEndOfDocument control where endnotes are printed. After making changes, the numbering continuity of a document that spans several sections should be checked.

Endnotes are located at the end of a section or document

The endnote position is controlled by FootnotePosition. The example sets the endnote position to PrintAsEndOfSection, so the two endnotes are placed at the end of the last section; when they are to be collected at the end of the document, PrintAsEndOfDocument should be used instead. When a document contains several sections, endnotes are distributed according to the position of each section.

Remove Footnotes and Endnotes

Removing notes requires traversing the child objects of body paragraphs. Footnote and endnote objects appear in a paragraph's child object collection with the Footnote type, and GetFootnoteType() distinguishes the two. The example traverses the child objects in reverse so that deleting the current object does not affect indexes that have not yet been checked.

Operation Method
Traverse body objects Section->GetBody()->GetChildObjects()
Check the object type Object::CheckType<Footnote>()
Read the note type Footnote->GetFootnoteType()
Delete an object DocumentObjectCollection->RemoveAt(index)
Traverse in reverse Decrement from GetCount() - 1 to 0

The detailed steps are as follows.

  • Create a Document object and load AddEndnotes.docx, which contains both footnotes and endnotes.
  • Output the number of footnotes and endnotes before removal.
  • Traverse the paragraphs among the body objects of each section.
  • Traverse the child objects of each paragraph in reverse and check for the Footnote type.
  • Delete footnotes and endnotes separately according to FootnoteType, and accumulate the counts.
  • Save the document and output the removal counts.

The code for removing footnotes and endnotes 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/Body.h"
#include "Spire/Doc/DocumentObject.h"
#include "Spire/Doc/Collections/SectionCollection.h"
#include "Spire/Doc/Collections/DocumentObjectCollection.h"
#include "Spire/Doc/Documents/Paragraph.h"
#include "Spire/Doc/Fields/Footnote.h"
#include "Spire/Doc/FootnoteType.h"
#include "Spire/Doc/FileFormat.h"
using namespace std;
using namespace Spire::Doc;
using namespace Spire::Doc::Collections;
using namespace Spire::Doc::Documents;
using namespace Spire::Doc::Fields;

int main() {

    //Load the document that contains both footnotes and endnotes
    intrusive_ptr<Document> document = new Document();
    document->LoadFromFile("Output/AddEndnotes.docx");

    cout << "Before removal: " << document->GetFootnotes().size()
         << " footnotes, " << document->GetEndnotes().size() << " endnotes" << endl;

    //Traverse the body objects of the section and remove the footnote and endnote references in paragraphs
    int removedFootnotes = 0;
    int removedEndnotes = 0;
    intrusive_ptr<Section> section = document->GetSections()->GetItem(0);
    intrusive_ptr<DocumentObjectCollection> bodyItems = section->GetBody()->GetChildObjects();

    for (int i = 0; i < bodyItems->GetCount(); i++)
    {
        intrusive_ptr<DocumentObject> item = bodyItems->GetItem(i);
        if (!Object::CheckType<Paragraph>(item))
            continue;

        intrusive_ptr<Paragraph> paragraph = Object::Dynamic_cast<Paragraph>(item);
        intrusive_ptr<DocumentObjectCollection> children = paragraph->GetChildObjects();

        //Traverse in reverse so that removal does not affect indexes that have not been checked
        for (int j = children->GetCount() - 1; j >= 0; j--)
        {
            intrusive_ptr<DocumentObject> child = children->GetItem(j);
            if (!Object::CheckType<Footnote>(child))
                continue;

            intrusive_ptr<Footnote> note = Object::Dynamic_cast<Footnote>(child);
            if (note->GetFootnoteType() == FootnoteType::Footnote)
            {
                children->RemoveAt(j);
                removedFootnotes++;
            }
            else if (note->GetFootnoteType() == FootnoteType::Endnote)
            {
                children->RemoveAt(j);
                removedEndnotes++;
            }
        }
    }

    cout << "Removed " << removedFootnotes << " footnotes and "
         << removedEndnotes << " endnotes" << endl;

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

After saving, the reference markers in the body text and the footnote area at the bottom of the page disappear at the same time, and no endnotes are displayed at the end of the document. The console output is as follows.

Before removal: 2 footnotes, 2 endnotes
Removed 2 footnotes and 2 endnotes

The body text and page bottom after footnotes and endnotes are removed

Reverse traversal avoids index shifting

After an element is deleted from a collection, the indexes of the following elements shift forward. The example traverses from the end toward the beginning, so deleting the current object does not affect elements that have not yet been checked. With a forward traversal, the index should be moved back after each deletion.

Removing note objects does not delete body text

RemoveAt() deletes only the note reference object in the paragraph and its note content; the body text remains unchanged. After the example removes the two footnotes, the text of the warranty period and electrical control clauses is still present, and only the number markers are missing.

Count notes after saving

After notes are deleted in memory, Document->GetFootnotes() and Document->GetEndnotes() may still return the counts from before the deletion. In this verification, the collections still returned two entries after deletion and returned zero after the document was saved and reloaded. The example reports the result with traversal counters.

Footnotes and endnotes both exist as child objects of a paragraph. When inserting, the type is specified through AppendFootnote(), and the note text and marker are formatted separately; the numbering, restart rule, and print position are controlled by section options; when removing, the child objects are traversed and deleted by type. When a document that spans several sections is processed, the numbering continuity of both footnotes and endnotes should be checked.

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.