C++ Compare Two Word Documents

Document comparison turns the differences between one version and another into revisions, which a reviewer can accept or reject one by one. The comparison uses one document as the base and the other as the reference. Insertions and deletions of text, paragraph adjustments, and formatting changes can all be recorded as revisions, and the revision author and time are saved together with each revision.

Spire.Doc for C++ performs the comparison with Document->Compare(), and the differences are written into the document that calls the method. To control the comparison scope, pass a CompareOptions object to ignore, for example, formatting differences, headers and footers, or tables. After the comparison, call GetRevisionInfos()->GetCount() to obtain the number of revisions, and save the document to view the revisions in Word.

This article covers two features:

The examples use two versions of the "Smart Warehouse Equipment Procurement Specification": PurchaseDraft.docx is the discussion draft, and PurchaseFinal.docx is the revised draft. The revised draft adjusts the delivery period and the warranty period, adds acceptance text, replaces the cash-on-delivery clause in the payment terms, and applies bold and a dark blue color to part of the last paragraph. It also changes the header and footer text, adjusts the letter case of the document number, and updates the sampling ratio of the "Runtime test" item in the acceptance checklist.

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.

The comparison operation involves the following members:

Member Purpose
Document->Compare(other, author) Compares another document against the current document as the base
Document->Compare(other, author, date, options) Specifies the comparison time and options
CompareOptions->SetIgnoreFormatting(true) Ignores formatting differences
CompareOptions->SetIgnoreCaseChanges(true) Ignores case differences
CompareOptions->SetIgnoreHeadersAndFooters(true) Ignores headers and footers
CompareOptions->SetIgnoreTables(true) Ignores tables
CompareOptions->SetIgnoreComments(true) Ignores comments
Document->GetRevisionInfos() Returns the revision collection
RevisionInfoCollection->GetCount() Returns the revision count

Standard Comparison

A standard comparison specifies only the revision author; the comparison time defaults to the current time, and all differences are recorded as revisions. The example loads the discussion draft and the revised draft, calls Compare() with the discussion draft as the base, outputs the revision count, and then saves the discussion draft.

Operation Method Description
Load the base document LoadFromFile(path) Differences are written into this document
Load the reference document LoadFromFile(path) Read-only; not modified
Compare the documents Compare(other, author) The author name is written into the revisions
Count the revisions GetRevisionInfos()->GetCount() Returns an int
Save the result SaveToFile(path, format) Saves the base document with revisions

The detailed steps are as follows.

  • Create two Document objects and call LoadFromFile() to load the discussion draft and the revised draft respectively.
  • Call Compare(doc2, "Reviewer") with the discussion draft as the base.
  • Call GetRevisionInfos()->GetCount() to output the revision count.
  • Call SaveToFile() to save the discussion draft with revisions.
  • Close both documents.

The code for the standard comparison 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/FileFormat.h"
#include "Spire/Doc/RevisionInfoCollection.h"
#include "Spire/Doc/common/h/Stream.h"
using namespace std;
using namespace Spire::Doc;
using namespace Spire::Doc::Common;

int main()
{
    SetConsoleOutputCP(CP_UTF8);

    // Load the base document and the revised document
    intrusive_ptr<Document> doc1 = new Document();
    doc1->LoadFromFile("PurchaseDraft.docx");
    intrusive_ptr<Document> doc2 = new Document();
    doc2->LoadFromFile("PurchaseFinal.docx");

    // Compare doc2 against doc1; the differences are written into doc1 as revisions
    doc1->Compare(doc2, "Reviewer");
    cout << "Revision count: " << doc1->GetRevisionInfos()->GetCount() << endl;

    // Save the base document with revisions
    doc1->SaveToFile("Output/CompareDocuments.docx", FileFormat::Docx);
    doc1->Close();
    doc2->Close();
    return 0;
}

The console outputs the number of revisions produced by this comparison:

Revision count: 22

The saved document shows the differences between the two versions as revisions: changed values and inserted text are marked with a colored underline, deleted content is shown with strikethrough, and changes in the table and the case change in the document number are also recorded as revisions. The balloons on the right list the deleted text and the revision author:

Revisions generated by the standard comparison (22)

Comparison Results Are Written into the Document That Calls Compare

doc1->Compare(doc2, ...) uses doc1 as the base and writes the differences of doc2 relative to doc1 into doc1; doc2 remains unchanged. When the saved file is opened, it is the base document with revisions. To keep the original discussion draft, copy the file before the comparison or save the result under a new file name. The example saves the result as CompareDocuments.docx, and the original file is not affected.

The Revision Author and Time Support Review

The second parameter is the revision author, and the example passes "Reviewer". Word distinguishes revisions by author, so when accepting or rejecting changes, the changes made by a particular author can be filtered. The time of a standard comparison defaults to the current time, and the balloons are ordered by that time. When a fixed comparison time is required, use the overload that accepts a DateTime parameter.

The Revision Count Depends on the Comparison Result

GetRevisionInfos() returns the collection of revisions generated by the comparison, and the count depends on the differences between the two versions. In the example, the revised draft contains value adjustments, new sentences, deleted text, formatting changes, rewritten header and footer text, a case change, and a table change, which together produce 22 revisions. The collection reflects only the revisions in the current document, and its count changes with the differences between the two versions.

Comparison with Options

A comparison with options passes a DateTime and a CompareOptions object to Compare() and disables the comparison of a particular kind of difference as needed. Each switch in CompareOptions is turned off by default. The example enables the four options for ignoring formatting, tables, headers and footers, and case changes at the same time, so that these four kinds of differences do not produce revisions and only insertions, deletions, and replacements in the body text are retained.

Option Method Effect
Ignore formatting SetIgnoreFormatting(true) Does not compare fonts, font sizes, colors, or paragraph formatting
Ignore case changes SetIgnoreCaseChanges(true) Does not treat a change in letter case as a difference
Ignore comments SetIgnoreComments(true) Does not compare comments
Ignore fields SetIgnoreFields(true) Does not compare field codes and field results
Ignore footnotes SetIgnoreFootnotes(true) Does not compare footnotes
Ignore headers and footers SetIgnoreHeadersAndFooters(true) Does not compare headers and footers
Ignore tables SetIgnoreTables(true) Does not compare table content
Ignore text boxes SetIgnoreTextboxes(true) Does not compare text boxes
Detect moves SetCompareMoves(true) Records the movement of text or paragraphs as move revisions
Comparison level SetTextCompareLevel(TextDiffMode::Word/Char) Compares by word or by character; the default is Word

The detailed steps are as follows.

  • Create two Document objects and load the discussion draft and the revised draft respectively.
  • Create a CompareOptions object and call SetIgnoreFormatting(true), SetIgnoreTables(true), SetIgnoreHeadersAndFooters(true), and SetIgnoreCaseChanges(true) in turn.
  • Call Compare(doc2, "Reviewer", DateTime::GetNow(), options).
  • Call GetRevisionInfos()->GetCount() to output the revision count.
  • Call SaveToFile() to save the result document.

The code for the comparison with options 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/Comparison/CompareOptions.h"
#include "Spire/Doc/FileFormat.h"
#include "Spire/Doc/RevisionInfoCollection.h"
#include "Spire/Doc/common/h/DateTime.h"
#include "Spire/Doc/common/h/Stream.h"
using namespace std;
using namespace Spire::Doc;
using namespace Spire::Doc::Common;
using namespace Spire::Doc::Documents::Comparison;

int main()
{
    SetConsoleOutputCP(CP_UTF8);

    // Load the base document and the revised document
    intrusive_ptr<Document> doc1 = new Document();
    doc1->LoadFromFile("PurchaseDraft.docx");
    intrusive_ptr<Document> doc2 = new Document();
    doc2->LoadFromFile("PurchaseFinal.docx");

    // Disable the comparison of formatting, table, header/footer, and case differences
    CompareOptions* options = new CompareOptions();
    options->SetIgnoreFormatting(true);
    options->SetIgnoreTables(true);
    options->SetIgnoreHeadersAndFooters(true);
    options->SetIgnoreCaseChanges(true);
    doc1->Compare(doc2, "Reviewer", DateTime::GetNow(), options);
    cout << "Revision count after ignoring multiple differences: " << doc1->GetRevisionInfos()->GetCount() << endl;

    // Save the base document with revisions
    doc1->SaveToFile("Output/CompareDocumentsWithOptions.docx", FileFormat::Docx);
    doc1->Close();
    doc2->Close();
    return 0;
}

The console shows that the revision count falls from 22 to 13:

Revision count after ignoring multiple differences: 13

The saved document no longer shows the formatting revisions in the last paragraph, and the changes in the header and footer, the case of the document number, and the acceptance checklist no longer produce revisions. The text changes and deletions in the body are still retained as revisions:

Revisions after ignoring formatting, table, header/footer, and case differences (13)

Revision Count for Each Option

Enabling a single switch on the same pair of documents shows how each option affects the revision count. In the following table, the author and the comparison time are the same in every row; only the comparison configuration differs.

Comparison configuration Revision count
Default comparison 22
Ignore formatting only 20
Ignore tables only 20
Ignore headers and footers only 19
Ignore case changes only 20
All four options above 13
Character-level comparison 23

Ignore Formatting (22 → 20)

SetIgnoreFormatting(true) prevents differences in fonts, font sizes, colors, and paragraph formatting from producing revisions. The revised draft sets part of the last paragraph in bold and dark blue, and a standard comparison records these formatting changes as 2 formatting revisions. With the option enabled, the formatting revisions are no longer generated, and the revision count changes from 22 to 20. Insertions, deletions, and replacements of the text itself still produce revisions.

Ignore Tables (22 → 20)

SetIgnoreTables(true) excludes table content from the comparison. The revised draft changes the sampling ratio of the "Runtime test" item in the acceptance checklist from 10% to 20%, and a standard comparison produces 2 revisions (deleting 10 and inserting 20). With the option enabled, the table is retained as it appears in the base document, the sampling ratio in the result remains 10%, and the revision count is 20. Content outside the table is compared as usual.

Ignore Headers and Footers (22 → 19)

SetIgnoreHeadersAndFooters(true) excludes headers and footers from the comparison. The header of the revised draft gains the text "(Revised)", and the footer changes from "Internal Discussion Draft" to "Internal Revised Draft", which together produce 3 revisions. With the option enabled, these revisions are no longer generated, and the revision count is 19. Revisions in the header and footer appear in the header and footer areas at the top and bottom of the page, whereas the article figures show only the middle of the page, so the balloons for these revisions do not appear in the figures.

Ignore Case Changes (22 → 20)

SetIgnoreCaseChanges(true) prevents a change in letter case from being treated as a difference. The document number in the discussion draft is WH-2026-018, and the revised draft writes it as wh-2026-018. A standard comparison records 2 revisions, deleting WH and inserting wh. With the option enabled, the numbers are treated as the same, and the revision count is 20.

Option Combinations and Character-Level Comparison

The four switches act on different areas and do not affect one another. When all four are enabled, the revision count is 22 - 2 - 2 - 3 - 2 = 13. When several kinds of differences need to be ignored at the same time, call several Set* methods in succession and pass the same CompareOptions object to a single comparison.

SetTextCompareLevel() controls the granularity of the text comparison. The default is TextDiffMode::Word, which compares by word. Passing TextDiffMode::Char compares by character, and consecutive changes are split into finer insertions and deletions. For the same pair of documents, the revision count changes from 22 to 23.

The sample documents contain no comments, fields, footnotes, text boxes, or paragraph moves, so SetIgnoreComments(), SetIgnoreFields(), SetIgnoreFootnotes(), SetIgnoreTextboxes(), and SetCompareMoves() have no effect on this result; their scope is described in the table above.

Options Apply Only to the Call That Receives Them

CompareOptions takes effect only in the Compare() call to which it is passed. It is not written into the document and does not affect later comparisons. The example creates a separate object and sets four options, leaving the other options at their default value of false. When a different ignore scope is needed for each comparison, create a new object and set the corresponding switches.

The Overload Determines the Comparison Time

The overload with options accepts a DateTime parameter, and the example passes DateTime::GetNow(). The comparison time is written into the revision metadata for Word to display and for review. When a fixed comparison time is required for auditing, pass a specified DateTime. The overload that accepts only the author also compares with the current time.

Get a Free License

If you want to remove the evaluation message from the generated documents, or to get rid of the function limitations, please apply for a 30-day temporary license.