RTF (Rich Text Format) records text and layout instructions as plain text, so rich text can move between operating systems and word processors. Compared with Docx, RTF does not depend on a ZIP package or an XML structure, and older office software and some business systems can read it directly; compared with plain text, RTF still retains fonts, font sizes, colors, tables and images. Exchanging formatted documents between heterogeneous systems commonly requires converting between Word and RTF.

Spire.Doc for C++ writes RTF with FileFormat::Rtf in Document->SaveToFile(), loads RTF with Document->LoadFromFile() or Document->LoadRtf(), inserts an RTF fragment into a paragraph with Paragraph->AppendRTF(), and can save a loaded RTF directly as Word or PDF. 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:

The examples use the "Skylark" Customer Service Center 2026 Third-Quarter Operations Report (WordToRtf.docx). The document runs to two pages and contains five sections, two tables, one bar chart, and a header and footer; the body text is set in Arial:

The Word document to be converted, two pages in total

The reverse conversion uses the Equipment Inspection Record (Legacy.rtf). The file was produced by saving the corresponding Word document as RTF and runs to two pages with four tables and a header and footer; it is used to check how much content survives the RTF-to-Word conversion.

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.

Convert Word to RTF

Saving a Word document as RTF requires only specifying FileFormat::Rtf at save time. At load time, LoadFromFile() recognizes the Word file by its extension, and at save time the format enumeration determines the output type. Fonts, font sizes, colors, paragraph alignment, tables and images in the RTF are written as control words and groups, and the recipient can open the file without installing Spire.Doc.

Operation Main call
Load a Word document Document->LoadFromFile(fileName)
Save as RTF Document->SaveToFile(fileName, FileFormat::Rtf)
Save as PDF Document->SaveToFile(fileName, FileFormat::PDF)
Load an RTF file Document->LoadFromFile(fileName, FileFormat::Rtf) or Document->LoadRtf(fileName)
Insert an RTF snippet Paragraph->AppendRTF(rtfCode)

The detailed steps are as follows.

  • Create a Document object.
  • Load the sample Word file with the Document->LoadFromFile() method.
  • Call Document->SaveToFile() and save the document with FileFormat::Rtf.
  • Call Document->Close() to release the document.

The code for converting Word to RTF 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 path
    string inputFile = "Data/WordToRtf.docx";

    // Specify the output file path and name
    string outputPath = "Output/";
    string outputFile = outputPath + "WordToRtf.rtf";

    // Create a Document object and load the Word document
    intrusive_ptr<Document> document = new Document();
    document->LoadFromFile(inputFile);

    // Save the document as RTF
    document->SaveToFile(outputFile, FileFormat::Rtf);

    document->Close();

    cout << "Saved: " << outputFile << endl;
}

Opened in Word, the converted RTF still runs to two pages, and the header and footer, the two tables and the bar chart are all retained:

The RTF file produced from the Word document, opened in Word

Change in File Size

The sample Word document is 65,773 bytes, and the converted RTF is 3,748,230 bytes, about 57 times the original. Most of the growth comes from images: when writing a bitmap, RTF stores both a PNG image and a WMF preview, so the same chart is written twice; in addition, characters outside the code page are written as \uN escapes or \'hh hex escapes, and layout attributes are recorded one control word at a time.

For a text-heavy document, the growth comes mainly from formatting control words and character escapes and is noticeably smaller than for a document that contains images. When the recipient has a file-size limit, compress the images in the source document or reduce their number without affecting the content, rather than compressing the RTF after conversion.

What a Reloaded RTF Contains

After the generated RTF is loaded again, the document still runs to two pages, and the two tables, the header and footer, and the chart are all present. The chart is stored as a picture object in RTF rather than as Docx DrawingML; when the document is saved as Docx again, it is written as a VML picture. The paragraph count is one higher than in the original document because of the evaluation paragraph written at save time, which does not appear in a licensed environment.

This shows that RTF preserves structured content well and is suitable as an intermediate format for exchange between systems. If the document will continue to be edited in Word, keep the original Docx and do not treat the RTF as the only archive.

Convert RTF to Word

Converting RTF to Word follows the same process in reverse; the difference is that FileFormat::Rtf is specified at load time and FileFormat::Docx2013 at save time. Spire.Doc provides three ways to load RTF, and all three produce the same document object.

Load method Description
Document->LoadFromFile(fileName, FileFormat::Rtf) Specifies the input format explicitly
Document->LoadFromFile(fileName) Recognizes the file as RTF by its extension
Document->LoadRtf(fileName) Uses the dedicated RTF load method

The detailed steps are as follows.

  • Create a Document object.
  • Load the RTF file with the Document->LoadFromFile() method, specifying FileFormat::Rtf.
  • Call Document->SaveToFile() and save the document with FileFormat::Docx2013.
  • Call Document->Close() to release the document.

The code for converting RTF to Word 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 path
    string inputFile = "Data/Legacy.rtf";

    // Specify the output file path and name
    string outputPath = "Output/";
    string outputFile = outputPath + "Legacy.docx";

    // Create a Document object and load the file as RTF
    intrusive_ptr<Document> document = new Document();
    document->LoadFromFile(inputFile, FileFormat::Rtf);

    // Save the document as Word (docx)
    document->SaveToFile(outputFile, FileFormat::Docx2013);

    document->Close();

    cout << "Saved: " << outputFile << endl;
}

An RTF file is plain text. The beginning records the RTF version, the character set, the default font and the font table, followed by the color table, the style sheet and the body content; characters outside the code page are written as \' or \u escapes:

The font table at the start of the RTF file

Opened in Word, the file runs to two pages, with four tables and the header and footer intact. The converted Word document also runs to two pages, and the row and column structure of the tables, the cell shading, the header and footer, and the inspection route map are all retained:

The Word document produced from the RTF

What Content Is Preserved

The sample RTF contains 19 body paragraphs and 4 tables. The converted Docx keeps all the paragraphs and tables; the cell shading in the tables is written as w:shd in 47 places, exactly the same as in the Docx from which the RTF was generated. The inspection route map in the document is stored as a VML picture rather than in a w:drawing node, so a tool that counts only DrawingML pictures may report zero, but Word displays it normally.

At the style level, RTF does not carry the Docx style sheet, and the converted paragraphs are rebuilt from the formatting attributes in the RTF. A program that relies on built-in style names for subsequent processing should re-read the paragraph formatting after conversion rather than assume that the style names are unchanged.

Equivalence of the Three Load Methods

Loading the same RTF with the explicit format, by extension, and with LoadRtf() produces documents that are all two pages long and contain 4 tables, 47 instances of cell shading and 1 picture object. Which method is used does not affect the conversion result; the difference lies only in the call form: the explicit format suits files with non-standard extensions, and LoadRtf() suits callers that already know the input is RTF.

Convert RTF to PDF

PDF is a fixed-layout format suited to archiving, printing and distribution across devices. Converting RTF to PDF requires only changing the save format to FileFormat::PDF; the steps for loading the RTF are the same as in the previous section. During conversion, Spire.Doc lays out the document according to its page setup and embeds the fonts it uses in the output file.

The detailed steps are as follows.

  • Create a Document object and load the RTF file.
  • Call Document->SaveToFile() and save the document with FileFormat::PDF.
  • Read Document->GetPageCount() to obtain the page count after conversion.
  • Call Document->Close() to release the document.

The code for converting RTF to PDF 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 path
    string inputFile = "Data/Legacy.rtf";

    // Specify the output file path and name
    string outputPath = "Output/";
    string outputFile = outputPath + "Legacy.pdf";

    // Create a Document object and load the RTF file
    intrusive_ptr<Document> document = new Document();
    document->LoadFromFile(inputFile, FileFormat::Rtf);

    // Save the document as PDF
    document->SaveToFile(outputFile, FileFormat::PDF);

    // Print the page count after conversion
    cout << "Pages: " << document->GetPageCount() << endl;

    document->Close();

    cout << "Saved: " << outputFile << endl;
}

The output is a two-page A4 document, and the header and footer, the tables and the route map all appear in the PDF:

The PDF document produced from the RTF

Pagination May Differ from Word

In the sample, the PDF is two pages, and page 2 begins at section IV, the same point at which the same RTF breaks when opened in Word. The two layout engines still do not handle line height, paragraph spacing and table row splitting in exactly the same way, so pagination can diverge in other documents. When the page breaks are critical, check the page count and break points after conversion, and adjust margins, line spacing or table row heights if necessary, rather than assuming that the PDF matches Word exactly.

Font Handling

An RTF font table records only font names and character sets; the actual glyphs depend on the fonts installed on the current system. When converting to PDF, Spire.Doc looks up each font by name on the local machine and embeds the glyphs it uses as a subset. The recipient does not need the corresponding font installed to open the PDF, and the appearance matches the conversion environment. If a font declared in the RTF is missing locally, a substitute is used, and character widths and line heights may change; confirm that the required fonts are installed before a formal conversion.

Insert an RTF Snippet in a Paragraph

Besides converting whole files, Spire.Doc can insert an RTF fragment into an existing paragraph. Paragraph->AppendRTF() accepts a complete RTF fragment, parses it, and appends the text and formatting in the fragment to the end of the paragraph. This suits embedding prepared rich text in a template or joining RTF data produced by another system into a document.

Overload Description
AppendRTF(rtfCode) Appends the fragment to the current paragraph
AppendRTF(rtfCode, addtolastsection) The second parameter controls whether sections in the fragment are merged into the last section of the document

The detailed steps are as follows.

  • Create a Document object and call AddSection() to add a section.
  • Add an explanatory paragraph containing the text that precedes the fragment.
  • Create a target paragraph to receive the RTF fragment.
  • Construct a complete RTF string containing \rtf1, a font table, a color table and the body.
  • Call Paragraph->AppendRTF() to insert the fragment.
  • Add a comparison paragraph and call Document->SaveToFile() to save the result.

The code for inserting an RTF fragment 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/Documents/Paragraph.h"
#include "Spire/Doc/Fields/TextRange.h"
#include "Spire/Doc/FileFormat.h"
using namespace std;
using namespace Spire::Doc;
using namespace Spire::Doc::Documents;

int main() {

    // Create a blank document and a section
    intrusive_ptr<Document> document = new Document();
    intrusive_ptr<Section> section = document->AddSection();

    // Insert the introductory paragraph
    intrusive_ptr<Paragraph> intro = section->AddParagraph();
    intro->AppendText("The following line is inserted from an RTF snippet:");

    // Create the target paragraph and append the RTF snippet to it
    intrusive_ptr<Paragraph> target = section->AddParagraph();
    string rtf =
        "{\\rtf1\\ansi\\deff0"
        "{\\fonttbl{\\f0\\fnil\\fcharset0 Arial;}}"
        "{\\colortbl;\\red47\\green85\\blue151;}"
        "\\uc1\\f0\\fs28\\b\\cf1 "
        "This line was inserted from an RTF snippet."
        "\\b0\\cf0\\par}";
    target->AppendRTF(rtf);

    // Insert a comparison paragraph
    intrusive_ptr<Paragraph> tail = section->AddParagraph();
    tail->AppendText("This is an ordinary paragraph after the snippet, used to compare font and size.");

    // Save the result
    document->SaveToFile("Output/AppendRtf.docx", FileFormat::Docx2013);
    document->Close();

    cout << "Saved: Output/AppendRtf.docx" << endl;
}

The text in the snippet is inserted in bold, 14-point blue Arial, and the paragraphs before and after keep their default formatting:

The result after the RTF snippet is inserted into the paragraph

The Fragment Must Be Complete RTF

AppendRTF() accepts a complete RTF document fragment, not isolated control words. The fragment must start with \rtf1, include a font table \fonttbl, and end its body with \par. Without these structures, parsing may fail or produce only part of the content.

When the text contains characters that cannot be written directly into the RTF string, use \uN? escapes: N is the Unicode code point of the character, and \uc1 declares that each escape is followed by one fallback character, which is the ? in the example. The sample uses plain ASCII, so no escapes are needed, but the declaration is kept so that the fragment can be extended with non-ASCII text. Control words such as \b, \fs28 and \cf1 in the fragment are converted to Word bold, font size and font color when the fragment is inserted and are not displayed as text.

The addtolastsection Parameter

The two-parameter overload specifies whether the content of the fragment is merged into the last section of the document. When the fragment carries section information, setting the second parameter to true avoids creating an additional section; an ordinary fragment contains no section information and can be inserted with the single-parameter overload. After insertion, the paragraph and character formatting in the fragment are merged into the formatting system of the target paragraph, and later changes to the paragraph formatting apply the same rules to the fragment content and the existing content.

Function Comparison

Function Main call Key point
Word to RTF SaveToFile(..., FileFormat::Rtf) Keeps formatting, tables and images; the file becomes larger
RTF to Word LoadFromFile(..., FileFormat::Rtf) + Docx2013 Cell shading and table structure are preserved
RTF to PDF LoadFromFile(..., FileFormat::Rtf) + PDF Fixed layout; pagination may differ from Word
Insert an RTF snippet Paragraph->AppendRTF(rtfCode) The fragment must be complete; non-ASCII text uses \uN? escapes

The four operations share the same document object. Whole-file conversion takes place at load and save time, whereas snippet insertion modifies the document content at the paragraph level. Which approach to use depends on whether the input is a complete file or a fragment of rich-text data; for scenarios that require assembling content in a template, AppendRTF() avoids the intermediate step of generating a temporary file and then inserting it.

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.

Plain text (TXT) contains only characters and line breaks. It carries no fonts, font sizes, tables or images, so the files are small and any program can read them; they are commonly used for log export, data exchange and content archiving. Word handles layout and formal delivery, and converting between the two formats is common: exporting Word to TXT extracts body text that a program can process further, and loading TXT as Word turns collected text into a regular document.

The boundary should be stated first: TXT has no concept of styles or structure, so both directions work only at the text level. Styles, table structure and images on the Word side do not enter the TXT; conversely, the Word document produced from TXT contains only ordinary paragraphs, and headings and lists have to be set separately. Using the conversion with this boundary in mind avoids unrealistic expectations about the result.

Spire.Doc for C++ exports plain text through FileFormat::Txt in Document->SaveToFile(), loads a text file as a document object through Document->LoadText(), and specifies the source file encoding through Encoding. All processing takes place in the local process, and the document does not need to be uploaded to any service.

This article covers three features:

The examples use the Quarterly Product Operations Meeting Minutes (WordToTxt.docx). The document runs to one page and contains a title, a bulleted list, a numbered list, one table, one bar chart, and a header and footer:

The Word document to be converted, one page in total

The reverse conversion uses the plain-text version of the same minutes (TxtToWord.txt). The file is UTF-8 encoded and has 25 lines, containing a title, section names, numbered lines and items that begin with a hyphen; it is used to check the paragraph mapping rules from TXT to Word.

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.

Convert Word to TXT

Exporting Word to plain text requires only specifying FileFormat::Txt at save time. The load step is unchanged: LoadFromFile() loads the Word document, the format enumeration at save time determines the output type, and Spire.Doc extracts the document content under the "text only" rule.

Operation Main call
Load a Word document Document->LoadFromFile(fileName)
Export plain text Document->SaveToFile(fileName, FileFormat::Txt)
Load plain text Document->LoadText(fileName)
Load plain text with an encoding Document->LoadText(fileName, encoding)

The detailed steps are as follows.

  • Create a Document object.
  • Load the sample Word file with the Document->LoadFromFile() method.
  • Call Document->SaveToFile() and save the document with FileFormat::Txt.
  • Call Document->Close() to release the document.

The code for converting Word to TXT 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 path
    string inputFile = "Data/WordToTxt.docx";

    // Specify the output file path and name
    string outputPath = "Output/";
    string outputFile = outputPath + "WordToTxt.txt";

    // Create a Document object and load the Word document
    intrusive_ptr<Document> document = new Document();
    document->LoadFromFile(inputFile);

    // Export the document as plain text
    document->SaveToFile(outputFile, FileFormat::Txt);

    document->Close();

    cout << "Saved: " << outputFile << endl;
}

The sample document is 55,520 bytes, and the exported plain text is 1,233 bytes. The original document is on the left and the exported result on the right; the title, the lists and the table keep only their text, and the image is not exported:

The Word document and the exported plain text

Export Rules

FileFormat::Txt extracts text in paragraph order; each element is handled as follows.

Element Export result
Title and body text Fonts, font sizes, colors and bold are discarded; written as ordinary text lines
Bulleted list Written with a * prefix; list level information is lost
Numbered list Written with a 1. prefix (digit, period and two spaces)
Table Expanded cell by cell into separate lines; row and column relationships are not preserved
Image Not exported; the paragraph that contains it becomes an empty line
Header and footer Header text is written on the first line, footer text on the last line

The table in the sample has four rows and three columns, so the twelve cells each occupy one line after export; the paragraph that contains the bar chart becomes an empty line; the header "Skylark Technology · Operations Center" is on the first line of the file, and the footer "Internal Use Only · Do Not Distribute" is on the last line. When row and column relationships have to be restored, regroup the lines by a fixed column count on the reading side instead of looking for a delimiter in the TXT.

Encoding and Line Breaks

The exported plain text is UTF-8 encoded with a BOM, the byte order mark is EF BB BF, and line breaks are CRLF. The BOM helps Windows Notepad and some editors identify the encoding, but programs that process bytes treat the BOM as characters at the start of the body and should remove it before reading. With std::ifstream, check the first three bytes and skip them, or decode the file as utf-8-sig.

Convert TXT to Word

Loading TXT as a Word document uses LoadText(). Unlike LoadFromFile(), LoadText() is dedicated to text files and provides an overload that accepts an Encoding parameter; after loading, call SaveToFile() to save the document as Docx and the Word document is ready.

The detailed steps are as follows.

  • Create a Document object.
  • Load the plain text file with the Document->LoadText() method.
  • Call Document->SaveToFile() and save the document with FileFormat::Docx2013.
  • Call Document->Close() to release the document.

The code for converting TXT to Word 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 path
    string inputFile = "Data/TxtToWord.txt";

    // Specify the output file path and name
    string outputPath = "Output/";
    string outputFile = outputPath + "TxtToWord.docx";

    // Create a Document object
    intrusive_ptr<Document> document = new Document();

    // Load the plain text file
    document->LoadText(inputFile);

    // Save the document as Word (docx)
    document->SaveToFile(outputFile, FileFormat::Docx2013);

    document->Close();

    cout << "Saved: " << outputFile << endl;
}

The loaded text is restored as paragraphs line by line, all in the Normal style, and the title and list markers remain as ordinary text:

The plain text and the Word document produced from it

Paragraph Mapping Rules

The sample text has 25 lines, and the loaded document contains 26 paragraphs. Each line break corresponds to one paragraph, and an empty line corresponds to an empty paragraph; the line break at the end of the file produces one more empty paragraph at the end, so the paragraph count is one higher than the line count.

The loading process does not interpret any Markdown or plain-text layout conventions: I. Meeting Overview is ordinary text and does not become a heading; 1. and - are only line-start characters and do not produce numbered or bulleted lists; spaces within a line and typographic punctuation are kept as they are. If headings and lists are needed after conversion, reset the style of the specified paragraphs according to a fixed line format, or use an input format that carries structure.

Choosing Between LoadText and LoadFromFile

LoadFromFile(fileName, FileFormat::Txt) can also load a text file, and LoadFromFile(fileName) can be used directly when the extension is recognized. Both methods produce the same document content as LoadText(); the difference is that LoadText() provides the encoding parameter and suits files that are not UTF-8 or scenarios that require a fixed decoding behavior. For files whose extension is not .txt, prefer LoadText() or specify FileFormat::Txt explicitly to avoid a failure of extension-based recognition.

Load a TXT File with a Specified Encoding

A text file carries no encoding declaration, and the same byte sequence decodes into different characters under different encodings. Legacy files from Chinese Windows environments often use GBK, files exported by cross-platform tools are mostly UTF-8, and some systems also output UTF-16 or UTF-7. When the encoding is wrong, characters appear as mojibake or replacement characters.

The second parameter of LoadText() accepts an Encoding object that specifies the source file encoding. Spire::Doc::Common::Encoding provides factory methods for common encodings and can also construct one from a code page.

Encoding Code page Factory method
UTF-8 65001 Encoding::GetUTF8()
GBK 936 Encoding::GetEncoding(936)
UTF-16 LE 1200 Encoding::GetUnicode()
UTF-16 BE 1201 Encoding::GetBigEndianUnicode()
UTF-7 65000 Encoding::GetUTF7()
UTF-32 12000 Encoding::GetUTF32()

The detailed steps are as follows.

  • Create a Document object.
  • Load the text file with the Document->LoadText() method, passing Encoding::GetUTF8() as the second parameter.
  • Call Document->SaveToFile() and save the document with FileFormat::Docx2013.
  • Call Document->Close() to release the document.

The code for loading plain text as UTF-8 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/common/h/Encoding.h"
using namespace std;
using namespace Spire::Doc;
using namespace Spire::Doc::Common;

int main() {

    // Specify the input file path
    string inputFile = "Data/TxtToWord.txt";

    // Specify the output file path and name
    string outputFile = "Output/TxtToWord_Utf8.docx";

    // Create a Document object
    intrusive_ptr<Document> document = new Document();

    // Load the plain text with UTF-8 encoding
    document->LoadText(inputFile, Encoding::GetUTF8());

    // To read a GBK file, use the 936 code page instead
    // document->LoadText("Data/TxtToWord_GBK.txt", Encoding::GetEncoding(936));

    // Save as a Word document
    document->SaveToFile(outputFile, FileFormat::Docx2013);

    document->Close();

    cout << "Saved: " << outputFile << endl;
}

Symptoms of an Encoding Mismatch

Decoding the same UTF-8 file as GBK and saving the result as Word turns the accented name and the typographic punctuation in the document into unrelated characters and replacement symbols, for example Jos茅 脕lvarez in place of José Álvarez; the ASCII text around them remains readable, so the error can hide in names and quotes. Decoding as UTF-8 is correct. The left side shows the wrong encoding and the right side the correct result:

The same file decoded as GBK and as UTF-8

When this kind of result appears, check the actual encoding of the file rather than modifying the document content. A hex viewer shows the bytes: non-ASCII UTF-8 characters start with C2–F4, GBK lead bytes are 81–FE, and files with a BOM begin with EF BB BF (UTF-8), FF FE (UTF-16 LE) or FE FF (UTF-16 BE).

Default Loading and Explicit Encoding

Without an encoding, LoadText() recognizes common encodings from the file content. In the sample environment, UTF-8, GBK and UTF-16 files load correctly when no Encoding argument is passed. A UTF-7 file whose content starts with ASCII is not recognized: the escape sequences remain in the text, and the file has to be loaded with Encoding::GetUTF7(), which decodes it correctly. The recognition strategy may differ between runtime versions, so when the file encoding is uncommon, or when the result must be identical on every load, pass Encoding explicitly so that decoding does not depend on the environment.

Function Comparison

Function Main call Key point
Word to TXT SaveToFile(..., FileFormat::Txt) Text only; UTF-8 with BOM, CRLF
TXT to Word LoadText(fileName) + Docx2013 One paragraph per line break, all in Normal style
Load with an encoding LoadText(fileName, encoding) The encoding must match the file

Both directions handle text only. Word to TXT loses tables, images and styles; TXT to Word does not create headings or lists automatically. When the same content has to move back and forth between the two formats, keep a structured original document and use the TXT only as a text carrier.

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.

Document properties record information that lies outside the content. Built-in properties have names and meanings defined by Word and cover the title, subject, author, company, category, keywords, and comments; custom properties have names and values defined by the business and are often used for fields such as contract numbers, review status, and project numbers. Properties do not take part in body layout, yet they provide the basis for archiving, retrieval, and workflow decisions.

Spire.Doc for C++ reads and writes built-in properties through Document->GetBuiltinDocumentProperties() and manages custom properties through Document->GetCustomDocumentProperties(). A custom value is passed as an Object, and a string is wrapped in a String object; when reading, DocumentProperty->ToString(), GetName(), and GetValueType() return the value, the name, and the type.

This article covers three features:

The entry points and uses of the two kinds of properties are as follows:

Category Entry point Typical fields
Built-in properties GetBuiltinDocumentProperties() Title, subject, author, company, category, keywords, comments
Custom properties GetCustomDocumentProperties() Business fields such as contract number, review status, and archive date

Built-in properties are visible on the Info page and on the Details tab of the file properties; custom properties are stored in docProps/custom.xml in the document package and are parsed by the program that reads them.

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.

Set Built-in Document Properties

Built-in properties are provided by BuiltinDocumentProperties, and the common fields each have a corresponding Set* and Get* method. The example loads a project progress report, writes the title, subject, author, manager, company, category, keywords, and comments, and then reads three of them back to confirm the result.

Operation Method Description
Title SetTitle(string) / GetTitle() Document title
Subject SetSubject(string) Document subject
Author SetAuthor(string) Creator
Manager SetManager(string) Responsible person or department
Company SetCompany(string) Owning company
Category SetCategory(string) Document category
Keywords SetKeywords(string) Multiple keywords separated by commas
Comments SetComments(string) Supplementary notes

The detailed steps are as follows.

  • Create a Document object and call LoadFromFile() to load the sample document.
  • Call GetBuiltinDocumentProperties() to obtain the built-in property object.
  • Call SetTitle(), SetSubject(), SetAuthor(), SetManager(), SetCompany(), SetCategory(), SetKeywords(), and SetComments() in turn to write the fields.
  • Call GetTitle(), GetAuthor(), and GetCompany() to read and output the result.
  • Call SaveToFile() to save the document.

The code for setting the built-in document properties is shown below.

#include <iostream>
#include <string>
#include "Spire/Doc/pch.h"
#ifdef DocumentProperties
#undef DocumentProperties
#endif
#define DocumentProperties DocumentPropertiesA
#include "Spire/Doc/BuiltinDocumentProperties.h"
#include "Spire/Doc/Document.h"
#include "Spire/Doc/FileFormat.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 project progress report
    intrusive_ptr<Document> document = new Document();
    document->LoadFromFile("Template.docx");

    //Write the built-in summary properties
    intrusive_ptr<BuiltinDocumentProperties> properties =
        document->GetBuiltinDocumentProperties();
    properties->SetTitle("Smart Warehouse Management Platform Project Progress Report");
    properties->SetSubject("Q4 2026 Project Progress");
    properties->SetAuthor("Chen Li");
    properties->SetManager("Project Management Department");
    properties->SetCompany("Beichen Supply Chain Co., Ltd.");
    properties->SetCategory("Internal Report");
    properties->SetKeywords("warehousing, project progress, 2026Q4, internal");
    properties->SetComments("Reviewed by the project management committee and archived as quarterly material.");

    cout << "Title: " << properties->GetTitle() << endl;
    cout << "Author: " << properties->GetAuthor() << endl;
    cout << "Company: " << properties->GetCompany() << endl;

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

The console output shows that the three fields have been written and can be read back:

Title: Smart Warehouse Management Platform Project Progress Report
Author: Chen Li
Company: Beichen Supply Chain Co., Ltd.

After saving, open the Details tab of the file properties; the title, subject, author, category, comments, company, and manager all appear in the property list:

The Details tab after the built-in properties are written

Built-in Properties Are Written to the File When the Document Is Saved

Methods such as SetTitle() modify the property object in memory, and the values are written into the document package only when SaveToFile() is called. When a document is generated from a template, the property values already present in the template are retained until the moment of saving and are then replaced by the values that are explicitly set. The example assigns all eight fields one by one, and fields without an assignment keep the value from the template.

Property Values Do Not Take Part in Body Layout

Built-in properties are metadata. They do not appear on the page, and they do not affect pagination or printing. The page saved by the example is identical to the page before loading, and the change is visible only in the file properties panel. When a title or an author needs to be displayed on the page, insert the corresponding content into the body, a header, or a footer; the properties themselves provide no layout output.

Statistical Fields Are Read-Only

Statistical fields such as WordCount, CharCount, PageCount, and ParagraphCount are calculated when the document is saved and offer only Get* methods, with no corresponding Set*. The example sets only the summary fields. When a page count or a word count is needed, read these fields rather than attempting to write them.

Add Custom Document Properties

The names and values of custom properties are determined by the business. The second parameter of CustomDocumentProperties->Add(name, value) is an intrusive_ptr<Object>, so a string is first wrapped in a String object. The example adds three properties, namely the contract number, the review status, and the archive date, and then iterates over the collection to output the name, the value, and the value type of each property.

Operation Method Description
Add a property Add(name, Object) The value is an object derived from Object
Add a string Add(name, new String(value)) Uses Spire::Doc::Common::String
Count the properties GetCount() Returns the number of properties
Get a property by index GetItem(index) Returns a DocumentProperty
Read the name DocumentProperty->GetName() Property key
Read the value DocumentProperty->ToString() Converts to a string
Read the type GetValueType() Returns a PropertyValueType

The detailed steps are as follows.

  • Create a Document object and call LoadFromFile() to load the sample document.
  • Call GetCustomDocumentProperties() to obtain the custom property collection.
  • Call Add() three times to add string properties, each value wrapped in a String object.
  • Call GetCount() to output the count, and call GetItem(index) in a loop to obtain each property.
  • Call GetName(), ToString(), and GetValueType() to output the name, the value, and the type.
  • Call SaveToFile() to save the document.

The code for adding custom document properties is shown below.

#include <iostream>
#include <string>
#include "Spire/Doc/pch.h"
#ifdef DocumentProperties
#undef DocumentProperties
#endif
#define DocumentProperties DocumentPropertiesA
#include "Spire/Doc/CustomDocumentProperties.h"
#include "Spire/Doc/Document.h"
#include "Spire/Doc/DocumentProperty.h"
#include "Spire/Doc/FileFormat.h"
#include "Spire/Doc/common/h/Stream.h"
#include "Spire/Doc/common/h/System_String.h"
using namespace std;
using namespace Spire::Doc;
using namespace Spire::Doc::Common;

//Convert a property value type to a readable name
string GetTypeName(PropertyValueType type)
{
    switch (type)
    {
    case PropertyValueType::String: return "String";
    case PropertyValueType::Int:
    case PropertyValueType::Int32: return "Integer";
    case PropertyValueType::Date: return "Date";
    case PropertyValueType::Boolean: return "Boolean";
    case PropertyValueType::Double:
    case PropertyValueType::Float: return "Number";
    default: return "Other";
    }
}

int main()
{
    SetConsoleOutputCP(CP_UTF8);

    //Load the project progress report
    intrusive_ptr<Document> document = new Document();
    document->LoadFromFile("Template.docx");

    //Add three custom properties; the values are passed as String objects
    intrusive_ptr<CustomDocumentProperties> properties =
        document->GetCustomDocumentProperties();
    properties->Add("Contract Number", new String("HT-2026-018"));
    properties->Add("Review Status", new String("Approved"));
    properties->Add("Archive Date", new String("2026-12-31"));

    //Iterate over the custom properties
    cout << "Custom property count: " << properties->GetCount() << endl;
    for (int i = 0; i < properties->GetCount(); i++)
    {
        intrusive_ptr<DocumentProperty> property = properties->GetItem(i);
        cout << property->GetName() << " = " << property->ToString()
             << " (" << GetTypeName(property->GetValueType()) << ")" << endl;
    }

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

The console output lists the name, the value, and the type of the three properties, all of which are of type String:

Custom property count: 3
Contract Number = HT-2026-018 (String)
Review Status = Approved (String)
Archive Date = 2026-12-31 (String)

The body of the saved document is unchanged, and the custom properties are written into the document package. In the figure below, the right side shows the property list printed by the program:

The body text and the property list after three custom properties are added

Values Must Be Wrapped as Object

The second parameter of Add() is an intrusive_ptr<Object>, so a std::string cannot be passed directly. The example creates a Spire::Doc::Common::String with new String("HT-2026-018"); this type derives from Object and can be passed as the parameter. Property values are always passed as Object, and when reading, the value can be converted to a target type through ToInt(), ToDateTime(), or ToBool() on DocumentProperty.

Custom Properties Are Stored in custom.xml

After saving, the document package contains a new docProps/custom.xml, in which each property corresponds to one <property> element. The content generated by the example is shown below (excerpt):

<Properties xmlns="http://schemas.openxmlformats.org/officeDocument/2006/custom-properties"
            xmlns:vt="http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes">
  <property fmtid="{D5CDD505-2E9C-101B-9397-08002B2CF9AE}" pid="2" name="Contract Number">
    <vt:lpwstr>HT-2026-018</vt:lpwstr>
  </property>
  <property fmtid="{D5CDD505-2E9C-101B-9397-08002B2CF9AE}" pid="3" name="Review Status">
    <vt:lpwstr>Approved</vt:lpwstr>
  </property>
  <property fmtid="{D5CDD505-2E9C-101B-9397-08002B2CF9AE}" pid="4" name="Archive Date">
    <vt:lpwstr>2026-12-31</vt:lpwstr>
  </property>
</Properties>

pid starts at 2 and increases, name holds the property key, and vt:lpwstr denotes a Unicode string.

Custom Properties Do Not Appear in the Details Tab

The Details tab of the Windows file properties lists only the standard fields recognized by the system, and the custom properties of a docx are not shown there. To check custom properties, read CustomDocumentProperties from a program or inspect docProps/custom.xml directly. The example therefore places the property list printed by the program next to the page.

Read and Remove Custom Document Properties

A single property is read with GetItem(name) or GetItem(index), which return a DocumentProperty, and removed with Remove(name). The example loads a document that contains three custom properties, outputs the count and the contract number, removes "Review Status", and then outputs the names of the remaining properties.

Operation Method Description
Read by name GetItem(name) Returns a DocumentProperty
Read by index GetItem(index) Returns a DocumentProperty
Read the value DocumentProperty->ToString() String form
Remove a property Remove(name) Removes by name
Count after removal GetCount() The count decreases by one

The detailed steps are as follows.

  • Create a Document object and call LoadFromFile() to load the document that contains the custom properties.
  • Call GetCustomDocumentProperties() to obtain the property collection.
  • Call GetCount() to output the count before removal.
  • Call GetItem("Contract Number")->ToString() to read the value by name.
  • Call Remove("Review Status") to remove the property, output the count again, and list the remaining names.
  • Call SaveToFile() to save the result document.

The code for reading and removing custom document properties is shown below.

#include <iostream>
#include <string>
#include "Spire/Doc/pch.h"
#ifdef DocumentProperties
#undef DocumentProperties
#endif
#define DocumentProperties DocumentPropertiesA
#include "Spire/Doc/CustomDocumentProperties.h"
#include "Spire/Doc/Document.h"
#include "Spire/Doc/DocumentProperty.h"
#include "Spire/Doc/FileFormat.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 document that contains three custom properties
    intrusive_ptr<Document> document = new Document();
    document->LoadFromFile("CustomProperties.docx");
    intrusive_ptr<CustomDocumentProperties> properties =
        document->GetCustomDocumentProperties();
    cout << "Property count before removal: " << properties->GetCount() << endl;

    //Read a single property by name
    cout << "Contract Number: " << properties->GetItem("Contract Number")->ToString() << endl;

    //Remove the Review Status property, then list the remaining names
    properties->Remove("Review Status");
    cout << "Property count after removal: " << properties->GetCount() << endl;
    for (int i = 0; i < properties->GetCount(); i++)
    {
        cout << properties->GetItem(i)->GetName() << endl;
    }

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

The console output shows that the property count falls from 3 to 2, and that the two remaining properties are the contract number and the archive date:

Property count before removal: 3
Contract Number: HT-2026-018
Property count after removal: 2
Contract Number
Archive Date

The saved document no longer contains "Review Status", and docProps/custom.xml keeps only two properties:

The custom properties after

Removing a Property Does Not Affect the Body

Custom properties are document metadata, and removing one leaves both the body content and the layout unchanged. After the example removes "Review Status", the page and the paragraphs stay as they were, and the change is visible only in the property collection and in custom.xml. When a review status needs to be displayed on the page, reference the property value through a field or through text, and handle the related content when the property is removed.

Reading by Name Is Case-Sensitive

The name passed to GetItem("Contract Number") must match the key written by Add() exactly. When the names differ, the call does not return the intended property. When iterating, obtain the actual key with GetItem(index)->GetName() and compare it with the business field, which avoids a failed read caused by a difference in the name.

Changes Are Written to the File Only on Save

Remove() modifies the property collection in memory, and the result is written into custom.xml only when SaveToFile() is called. The example saves immediately after the removal, and the result document contains two properties. When the original file needs to be kept, copy the document before the removal or save the result under a new file name.

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.

Page 2 of 387
page 2