C++ Insert Forms, Fields, Images, and HTML with the Document Navigator

After positioning the cursor, DocumentNavigator offers an insertion method for each type of content. Form fields and check boxes collect information to be filled in, fields generate dynamic content such as page numbers and dates, images display graphics, and HTML fragments are converted into document objects and written into the document. Compared with constructing paragraphs and text objects one by one, the navigator's insertion methods combine positioning and content generation in a single operation.

Spire.Doc for C++ provides InsertTextFormField(), InsertCheckBox(), InsertField(), InsertImage(), and InsertHtml(). The insertion position is determined by the current cursor, and the parameters specify the form field type, field code, image size, and HTML content. All processing is completed in the local process, and the document does not need to be uploaded to any service.

This article covers four features:

The example uses the "Smart Warehousing Management Platform Project Brief" (ProjectBrief.docx). The document is one page long and contains a header, a footer, and three sections; the four examples each start a new paragraph at the end of the document and insert content there, so they do not affect one another. The insertion methods are listed below:

Operation Method
Text form field InsertTextFormField(name, type, format, fieldValue, maxLength)
Check box InsertCheckBox(name, defaultValue, checkedValue, size)
Built-in field InsertField(FieldType, updateField)
Field-code field InsertField(fieldCode)
Insert image InsertImage(fileName) and its overloads
Insert HTML InsertHtml(html) / InsertHtml(html, useNavigatorFormatting)

Install Spire.Doc for C++

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

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

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

Insert Form Fields and Check Boxes

InsertTextFormField() inserts a text form field; its parameters are, in order, the name, type, format, default value, and maximum length. InsertCheckBox() inserts a check box; the short overload specifies the name, checked state, and size, and the long overload specifies the default state and the current checked state separately.

The detailed steps are as follows.

  • Create a Document object and call LoadFromFile() to load the sample document.
  • Create a DocumentNavigator object and call MoveToDocumentEnd() and the parameterless Writeln() to start a new paragraph at the end of the document.
  • Call Write() to write the form label, and then call InsertTextFormField() to insert a numeric form field.
  • Call Writeln() to move to a new line, write the check box label, and call InsertCheckBox() to insert a check box.
  • Save the result document with Document->SaveToFile().

The code for inserting a form field and a check box is shown below.

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

int main() {

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

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

    //Move to the end of the document and start a new paragraph
    navigator->MoveToDocumentEnd();
    navigator->Writeln();

    //Insert a numeric text form field
    navigator->Write("Budget amount (USD): ");
    navigator->InsertTextFormField("BudgetAmount", TextFormFieldType::NumberText,
                                   "0.00", "480000", 12);
    navigator->Writeln();

    //Insert a check box that is unchecked by default and has a size of 18
    navigator->Write("Confirm the above information: ");
    navigator->InsertCheckBox("ConfirmCheckBox", false, true, 18);
    navigator->Writeln();

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

At the end of the document, "Budget amount (USD): 480000" and "Confirm the above information:" are displayed in order, and the check box is displayed at the specified size:

The form field and check box inserted at the end of the document

Form Field Parameters Are Interpreted by Type

TextFormFieldType determines how the format and default value are interpreted. RegularText uses ordinary text, NumberText uses a numeric format (in the example, 0.00), DateText uses a date format, CurrentDate and CurrentTime take the current date or time, and Calculation uses a formula that starts with an equals sign. When the format does not match the type, the form field may display an incorrect value or empty content.

The Two Overloads of the Check Box

The three-parameter overload InsertCheckBox(name, checkedValue, size) specifies only the current checked state; the four-parameter overload InsertCheckBox(name, defaultValue, checkedValue, size) specifies the default state and the current checked state separately. The example uses the four-parameter overload, with the default state unchecked, the current state checked, and a size of 18.

Filling and Protecting Form Fields

The example demonstrates only the insertion of form fields, and the document does not enable protection. In Word, filling in form fields is usually combined with form protection; when editing is to be restricted to form fields, form protection can be enabled on the document. Without protection, the form fields are still displayed, but the body text can also be edited directly. The names of form fields should be unique within the same document so that they can be read or updated later.

Insert Fields

InsertField(FieldType, updateField) inserts a field by built-in type, and the second parameter specifies whether to update the result immediately; InsertField(fieldCode) inserts a field by field-code string and returns a Field object on which Update() can be called to calculate the field result.

The detailed steps are as follows.

  • Create a Document object and call LoadFromFile() to load the sample document.
  • Create a DocumentNavigator object and start a new paragraph at the end of the document.
  • Call Write() to write the explanatory text, and call InsertField(FieldType::FieldNumPages, true) and InsertField(FieldType::FieldPage, true) to insert the total page count and page number fields.
  • Call InsertField("DATE \@ "MMMM d, yyyy"") to insert a date field, and call Field->Update() to update the result.
  • Save the result document with Document->SaveToFile().

The code for inserting fields is shown below.

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

int main() {

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

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

    //Move to the end of the document and start a new paragraph
    navigator->MoveToDocumentEnd();
    navigator->Writeln();

    //Insert page number and page count fields by FieldType
    navigator->Write("This document contains ");
    navigator->InsertField(FieldType::FieldNumPages, true);
    navigator->Write(" page(s); this is page ");
    navigator->InsertField(FieldType::FieldPage, true);
    navigator->Write(".");
    navigator->Writeln();

    //Insert a date field by field code and update the result
    intrusive_ptr<Field> dateField = navigator->InsertField("DATE \\@ \"MMMM d, yyyy\"");
    dateField->Update();
    navigator->Writeln();

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

After insertion, the paragraph reads "This document contains 1 page(s); this is page 1.", and the next paragraph shows the date calculated in the specified format:

The page number and date fields inserted by FieldType and field code

Choosing Between Built-in Types and Field Codes

FieldType covers common fields such as page number, page count, date, and time, and using the enumeration avoids assembling field codes by hand. When a field requires a switch or is not covered by FieldType, use a field-code string. The DATE \@ "MMMM d, yyyy" in the example uses the \@ switch to specify the date format; in a C++ string, the backslash must be written as \\.

Updating Field Results

InsertField(FieldType, true) updates the result at insertion time. When a field is inserted by field code, the second parameter does not exist, and Field->Update() should be called after insertion; otherwise the field may display the field code or remain blank. The result of a date field depends on the system date, and the page number and page count fields depend on the final pagination, so they need to be updated again after the document content changes.

Field Results Participate in Layout

A field result is ordinary text and participates in paragraph layout and pagination. The page number and page count can be updated once before saving to obtain the current result; if further content is inserted later and changes the page count, the update method should be called again before saving so that the field results match the final layout.

Insert Images

InsertImage() provides several overloads: passing only the file name inserts the image at its original size; passing the file name, width, and height inserts it at the specified size; and passing the file name, horizontal origin and offset, vertical origin and offset, width and height, and wrapping style creates a floating image.

The detailed steps are as follows.

  • Create a Document object and call LoadFromFile() to load the sample document.
  • Create a DocumentNavigator object, start a new paragraph at the end of the document, write the image caption, and move to a new line.
  • Call InsertImage("progress.png", 280, 150) to insert the image at the specified width and height.
  • Save the result document with Document->SaveToFile().

The code for inserting an image is shown below.

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

int main() {

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

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

    //Move to the end of the document and start a new paragraph
    navigator->MoveToDocumentEnd();
    navigator->Writeln();
    navigator->Write("Implementation progress overview:");
    navigator->Writeln();

    //Insert the image at the specified width and height, in points
    navigator->InsertImage("progress.png", 280, 150);
    navigator->Writeln();

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

The progress diagram is inserted at the end of the document at 280 points wide and 150 points high:

The progress diagram inserted at the specified width and height

Image Overloads Control Layout

The short overload inserts the image at its original size, which suits icons whose size is already appropriate. The overload with width and height scales the image to the specified size, which is the one used in the example. The full overload sets the horizontal origin, horizontal offset, vertical origin, vertical offset, width and height, and wrapping style at the same time, for example:

navigator->InsertImage("progress.png",
    HorizontalOrigin::LeftMarginArea, 0,
    VerticalOrigin::Paragraph, 60,
    280, 150, TextWrappingStyle::Square);

When an image needs to be fixed at a position on the page and not move with the text flow, use the full overload and choose suitable origins and a wrapping style. Using the full overload requires including HorizontalOrigin.h, VerticalOrigin.h, and TextWrappingStyle.h.

Size Units Are Points

The width and height parameters of InsertImage() are in points, and one inch equals 72 points. The 280 × 150 in the example has the same aspect ratio as the 560 × 300 source image, so the image is not distorted after scaling. When only one dimension is known, calculate the other from the aspect ratio and pass a complete set of parameters.

Image Path and Working Directory

A relative path is resolved against the current working directory of the process. The example places progress.png in the same directory as the executable and loads it by file name at run time. If the image file does not exist or its format is not supported, the insertion operation fails, so the file path and format should be confirmed before the call.

Insert HTML

InsertHtml(html) parses an HTML fragment into document objects and inserts them one by one at the cursor position. Headings, paragraphs, bold text, and lists are converted into the corresponding document structures; the second overload accepts a useNavigatorFormatting parameter, which specifies whether the inserted content follows the navigator's current formatting settings.

The detailed steps are as follows.

  • Create a Document object and call LoadFromFile() to load the sample document.
  • Create a DocumentNavigator object, call MoveToDocumentEnd() to position at the end of the document, and call the parameterless Writeln() twice in succession to keep one empty paragraph as spacing.
  • Call InsertHtml() to insert an HTML fragment containing a heading, a paragraph, bold text, and a bulleted list.
  • Save the result document with Document->SaveToFile().

The code for inserting HTML is shown below.

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

int main() {

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

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

    //Move to the end of the document, start a new paragraph, and keep one empty paragraph as spacing
    navigator->MoveToDocumentEnd();
    navigator->Writeln();
    navigator->Writeln();

    //Convert the HTML fragment into document objects and insert them
    navigator->InsertHtml(
        "<h3>Supplementary Notes</h3>"
        "<p>After the platform goes live, the operations team will provide "
        "<strong>24x7</strong> support, and the fault response time will not exceed "
        "30 minutes.</p>"
        "<ul><li>Routine changes must be requested three working days in advance;</li>"
        "<li>Emergency changes are approved by the duty manager.</li></ul>");

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

The h3, p, strong, and ul/li in the HTML are converted into a heading, paragraphs, bold text, and a bulleted list:

The heading, paragraphs, and list converted from the HTML fragment

HTML Fragments Are Converted into Document Objects

InsertHtml() accepts an HTML fragment and does not require complete html and body tags. Headings are converted into the document's heading styles, paragraphs into body paragraphs, strong and em into bold or italic text, and ul/li into bulleted lists. The converted content participates in layout like native document objects and can be located and modified with the navigator afterward.

Keeping Navigator Formatting or Using the HTML's Own Formatting

The single-parameter overload generates formatting from the HTML tags themselves; the overload with the useNavigatorFormatting parameter can specify whether the inserted content follows the navigator's current formatting settings. When the inserted content needs to match the surrounding text, position at the target paragraph and set the character format first, then call the overload with that parameter.

Paragraph State After Insertion

After InsertHtml() finishes inserting, the cursor is in the last inserted paragraph. If the HTML ends with a list, a subsequent call to the parameterless Writeln() adds an empty paragraph that inherits the list formatting, which appears in the result as a redundant bullet. The example reserves an empty paragraph as spacing before insertion and does not append another empty paragraph afterward, avoiding this problem.

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.