How to Add Image in DOCX using C++

In this example, we will learn how to add image in DOCX using C++. Inserting images inside word document using C++ is one of commonly inquired requirement by developers. Adding image to DOC using C++ can be achieved using simple API calls.

Steps to Add Image in DOCX using C++

  1. Download and install latest Aspose.Words.Cpp NuGet package
  2. Add a reference to Aspose::Words namespace
  3. Instantiate Document Class object to load DOCX for adding image
  4. Instantiate DocumentBuilder class to work with content inside DOCX
  5. Use imageWriter method to load and add JPEG image inside document
  6. Save the DOCX with Image in C++ by using Save method

In the following example, you can easily add JPEG image to DOCX in C++ by using few API calls and having no external dependence on MS Word. The API allow you to add JPEG, PNG, GIF or EMF images inside Word document.

Code to Add Image in DOCX using C++

#pragma once
#include <cstdint>
#include <iostream>
#include <Aspose.Words.Cpp/Document.h>
#include <Aspose.Words.Cpp/DocumentBase.h>
#include <Aspose.Words.Cpp/DocumentBuilder.h>
#include <Aspose.Words.Cpp/Drawing/Shape.h>
#include <Aspose.Words.Cpp/HeaderFooterType.h>
#include <Aspose.Words.Cpp/Saving/SaveOutputParameters.h>
#include <system/array.h>
#include <system/exceptions.h>
#include <Aspose.Words.Cpp/License.h>
#include <system/io/path.h>
using System::ArrayPtr;
using System::MakeArray;
using System::MakeObject;
using System::SharedPtr;
using System::String;
using namespace Aspose::Words;
using namespace Aspose::Words::Drawing;
class AddContentUsingDocumentBuilder
{
public:
void AddImageinWordDocument()
{
// File name and path of license file
System::String LicenseFileName = u"Aspose.Total.NET.lic";
// Setting the Aspose.Words before creating Word document
SharedPtr<License> wordsLicense = System::MakeObject<License>();
// Setting product license
wordsLicense->SetLicense(LicenseFileName);
// Instantiate Document class to load DOCX and add image
SharedPtr<Document> AddImagesToWordDOC = MakeObject<Document>(u"input.docx");
// Instantiate DocumentBuilder class to work with content inside DOCX
SharedPtr<DocumentBuilder> imageWriter = MakeObject<DocumentBuilder>(AddImagesToWordDOC);
// Take cursor to Primary Header in document
imageWriter->MoveToHeaderFooter(HeaderFooterType::HeaderPrimary);
// Insert image in word document using C++
SharedPtr<Shape> headerImage = imageWriter->InsertImage(u"Add Image in Word Header.jpg");
// Set Image Size in Header
headerImage->set_Width(1 * 72); // equals to one inch
headerImage->set_Height(1 * 72);
// Save the word document with image to docx format
AddImagesToWordDOC->Save(u"InsertImageinDocx.docx");
}
};

Earlier, we looked in to How to Convert Word Document to Images using C++. Whereas in this topic we have learnt how insert image to Word document using C++.

 English