PDFBox Inserting Image To PDF DocumentPDFBox provides a library for inserting an image to a PDF document. This library uses the Java program for inserting image in the PDF document. createFromFile() and drawImage() methods of the classes PDImageXObject and PDPageContentStream are used to insert image in the document. Follow the steps below to insert image in the existing PDF document- Load Existing DocumentWe can load the existing PDF document by using the static load () method. This method accepts a file object as a parameter. We can also invoke it using the class name PDDocument of the PDFBox. Retrieve PageIn this, we need to select a page in which an image will be inserted. The getPage() method is used to retrieve a page from PDF document. This method accepts a page number as a parameter for that page which we want to retrieve. This can be shown in the following code. Create Object for PDImageXObjectThe PDImageXobject class is used to create an image in the document. This class is responsible for performing all the operations related to an image like inserting an image, setting the height and width of the image etc. The createFromFile() method is used to create an object of PDImageXobject class. In this method, we need to pass the path of the image which we want to insert and document object to which image needs to be added. Prepare Content StreamThe PDPageContentStream class is used to create an object for inserting the various data elements. The constructor of this class contains the document object and the page object as a parameter as shown below. Draw ImageThe drawImage() method is used to insert an image in the PDF document. In this method, we need to pass the page object and dimensions of the image as a parameter to draw an image. Close PDPageContentStreamWe can close the PDPageContentStream class by using close() method. Save DocumentThe save () method is used to save the document. The save () method accepts a string value and passes a path of the document as a parameter. Close DocumentAfter completing the task, we need to close the PDDocument class object by using the close () method. Example-Output: After successful execution of the above program, it shows the following output message. ![]() Now, to verify the image is inserted in the document, open the PDF document, which will show the following output. ![]()
Next TopicPDFBox Extracting Image
|