In order to add Image in PDF, we’ll use Aspose.PDF for Java API which is a feature-rich, powerful, and easy-to-use conversion API for the Java platform. You can download its latest version directly from Maven and install it within your Maven-based project by adding the following configurations to the pom.xml.
<repository>
<id>AsposeJavaAPI</id>
<name>Aspose Java AP</name>
<url>https://releases.aspose.com/java/repo/</url>
</repository>
<dependency>
<groupId>com.aspose</groupId>
<artifactId>aspose-pdf</artifactId>
<version>version of aspose-pdf API</version>
</dependency>
Add Image to PDF using Java
You need Aspose.PDF for Java 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 - Java
try {
Document pdfDocument = new Document(DATA_DIR.resolve("AddImage.pdf").toString());
int lowerLeftX = 100;
int lowerLeftY = 100;
int upperRightX = 200;
int upperRightY = 200;
Page page = pdfDocument.getPages().get_Item(1);
FileInputStream imageStream = new FileInputStream(DATA_DIR.resolve("aspose-logo.jpg").toString());
page.getResources().getImages().add(imageStream);
page.getContents().add(new GSave());
Rectangle rectangle = new Rectangle(lowerLeftX, lowerLeftY, upperRightX, upperRightY);
Matrix matrix = new Matrix(new double[]{
rectangle.getURX() - rectangle.getLLX(), 0,
0, rectangle.getURY() - rectangle.getLLX(),
rectangle.getLLX(), rectangle.getLLY()});
page.getContents().add(new ConcatenateMatrix(matrix));
XImage ximage = page.getResources().getImages().get_Item(page.getResources().getImages().size());
page.getContents().add(new Do(ximage.getName()));
page.getContents().add(new GRestore());
pdfDocument.save(DATA_DIR.resolve("AddImage_out.pdf").toString());
pdfDocument.close();
} catch (Exception e) {
System.out.println(e.getMessage());
}