Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aspose-com-gists/fe6702a902f416508a722c2f08a6f499 to your computer and use it in GitHub Desktop.
Save aspose-com-gists/fe6702a902f416508a722c2f08a6f499 to your computer and use it in GitHub Desktop.
Add, Extract, Remove or Replace Images in PDF Files using C++ | https://blog.aspose.com/2021/08/02/working-with-images-in-pdf-files-using-cpp/
Read the complete article about working with images in PDF files using C++ by visiting the following link.
https://blog.aspose.com/2021/08/02/working-with-images-in-pdf-files-using-cpp/
// Load the PDF file
auto pdfDocument = MakeObject<Document>(u"SourceDirectory\\PDF\\Sample 1.pdf");
// Retrieve the first page
auto page = pdfDocument->get_Pages()->idx_get(1);
// Create an instance of the Rectangle class
double x = 100.0, y = 600.0, width = 200.0, height = 200.0;
auto rectangle = MakeObject<Aspose::Pdf::Rectangle>(x, y, x + width, y + height);
// Add image to the page
page->AddImage(u"SourceDirectory\\Images\\AsposeLogo.png", rectangle);
// Save the PDF file
pdfDocument->Save(u"OutputDirectory\\add_image_output.pdf");
// Load the PDF file
auto pdfDocument = MakeObject<Document>(u"OutputDirectory\\add_image_output.pdf");
// Delete a particular image
pdfDocument->get_Pages()->idx_get(1)->get_Resources()->get_Images()->Delete(1);
// Save the PDF file
pdfDocument->Save(u"OutputDirectory\\delete_image_output.pdf");
// Load the PDF file
auto pdfDocument = MakeObject<Document>(u"OutputDirectory\\add_image_output.pdf");
// Extract a particular image
auto image = pdfDocument->get_Pages()->idx_get(1)->get_Resources()->get_Images()->idx_get(1);
// Create a stream object to save the output image
System::SharedPtr<System::IO::FileStream> outputImage = System::IO::File::Create(u"OutputDirectory\\extract_image_output.jpg");
// Save the output image
image->Save(outputImage, System::Drawing::Imaging::ImageFormat::get_Jpeg());
// Close the stream
outputImage->Close();
// Load the PDF file
auto pdfDocument = MakeObject<Document>(u"OutputDirectory\\add_image_output.pdf");
// Open the new image with FileStream
System::SharedPtr<System::IO::FileStream> newImage = System::IO::File::OpenRead(u"SourceDirectory\\Images\\aspose.png");
// Replace the old image
pdfDocument->get_Pages()->idx_get(1)->get_Resources()->get_Images()->Replace(1, newImage);
// Close the stream
newImage->Close();
// Save the PDF file
pdfDocument->Save(u"OutputDirectory\\replace_image_output.pdf");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment