Create MS Word Documents (DOC/DOCX) using C++

Create Word Documents in C++

Aspose.Words is a feature-rich collection of APIs that lets you create, edit, and convert MS Word documents programmatically. It provides a wide range of basic as well as advanced features for manipulating word processing documents. In this article, you will learn how to use Aspose.Words for C++ and create MS Word documents from scratch using C++. The step by step guide as well as code samples will let you know how to insert text, images, tables, lists, and other elements in Word documents.

C++ API to Create MS Word Documents

Aspose.Words for C++ lets you generate and manipulate the word processing documents within C++ applications without MS Word. You can download the API or install it within your C++ applications using NuGet with the following command.

PM> Install-Package Aspose.Words.Cpp

Create MS Word Documents using C++

Let’s first create a simple Word document and save it as a .doc or .docx file. For this, you need to follow the below steps:

The following code sample shows how to create a Word DOCX document using C++.

// Initialize a Document.
System::SharedPtr<Document> doc = System::MakeObject<Document>();
// Use a document builder to add content to the document.
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
// Add text
builder->Writeln(u"Hello World!");
// Save the document to disk.
doc->Save(u"document.docx");

Edit or Update Existing Word DOC/DOCX using C++

You may also edit the existing Word documents using Aspose.Words for C++. For this, the API uses the Document Object Model (DOM) for the in-memory representation of a document. The DOM lets you access the elements of a Word document such as header/footer, paragraphs, tables, and etc. Read more about the DOM here.

For updating a Word document, simply load it using Document class and process it as desired. The following are the steps to edit and update an existing Word document.

  • Load the Word document using Document class.
  • Create an object of DocumentBuilder class to access the content.
  • Access the desired paragraph (or any other element) and update the content.
  • Save the updated document using Document->Save() method.

The following code sample shows how to update the text of a paragraph in a Word document using C++.

// Initialize a Document.
System::SharedPtr<Document> doc = System::MakeObject<Document>(u"document.docx");
// Use a document builder to add content to the document.
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
// Get section
auto section = doc->get_Sections()->idx_get(0);
// Get body
auto body = section->get_Body();
// Get first paragraph
auto para = body->get_FirstParagraph();
// Update text
auto run = para->get_Runs()->idx_get(0);
run->set_Text(u"This is the updated text.");
// Save the document to disk.
doc->Save(u"updated_document.docx");

Insert Images in Word Document using C++

The following are the steps to insert an image within MS Word documents using C++.

The following code sample shows how to insert an image into a Word document using C++.

System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
// Add a logo to the top left of the page. The image is placed in front of all other text.
System::SharedPtr<Shape> shape = builder->InsertImage( u"Aspose Logo.png", RelativeHorizontalPosition::Page, 60.0, RelativeVerticalPosition::Page, 60.0, -1.0, -1.0, WrapType::None);
doc->Save(u"document_with_image.docx");

Insert Table in Word Documents using C++

The table is an important element of the Word documents to keep the data in the form of rows and columns. In order to generate a table within the Word documents, follow the below steps.

  • Create a new Word document using Document class.
  • Create an object of Table class.
  • Insert table into the document using Document->get_FirstSection()->get_Body()->AppendChild() method.
  • Create a new row using the Row class.
  • Insert row into the table using Table->AppendChild(row) method.
  • Create and new Cell and insert text into it using Cell->get_FirstParagraph()->AppendChild() method.
  • Insert cell into the row using Row->AppendChild() method.
  • Repeat the process for adding multiple rows.
  • Save the document using Document->Save() method.

The following code sample shows how to insert a table in Word document using C++.

System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<Table> table = System::MakeObject<Table>(doc);
// Add the table to the document.
doc->get_FirstSection()->get_Body()->AppendChild(table);
System::SharedPtr<Row> row = System::MakeObject<Row>(doc);
row->get_RowFormat()->set_AllowBreakAcrossPages(true);
table->AppendChild(row);
// We can now apply any auto fit settings.
table->AutoFit(AutoFitBehavior::FixedColumnWidths);
// Create a cell and add it to the row
System::SharedPtr<Cell> cell = System::MakeObject<Cell>(doc);
cell->get_CellFormat()->get_Shading()->set_BackgroundPatternColor(System::Drawing::Color::get_LightBlue());
cell->get_CellFormat()->set_Width(80);
// Add a paragraph to the cell as well as a new run with some text.
cell->AppendChild(System::MakeObject<Paragraph>(doc));
cell->get_FirstParagraph()->AppendChild(System::MakeObject<Run>(doc, u"Row 1, Cell 1 Text"));
// Add the cell to the row.
row->AppendChild(cell);
// We would then repeat the process for the other cells and rows in the table.
// We can also speed things up by cloning existing cells and rows.
row->AppendChild((System::StaticCast<Node>(cell))->Clone(false));
row->get_LastCell()->AppendChild(System::MakeObject<Paragraph>(doc));
row->get_LastCell()->get_FirstParagraph()->AppendChild(System::MakeObject<Run>(doc, u"Row 1, Cell 2 Text"));
// Save the document to disk.
doc->Save(u"document_with_table.docx");

Add Lists in Word Documents using C++

Last but not the least, creating a list in the Word documents. The following are the steps to create a bullet list.

  • Create a new Word document or load an existing one using Document class.
  • Define a new DocumentBuilder object and initialize it with the Document object.
  • Create list using DocumentBuilder->get_ListFormat()->set_List(Document->get_Lists()->Add(ListTemplate::NumberArabicDot)) method.
  • Populate the list and set the list level.
  • Save the document as a file.

The following code sample shows how to create a list in a Word document using C++.

System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
// Create a numbered list based on one of the Microsoft Word list templates and
// apply it to the current paragraph in the document builder.
builder->get_ListFormat()->set_List(doc->get_Lists()->Add(ListTemplate::NumberArabicDot));
// There are 9 levels in this list, lets try them all.
for (int32_t i = 0; i < 9; i++)
{
builder->get_ListFormat()->set_ListLevelNumber(i);
builder->Writeln(System::String(u"Level ") + i);
}
// Create a bulleted list based on one of the Microsoft Word list templates
// and apply it to the current paragraph in the document builder.
builder->get_ListFormat()->set_List(doc->get_Lists()->Add(ListTemplate::BulletDiamonds));
// There are 9 levels in this list, lets try them all.
for (int32_t i = 0; i < 9; i++)
{
builder->get_ListFormat()->set_ListLevelNumber(i);
builder->Writeln(System::String(u"Level ") + i);
}
// This is a way to stop list formatting.
builder->get_ListFormat()->set_List(nullptr);
// Save the document to disk.
builder->get_Document()->Save(u"document_with_list.docx");

Conclusion

In this article, you have seen how to create MS Word documents from scratch using C++. Furthermore, you have learned how to insert elements such as text, images, tables, and lists in new or existing Word documents. You can explore more about the advanced features of the API using the documentation.

See Also