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
Document pdfDocument = new Document(dataDir+ "AddImage.pdf");
int lowerLeftX = 100;
int lowerLeftY = 100;
int upperRightX = 200;
int upperRightY = 200;
Page page = pdfDocument.Pages[1];
FileStream imageStream = new FileStream(dataDir + "aspose-logo.jpg", FileMode.Open);
page.Resources.Images.Add(imageStream);
page.Contents.Add(new Aspose.Pdf.Operators.GSave());
Aspose.Pdf.Rectangle rectangle = new Aspose.Pdf.Rectangle(lowerLeftX, lowerLeftY, upperRightX, upperRightY);
Matrix matrix = new Matrix(new double[] { rectangle.URX - rectangle.LLX, 0, 0, rectangle.URY - rectangle.LLY, rectangle.LLX, rectangle.LLY });
page.Contents.Add(new Aspose.Pdf.Operators.ConcatenateMatrix(matrix));
XImage ximage = page.Resources.Images[page.Resources.Images.Count];
page.Contents.Add(new Aspose.Pdf.Operators.Do(ximage.Name));
page.Contents.Add(new Aspose.Pdf.Operators.GRestore());
dataDir = dataDir + "AddImage_out.pdf";
pdfDocument.Save(dataDir);