Various industries use PDF format to automatically generate their documents such as invoices, reports, technical articles, etc. Along with text, these documents may also contain images and other graphical objects. In some instances, you have to replace the confidential images in the PDF documents before sharing. To accomplish that programmatically, this article covers how to replace images in PDF documents in Java.
Java Library to Replace Images in PDF
To replace images in PDF files, we will use Aspose.PDF for Java. It is a powerful library that provides basic as well as advanced PDF generation and manipulation features. You can either download the API or install it using the following Maven configurations.
Repository:
<id>AsposeJavaAPI</id>
<name>Aspose Java API</name>
<url>https://repository.aspose.com/repo/</url>
</repository>
Dependency:
<dependency>
<groupId>com.aspose</groupId>
<artifactId>aspose-pdf</artifactId>
<version>22.12</version>
</dependency>
How to Replace Images in a PDF in Java
In PDF documents, the images are kept in an image collection of each page. Thus, you can access any of the images from the collection using its index and manipulate it. The following are the steps to replace a particular image in a PDF in Java.
- Load the PDF file using the Document class.
- Get reference of the desired page of the PDF from collection using Document.getPages() method.
- Replace the image in the collection using [Pages[index].getResources().getImages().replace(imageIndex, new FileInputStream(“lovely.jpg”))]6 method.
- Save the updated document using Document.save(string) method.
The following code sample shows how to replace an image in a PDF using Java.
Free Library to Replace Images in PDF
You can get a free temporary license and replace images in PDF files without any limitations.
Explore Java PDF Library
You can explore more about the Java PDF library using the documentation. In case you would have any questions or queries, you can contact us via our forum.
Conclusion
In this article, you have learned how to replace images in PDF files using Java. You can simply integrate the provided code sample and replace PDF images from within your applications. Simply install the library and following the steps to replace images in PDF from within your Java applications.