In order to add Image in PDF, we’ll use Aspose.PDF for C++ API which is a feature-rich, powerful and easy to use document manipulation API for cpp platform. Open NuGet package manager, search for Aspose.PDF and install. You may also use the following command from the Package Manager Console.
PM > Install-Package Aspose.PDF.Cpp
Add Image to PDF using C++
You need Aspose.PDF for C++ to try the code in your environment.
- Create a Document object and open the input PDF document.
- Get the page you want to add an image.
- Add the image into the page’s Resources collection.
- Use the GSave operator to save the current graphical state.
- Use ConcatenateMatrix operator to specify where the image is to be placed.
- Use the Do operator to draw the image on the page.
- Use GRestore operator to save the updated graphical state.
- Save the PDF file.
Add Image to PDF document - C++
String _dataDir("C:\\Samples\\");
auto document = MakeObject<Document>(_dataDir + u"AddImage.pdf");
int lowerLeftX = 50;
int lowerLeftY = 750;
int upperRightX = 100;
int upperRightY = 800;
auto page = document->get_Pages()->idx_get(1);
auto imageStream = System::IO::File::OpenRead(_dataDir + u"logo.png");
page->get_Resources()->get_Images()->Add(imageStream);
page->get_Contents()->Add(MakeObject<Aspose::Pdf::Operators::GSave>());
auto rectangle = MakeObject<Rectangle>(lowerLeftX, lowerLeftY, upperRightX, upperRightY);
auto matrix = MakeObject<Matrix>(
MakeArray<double>({
rectangle->get_URX() - rectangle->get_LLX(),
0, 0,
rectangle->get_URY() - rectangle->get_LLY(),
rectangle->get_LLX(), rectangle->get_LLY() }));
page->get_Contents()->Add(MakeObject<Aspose::Pdf::Operators::ConcatenateMatrix>(matrix));
auto ximage = page->get_Resources()->get_Images()->idx_get(page->get_Resources()->get_Images()->get_Count());
page->get_Contents()->Add(MakeObject<Aspose::Pdf::Operators::Do>(ximage->get_Name()));
page->get_Contents()->Add(MakeObject<Aspose::Pdf::Operators::GRestore>());
document->Save(_dataDir + u"updated_document.pdf");
imageStream->Close();