Work with Images in PDF via C++

Manipulate images in PDF document. Use Aspose.PDF for C++ to modify PDF documents programmatically

Most popular action with Images in C++

Add Image to PDF Document Using C++ Library

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.

Package Manager Console

PM > Install-Package Aspose.PDF.Cpp

Add Image to PDF via C++


You need Aspose.PDF for C++ to try the code in your environment.

  1. Create a Document object and open the input PDF document.
  2. Get the page you want to add an image.
  3. Add the image into the page’s Resources collection.
  4. Use the GSave operator to save the current graphical state.
  5. Use ConcatenateMatrix operator to specify where the image is to be placed.
  6. Use the Do operator to draw the image on the page.
  7. Use GRestore operator to save the updated graphical state.
  8. Save the PDF file.

Add Image in an Existing PDF File - C++

Example: 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();