This article assists in how to insert image into PDF using Java. It provides details about the IDE configuration, a step-by-step process to write the application, and a runnable sample code to add image to PDF using Java. You will also learn different options to customize the process to render the image in any format say PNG, JPEG, etc., and place the image at a desired position on the PDF page.
Steps to Put Image in PDF using Java
- Establish the environment to use Aspose.PDF for Java to insert an image
- Load the source PDF file, get access to the first page for adding an image, and save the graphics state
- Create a stream of the image and add it to the images collection resource of the loaded PDF
- Instantiate the Matrix object using the desired rectangular position for the image
- Define the image drawing options and draw the image using the Do() method
- Restore the graphics state and save the output PDF before closing the image and PDF streams
These steps explain how to add image in PDF using Java where first the page reference is obtained from the loaded PDF file and then the image stream is created. This image is added to the image collection of the selected page and then the transformation Matrix is declared using the positional rectangle for the target image. In the end, the image is rendered using the Do() method, and the resultant PDF file is saved on the disk.
Code to Add Photo in PDF using Java
This code demonstrates the process to add picture to PDF using Java. It uses the Document class to load the PDF, the Page class object to hold the reference to the target PDF page, the FileInputStream object to hold the target image, the rectangle class to describe the image position on the page, the Matrix object to define the drawing of the image, and the Do() method to render the image. Note that the graphics state is saved before starting this operation and restored once the operation is completed.
In this article, we have witnessed the process to add photo to PDF using Java. If you want to learn the process to add a watermark in a PDF refer to the article on how to add watermark to PDF using Java.