Text replacement can write only a string and cannot preserve paragraphs, tables, lists, or field structures. Placeholders in contracts, project charters, and report templates frequently need to be replaced with a block of explanatory text, a table, a formatted HTML passage, or a date field that updates automatically. Such operations require locating the placeholder first and then inserting new document objects at the paragraph or body level.
Spire.Doc for C++ provides Document->Replace(), Paragraph->AppendHTML(), and insertion methods on body object collections for rich-content replacement. A search returns a TextSelection; GetAsOneRange() obtains the TextRange that contains the placeholder, from which the owning paragraph and its index can be read. When a table, a field, or a cloned paragraph is inserted, that index serves as the reference point. All processing takes place in the local process, and the document does not need to be uploaded to any service.
This article covers four features:
- Replace text with a Word document
- Replace text with an HTML snippet
- Replace text with a table
- Replace text with a field
The examples use the "Project Charter" template (ProjectCharter.docx), which reserves four bracketed placeholders:
| Placeholder | Replaced with | Main calls |
|---|---|---|
[PROJECT_OVERVIEW] |
Another Word document | Document->Replace() |
[DELIVERY_SCOPE] |
HTML snippet | Paragraph->AppendHTML() and ChildObjects->Insert() |
[MILESTONES] |
Table | Section->AddTable() and ChildObjects->Insert() |
[SIGN_DATE] |
DATE field | Field and FieldMark |

Each of the first three placeholders in the template occupies its own paragraph, whereas the signature date sits in the middle of the signature line, with the text "Signature date: " before it and "(effective upon approval)" after it. The document, HTML, and table examples operate on paragraph boundaries; the field example removes only the placeholder range and keeps the rest of the paragraph.
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.Cppin the project directory, and then add the package'sincludeandlibfolders to the project.
An integrated project needs to reference the corresponding dynamic libraries and to ensure that SpireDocCpp.dll, Spire.Doc.Base.dll, libSkiaSharp.dll, and libHarfBuzzSharp.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 examples use version 14.9.x, with std::string as UTF-8 narrow strings. Source files that contain non-ASCII characters should be saved as UTF-8, and the /utf-8 compiler option should be enabled in MSVC so that such characters in string literals are recognized correctly.
Replace Text with a Word Document
To replace text with a Word document, call Document->Replace() to substitute the matched text with the content of another document. When the source is a document, the method signature is int Replace(const std::string& matchString, intrusive_ptr<Document> matchDoc, bool caseSensitive, bool wholeWord), and the return value is the number of replacements actually made.
| Parameter | Meaning |
|---|---|
matchString |
The placeholder text to find |
matchDoc |
The document object used for replacement |
caseSensitive |
Whether matching is case-sensitive |
wholeWord |
Whether to match only whole words |
The detailed steps are as follows.
- Create a Document object.
- Load the template document with the Document->LoadFromFile() method.
- Create another Document object and load the Word document used for replacement.
- Call Document->Replace(), specifying the replacement content with
matchDoc. - Save the result document with the Document->SaveToFile() method.
The code for replacing text with a Word 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/FileFormat.h"
using namespace std;
using namespace Spire::Doc;
int main()
{
//Specify the input file paths
string inputFilePath = "ProjectCharter.docx";
string overviewFilePath = "ProjectOverview.docx";
//Specify the output file path and name
string outputPath = "Output/";
string outputFile = outputPath + "ReplaceWithDocument.docx";
//Create a Document object and load the template
intrusive_ptr<Document> document = new Document();
document->LoadFromFile(inputFilePath);
//Load the document used for replacement
intrusive_ptr<Document> overview = new Document();
overview->LoadFromFile(overviewFilePath);
//Replace the placeholder with the content of another document
int count = document->Replace("[PROJECT_OVERVIEW]", overview, false, false);
cout << "Replaced: " << count << endl;
//Save the result file
document->SaveToFile(outputFile, FileFormat::Docx2013);
overview->Close();
document->Close();
return 0;
}
Sample output is Replaced: 1. [PROJECT_OVERVIEW] in the template is replaced by the heading, paragraphs, and bulleted list of the "Project Overview" document, while the rest of the template remains unchanged:
![Project overview after [PROJECT_OVERVIEW] is replaced with a Word document](https://cdn.e-iceblue.com/images/articles/2026/11/CPP-Replace-Text-With-Document-HTML-Table-Field-2.webp)
The Return Value Is the Number of Replacements
Document->Replace() returns the number of replacements actually made in the whole document, not a Boolean value. The sample template contains only one [PROJECT_OVERVIEW], so it returns 1. When many templates are processed in a batch, the return values can be accumulated, or a log entry can be written when the count is 0 to investigate placeholder spelling and matching parameters.
Match Parameters and Placeholder Syntax
The last two parameters control case sensitivity and whole-word matching. The sample uses false, false, which ignores case and allows a placeholder that occurs inside a longer string to match. Placeholders are not limited to square brackets; forms such as @@OVERVIEW@@ and {{milestones}} work equally well. Square brackets are conspicuous and unlikely to conflict with body text, which makes them easy to verify by eye in a template.
Source Content Is Inserted Together with Its Formatting
During replacement, the paragraphs, character formatting, and list structure of the source document are copied to the target position, and the source document itself is not modified. The sample calls overview->Close() after replacement to release resources. If only some paragraphs of the source document should be inserted, Replace() need not be used: locate the placeholder with FindString(), obtain the owning paragraph and body index, then traverse the sections and paragraphs of the source document, clone the required paragraphs, and insert them at that index before removing the placeholder range. The inserted paragraphs retain the source formatting, which suits paragraph-by-paragraph filtering or adjustment before insertion.
Replace Text with an HTML Snippet
To replace text with an HTML snippet, Paragraph->AppendHTML() first parses the HTML into Word objects, which are then written into the body that owns the paragraph. The parse result may contain several paragraphs and list items, so the sample generates these objects in a temporary section, collects them in an array, and inserts them at the placeholder position. The handling differs depending on whether the placeholder is at the start of the paragraph, at the end, or in the middle.
| Placeholder position | Handling |
|---|---|
Start (index == 0) |
Remove the first object of the paragraph and insert the replacement objects at the paragraph position |
End (index == count - 1) |
Remove the last object of the paragraph and insert the replacement objects after the paragraph |
| Middle | Clone the original paragraph, split the content before and after the placeholder, and insert the replacement objects in between |
The detailed steps are as follows.
- Create a Document object and load the template document.
- Read the HTML file with
ifstreamto obtain a UTF-8 string. - Call Document->AddSection() to create a temporary section, and call Paragraph->AppendHTML() on a temporary paragraph to parse the HTML.
- Traverse the body of the temporary section and collect the generated objects.
- Call Document->FindAllString() to find all placeholders and record the owning paragraph, range, and index of each.
- Insert the replacement objects from back to front, and remove the placeholder ranges.
- Call SectionCollection->Remove() to delete the temporary section, and save the result document.
The code for replacing text with an HTML snippet is shown below. In addition to the header files above, it includes Spire/Doc/Body.h, Spire/Doc/DocumentObject.h, Spire/Doc/Collections/DocumentObjectCollection.h, Spire/Doc/Documents/Paragraph.h, Spire/Doc/Documents/TextSelection.h, Spire/Doc/Fields/TextRange.h, Spire/Doc/Section.h, and Spire/Doc/common/h/Object.h.
#include <iostream>
#include <fstream>
#include <iterator>
#include <string>
#include <vector>
#include <algorithm>
#include "Spire/Doc/pch.h"
#ifdef DocumentProperties
#undef DocumentProperties
#endif
#define DocumentProperties DocumentPropertiesA
#include "Spire/Doc/Body.h"
#include "Spire/Doc/Collections/DocumentObjectCollection.h"
#include "Spire/Doc/Collections/SectionCollection.h"
#include "Spire/Doc/Document.h"
#include "Spire/Doc/DocumentObject.h"
#include "Spire/Doc/Documents/Paragraph.h"
#include "Spire/Doc/Documents/TextSelection.h"
#include "Spire/Doc/Fields/TextRange.h"
#include "Spire/Doc/FileFormat.h"
#include "Spire/Doc/Section.h"
#include "Spire/Doc/common/h/Object.h"
using namespace std;
using namespace Spire::Doc;
using namespace Spire::Doc::Collections;
using namespace Spire::Doc::Common;
using namespace Spire::Doc::Documents;
using namespace Spire::Doc::Fields;
struct PlaceholderLocation
{
intrusive_ptr<TextRange> range;
intrusive_ptr<Paragraph> paragraph;
intrusive_ptr<Body> body;
int paragraphIndex;
int rangeIndex;
};
//Insert the collected objects at the placeholder position
void ReplaceWithHTML(PlaceholderLocation location,
vector<intrusive_ptr<DocumentObject>>& replacement)
{
int index = location.rangeIndex;
intrusive_ptr<Paragraph> paragraph = location.paragraph;
intrusive_ptr<Body> sectionBody = location.body;
int replacementIndex = -1;
if (index == 0)
{
//Start of paragraph: remove the first object and insert at the paragraph position
paragraph->GetChildObjects()->RemoveAt(0);
replacementIndex = sectionBody->GetChildObjects()->IndexOf(paragraph);
}
else if (index == paragraph->GetChildObjects()->GetCount() - 1)
{
//End of paragraph: remove the last object and insert after the paragraph
paragraph->GetChildObjects()->RemoveAt(index);
replacementIndex = location.paragraphIndex + 1;
}
else
{
//Middle of paragraph: split the original paragraph and keep the preceding content in it
intrusive_ptr<Paragraph> tail =
Object::Dynamic_cast<Paragraph>(paragraph->Clone());
while (paragraph->GetChildObjects()->GetCount() > index)
{
paragraph->GetChildObjects()->RemoveAt(index);
}
int stop = index + 1;
for (int i = 0; i < stop; i++)
{
tail->GetChildObjects()->RemoveAt(0);
}
sectionBody->GetChildObjects()->Insert(location.paragraphIndex + 1, tail);
replacementIndex = location.paragraphIndex + 1;
}
for (size_t i = 0; i < replacement.size(); i++)
{
sectionBody->GetChildObjects()->Insert(replacementIndex + (int)i,
replacement[i]->Clone());
}
}
int main()
{
//Specify the input file paths
string inputFilePath = "ProjectCharter.docx";
string htmlFilePath = "ScopeSnippet.html";
//Specify the output file path and name
string outputPath = "Output/";
string outputFile = outputPath + "ReplaceWithHtml.docx";
//Read the HTML snippet
ifstream htmlFile(htmlFilePath);
string html((istreambuf_iterator<char>(htmlFile)), istreambuf_iterator<char>());
//Load the template
intrusive_ptr<Document> document = new Document();
document->LoadFromFile(inputFilePath);
//Parse the HTML in a temporary section and collect the generated objects
vector<intrusive_ptr<DocumentObject>> replacement;
intrusive_ptr<Section> tempSection = document->AddSection();
intrusive_ptr<Paragraph> holder = tempSection->AddParagraph();
holder->AppendHTML(html);
for (int i = 0; i < tempSection->GetBody()->GetChildObjects()->GetCount(); i++)
{
replacement.push_back(tempSection->GetBody()->GetChildObjects()->GetItem(i));
}
//Record the position of each placeholder
vector<PlaceholderLocation> locations;
vector<intrusive_ptr<TextSelection>> selections =
document->FindAllString("[DELIVERY_SCOPE]", false, false);
for (intrusive_ptr<TextSelection> selection : selections)
{
PlaceholderLocation location;
location.range = selection->GetAsOneRange();
location.paragraph = location.range->GetOwnerParagraph();
location.body = location.paragraph->GetOwnerTextBody();
location.paragraphIndex = location.body->GetChildObjects()->IndexOf(location.paragraph);
location.rangeIndex = location.paragraph->GetChildObjects()->IndexOf(location.range);
locations.push_back(location);
}
//Process from back to front so earlier indexes are not shifted by insertions
sort(locations.begin(), locations.end(),
[](const PlaceholderLocation& a, const PlaceholderLocation& b)
{
if (a.paragraphIndex != b.paragraphIndex)
return a.paragraphIndex > b.paragraphIndex;
return a.rangeIndex > b.rangeIndex;
});
for (PlaceholderLocation location : locations)
{
ReplaceWithHTML(location, replacement);
}
//Delete the temporary section
document->GetSections()->Remove(tempSection);
//Save the result file
document->SaveToFile(outputFile, FileFormat::Docx2013);
document->Close();
return 0;
}
ScopeSnippet.html in the sample contains a level-3 heading, an explanatory paragraph, and a four-item list. After execution, [DELIVERY_SCOPE] is replaced by HTML content with a heading, an explanation, and a bulleted list:
![Delivery content after [DELIVERY_SCOPE] is replaced with an HTML snippet](https://cdn.e-iceblue.com/images/articles/2026/11/CPP-Replace-Text-With-Document-HTML-Table-Field-3.webp)
Supported HTML Elements
Paragraph->AppendHTML() supports common block-level and inline elements, including headings, paragraphs, lists, tables, bold, italic, and inline styles. External style sheets, scripts, and complex CSS positioning do not take effect, and page layout is recalculated according to the Word paragraph and table model. When precise control of the layout is required, constructing Word objects directly is more reliable than relying on HTML.
Process Multiple Placeholders from Back to Front
Inserting replacement objects changes the indexes of subsequent body objects. The sample first collects the positions of all placeholders, sorts them by paragraph index and range index in descending order, and then replaces them in turn. In this way, the positions of placeholders that have not yet been processed are not affected by inserted content. If they were processed from front to back, subsequent indexes would all shift, and content would easily be inserted in the wrong place.
Split the Paragraph When the Placeholder Is in the Middle
At the start and end of a paragraph, only the object that contains the placeholder is removed and the replacement content is inserted. In the middle of a paragraph, the original paragraph is first cloned, the objects after the placeholder are kept in the clone, the same objects are removed from the end of the original paragraph, and the replacement objects are inserted between the two. [DELIVERY_SCOPE] in the sample template occupies a paragraph of its own, so the start-of-paragraph branch is used; if the template is modified so that the placeholder shares a paragraph with body text, the other branches still apply.
Replace Text with a Table
Replacing text with a table works on paragraph boundaries: locate the placeholder, obtain its paragraph and body index, create and fill the table, then remove the original paragraph and insert the table at the same position. Column widths, header shading, banded row shading, and cell padding can all be set before insertion.
The detailed steps are as follows.
- Create a Document object and load the template document.
- Call Document->FindString() to locate the placeholder and obtain its paragraph and body index.
- Call Section->AddTable() to create a table, and use Table->ResetCells() to set the row and column counts and fill in the content.
- Call TableRow->SetIsHeader() to mark the header row, and use CellFormat->GetShading() to set cell shading.
- Remove the paragraph that contains the placeholder and insert the table at the same index.
- Save the result document with the Document->SaveToFile() method.
The code for replacing text with a table is shown below.
#include <iostream>
#include <string>
#include <vector>
#include "Spire/Doc/pch.h"
#ifdef DocumentProperties
#undef DocumentProperties
#endif
#define DocumentProperties DocumentPropertiesA
#include "Spire/Doc/Body.h"
#include "Spire/Doc/Collections/CellCollection.h"
#include "Spire/Doc/Collections/DocumentObjectCollection.h"
#include "Spire/Doc/Collections/ParagraphCollection.h"
#include "Spire/Doc/Collections/RowCollection.h"
#include "Spire/Doc/Collections/SectionCollection.h"
#include "Spire/Doc/Document.h"
#include "Spire/Doc/Documents/HorizontalAlignment.h"
#include "Spire/Doc/Documents/Paragraph.h"
#include "Spire/Doc/Documents/TextSelection.h"
#include "Spire/Doc/Fields/Shapes/Shading.h"
#include "Spire/Doc/Fields/TextRange.h"
#include "Spire/Doc/FileFormat.h"
#include "Spire/Doc/Formatting/CellFormat.h"
#include "Spire/Doc/Formatting/CharacterFormat.h"
#include "Spire/Doc/Formatting/Paddings.h"
#include "Spire/Doc/Formatting/ParagraphFormat.h"
#include "Spire/Doc/LineSpacingRule.h"
#include "Spire/Doc/PreferredWidth.h"
#include "Spire/Doc/Section.h"
#include "Spire/Doc/Table.h"
#include "Spire/Doc/TableCell.h"
#include "Spire/Doc/TableRow.h"
#include "Spire/Doc/WidthType.h"
#include "Spire/Doc/common/h/Color.h"
using namespace std;
using namespace Spire::Doc;
using namespace Spire::Doc::Collections;
using namespace Spire::Doc::Documents;
using namespace Spire::Doc::Fields;
using namespace Spire::Doc::Formatting;
//Apply uniform line spacing and space-after to cell paragraphs to keep rows compact
void SetCellParagraphSpacing(intrusive_ptr<Paragraph> paragraph)
{
intrusive_ptr<ParagraphFormat> format = paragraph->GetFormat();
format->SetBeforeSpacing(0);
format->SetAfterSpacing(0);
format->SetLineSpacingRule(LineSpacingRule::Exactly);
format->SetLineSpacing(16.0f);
}
int main()
{
//Specify the input file path
string inputFilePath = "ProjectCharter.docx";
//Specify the output file path and name
string outputPath = "Output/";
string outputFile = outputPath + "ReplaceWithTable.docx";
//Load the template
intrusive_ptr<Document> document = new Document();
document->LoadFromFile(inputFilePath.c_str());
//Locate the placeholder and obtain its paragraph and body index
intrusive_ptr<TextSelection> selection =
document->FindString("[MILESTONES]", false, false);
intrusive_ptr<TextRange> range = selection->GetAsOneRange();
intrusive_ptr<Paragraph> paragraph = range->GetOwnerParagraph();
intrusive_ptr<Body> body = paragraph->GetOwnerTextBody();
int paragraphIndex = body->GetChildObjects()->IndexOf(paragraph);
//Create a table with 5 rows and 3 columns
intrusive_ptr<Section> section = document->GetSections()->GetItem(0);
intrusive_ptr<Table> table = section->AddTable(true);
table->SetPreferredWidth(new PreferredWidth(WidthType::Percentage, 100));
table->ResetCells(5, 3);
vector<vector<string>> data =
{
{"Phase", "Planned Completion", "Deliverable"},
{"Requirements Confirmation", "2026-11-20", "Requirements Specification"},
{"Equipment Arrival", "2026-12-15", "12 robots and charging stations"},
{"System Integration", "2027-01-20", "Scheduling system and WMS interface"},
{"Overall Acceptance", "2027-03-15", "Acceptance report and O&M handover"},
};
intrusive_ptr<CharacterFormat> characterFormat = new CharacterFormat(document);
characterFormat->SetFontName("Calibri");
characterFormat->SetFontNameFarEast("Calibri");
//Header row: dark blue background with bold white text
intrusive_ptr<TableRow> headerRow = table->GetRows()->GetItem(0);
headerRow->SetIsHeader(true);
for (int c = 0; c < 3; c++)
{
intrusive_ptr<TableCell> cell = headerRow->GetCells()->GetItem(c);
cell->GetCellFormat()->GetPaddings()->SetAll(4.0f);
cell->GetCellFormat()->GetShading()->SetBackgroundPatternColor(
Color::FromArgbRGB(31, 56, 100));
intrusive_ptr<Paragraph> p = cell->AddParagraph();
SetCellParagraphSpacing(p);
p->GetFormat()->SetHorizontalAlignment(HorizontalAlignment::Center);
intrusive_ptr<TextRange> textRange = p->AppendText(data[0][c]);
textRange->ApplyCharacterFormat(characterFormat);
textRange->GetCharacterFormat()->SetBold(true);
textRange->GetCharacterFormat()->SetTextColor(Color::GetWhite());
}
//Data rows: light shading on alternating rows
for (int r = 1; r < (int)data.size(); r++)
{
intrusive_ptr<TableRow> row = table->GetRows()->GetItem(r);
for (int c = 0; c < 3; c++)
{
intrusive_ptr<TableCell> cell = row->GetCells()->GetItem(c);
cell->GetCellFormat()->GetPaddings()->SetAll(4.0f);
if (r % 2 == 0)
{
cell->GetCellFormat()->GetShading()->SetBackgroundPatternColor(
Color::FromArgbRGB(242, 246, 251));
}
intrusive_ptr<Paragraph> p = cell->AddParagraph();
SetCellParagraphSpacing(p);
if (c == 1)
{
p->GetFormat()->SetHorizontalAlignment(HorizontalAlignment::Center);
}
p->AppendText(data[r][c])->ApplyCharacterFormat(characterFormat);
}
}
//Remove the placeholder paragraph and insert the table at the same position
body->GetChildObjects()->Remove(paragraph);
body->GetChildObjects()->Insert(paragraphIndex, table);
//Save the result file
document->SaveToFile(outputFile, FileFormat::Docx2013);
document->Close();
return 0;
}
After execution, the paragraph that contains [MILESTONES] is removed, and a 5-row, 3-column milestone table appears in the same position:
![Milestone plan after [MILESTONES] is replaced with a table](https://cdn.e-iceblue.com/images/articles/2026/11/CPP-Replace-Text-With-Document-HTML-Table-Field-4.webp)
Table Replacement Removes the Entire Paragraph
The placeholder in the sample occupies a paragraph of its own, so the whole paragraph can be removed and the table inserted. If the paragraph also contains text at the same level, the paragraph cannot be removed directly; it should be split first: keep the content before the placeholder, move the text after it to a new paragraph, and insert the table between the two. Otherwise, the remaining text of the paragraph is lost together with the paragraph.
Header Row, Banded Shading, and Cell Padding
TableRow->SetIsHeader(true) marks the first row as a header row, which is repeated when the table spans pages. Cell shading is set with CellFormat->GetShading()->SetBackgroundPatternColor(); the header uses dark blue and the data rows alternate light shading, which produces a clear horizontal separation in the document. CellFormat->GetPaddings()->SetAll() leaves padding inside the cells so that text does not touch the borders.
Row Height Is Determined by Paragraph Formatting
Cell paragraphs of a newly created table inherit the default style of the document. If the template's default paragraph keeps space after it and uses 1.5 line spacing, the table rows will be noticeably taller than the existing table in the template. The sample clears the before and after spacing with ParagraphFormat and sets the line spacing to an exact 16 points, so that the inserted table matches the overall layout of the document. Column width is determined jointly by PreferredWidth and the cell content; the sample sets the table width to 100% of the page width.
Replace Text with a Field
Replacing text with a field requires constructing both the field code and the field result. The sample replaces [SIGN_DATE] with a DATE field whose field code uses the MMMM d, yyyy format, so that the current date is displayed when the document is opened or the field is updated. Inserting a field requires three objects: the Field itself, a FieldSeparator mark, and a FieldEnd mark.
| Object | Purpose |
|---|---|
Field |
Defines the field type and field code |
FieldMark + FieldMarkType::FieldSeparator |
Separates the field code from the field result |
FieldMark + FieldMarkType::FieldEnd |
Ends the field |
The detailed steps are as follows.
- Create a Document object and load the template document.
- Call Document->FindString() to locate the placeholder and obtain its paragraph and range index.
- Create a Field object, set the type to
FieldDatewith Field->SetType(), and set the date field code with Field->SetCode(). - Insert the
Field,FieldSeparator, andFieldEndin order, and then remove the placeholder range. - Set Document->SetIsUpdateFields() and save the result document.
The code for replacing text with a field is shown below.
#include <iostream>
#include <string>
#include "Spire/Doc/pch.h"
#ifdef DocumentProperties
#undef DocumentProperties
#endif
#define DocumentProperties DocumentPropertiesA
#include "Spire/Doc/Collections/DocumentObjectCollection.h"
#include "Spire/Doc/Document.h"
#include "Spire/Doc/Documents/FieldMarkType.h"
#include "Spire/Doc/Documents/Paragraph.h"
#include "Spire/Doc/Documents/TextSelection.h"
#include "Spire/Doc/FieldType.h"
#include "Spire/Doc/Fields/Field.h"
#include "Spire/Doc/Fields/FieldMark.h"
#include "Spire/Doc/Fields/TextRange.h"
#include "Spire/Doc/FileFormat.h"
#include "Spire/Doc/Formatting/CharacterFormat.h"
using namespace std;
using namespace Spire::Doc;
using namespace Spire::Doc::Collections;
using namespace Spire::Doc::Documents;
using namespace Spire::Doc::Fields;
using namespace Spire::Doc::Formatting;
void SetParagraphTextFont(intrusive_ptr<Paragraph> paragraph, const string& fontName)
{
intrusive_ptr<DocumentObjectCollection> childObjects = paragraph->GetChildObjects();
for (int i = 0; i < childObjects->GetCount(); i++)
{
intrusive_ptr<DocumentObject> child = childObjects->GetItem(i);
//A paragraph may also contain fields, bookmarks, and pictures, so handle TextRange only
if (child->GetDocumentObjectType() != DocumentObjectType::TextRange)
continue;
intrusive_ptr<TextRange> range = Object::Dynamic_cast<TextRange>(child);
if (range == nullptr)
continue;
//FontName covers Latin text and FarEast covers East Asian text; set both to avoid theme-font fallback
range->GetCharacterFormat()->SetFontName(fontName);
range->GetCharacterFormat()->SetFontNameFarEast(fontName);
}
}
int main()
{
//Specify the input file path
string inputFilePath = "ProjectCharter.docx";
//Specify the output file path and name
string outputPath = "Output/";
string outputFile = outputPath + "ReplaceWithField.docx";
//Load the template
intrusive_ptr<Document> document = new Document();
document->LoadFromFile(inputFilePath);
//Locate the placeholder
intrusive_ptr<TextSelection> selection = document->FindString("[SIGN_DATE]", false, false);
intrusive_ptr<TextRange> range = selection->GetAsOneRange();
intrusive_ptr<Paragraph> paragraph = range->GetOwnerParagraph();
int rangeIndex = paragraph->GetChildObjects()->IndexOf(range);
//Create a DATE field formatted as "November 26, 2026"
intrusive_ptr<Field> dateField = new Field(document);
dateField->SetType(FieldType::FieldDate);
dateField->SetCode("DATE \\@ \"MMMM d, yyyy\"");
//Insert the field, the separator mark, and the end mark in order
paragraph->GetChildObjects()->Insert(rangeIndex, dateField);
intrusive_ptr<FieldMark> separator = new FieldMark(document, FieldMarkType::FieldSeparator);
paragraph->GetChildObjects()->Insert(rangeIndex + 1, separator);
intrusive_ptr<FieldMark> end = new FieldMark(document, FieldMarkType::FieldEnd);
paragraph->GetChildObjects()->Insert(rangeIndex + 2, end);
//Remove the placeholder; the text after it stays in place
paragraph->GetChildObjects()->Remove(range);
SetParagraphTextFont(paragraph, "Calibri");
//Update fields so the saved file displays the field result
document->SetIsUpdateFields(true);
//Save the result file
document->SaveToFile(outputFile, FileFormat::Docx2013);
document->Close();
return 0;
}
After execution, [SIGN_DATE] is replaced by the current date, and "(effective upon approval)" after the placeholder remains after the date:
![Date field replacing [SIGN_DATE], with the text after the placeholder unchanged](https://cdn.e-iceblue.com/images/articles/2026/11/CPP-Replace-Text-With-Document-HTML-Table-Field-5.webp)
Backslashes and Quotes in the Field Code
Field->SetCode() accepts the field code string. In the sample, DATE \\@ "MMMM d, yyyy" is written with a double backslash in the C++ string literal, so the actual field code is DATE \@ "MMMM d, yyyy". The format string inside the quotation marks is interpreted by Word: MMMM produces the full month name, d the day without a leading zero, and yyyy the four-digit year. When a fixed numeric format is required, use MM and dd in the format string.
Keep the Text After the Placeholder
To insert the field, the Field, the separator mark, and the end mark are inserted before the placeholder in order, and the placeholder range is then removed. In this way, the text after the placeholder remains in the original paragraph and is not deleted together with the placeholder. If the placeholder were removed first and the field inserted afterwards, the range index would change and the position of the following text would have to be recalculated.
Display the Result After Updating the Field
Field defines only the type and code of the field; the displayed result is produced by updating the field. The sample sets SetIsUpdateFields(true) before saving, so Word or WPS updates the field when the file is opened and displays the current date. If the file is read by another program and no update is triggered, the field code or a cached result may still be displayed. The field can also be selected in Word and updated manually with F9.
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.
