Add, Delete and Extract Images from the PDF file
Add Image to Existing PDF File
Every PDF page object contains the getResources() and getContents() methods. Resources can be images and forms, for example, while content is represented by a set of PDF operators. Each operator has its own name and argument. This example use operators to add an image to a PDF file.
To add an image to an existing PDF file:
- Create a Document object and open the input PDF document.
- Get the page you want to add an image to.
- Add the image into the page’s getResources() collection.
- Use operators to place the image on the page:
- Use the GSave operator to save the current graphical state.
- Use the ConcatenateMatrix operator to specify where the image is to be placed.
- Use the Do operator to draw the image on the page.
- Finally, use the GRestore operator to save the updated graphical state.
- Save the file.
The following code snippet shows how to add image to a PDF document.
Adding image from BufferedImage into PDF
Starting release of Aspose.PDF for Java 9.5.0, we have introduced the support to add image from BufferedImage instance to PDF document. In order to support this requirement, a method is implemented: XImageCollection.add(BufferedImage image);
You can use any InputStream and not just only FileInputStream object to add image. So when using java.io.ByteArrayInputStream object, you do not need to store any files over system:
Delete Images from the PDF File
To delete an image from a PDF file, simply use the Images collection’s delete(..) method.
- Create Document object and open the input PDF file.
- Delete the image.
- Save the file.
The following code snippet shows how.
Extract Images from the PDF File
To extract and image from a page:
- Get the image from the Images collection using the image index.
- Use the XImage object’s save(..) method to save the extracted image.
The following code snippet shows you how to extract images from the PDF file.
Replace Image in an Existing PDF File
The Images collection’s replace(..) method allows you to replace an image in a PDF file. The Images collection can be found in a page’s Resources collection.
The following code snippet shows how to replace an image in a PDF file.
Delete Image from PDF Resources found by ImagePlacementAbsorber
To delete an image from a PDF file, you can simply use the Images collection’s delete(..) method. However, to delete image from the PDF resources found by ImagePlacementAbsorber, use the com.aspose.pdf.XImage.delete() method.
The following approach gets images from a PDF file and tries to delete them. Please note that an exception might be generated while removing image from PDF files.
Support for DICOM Images
Aspose.PDF for .NET supports functionality to add DICOM images to PDF documents. The following code snippet shows how to use this functionality.