Apache PDFbox is an open source java library used for manipulation of PDF’s. In this post we will see how to Add Image in PDF using Apache PDFBox.
Class – PDImageXObject
For creating an image in the PDF file, PDImageXObject class is used. The commonly used methods of this class are
a) createFromFile(String imagePath, PDDocument doc)
b) createFromFileByContent(File file, PDDocument doc)
c) createFromFileByExtension(File file, PDDocument doc)
d) setHeight(int h)
e) setWidth(int w)
For adding the image that was created using above methods, PDPageContentStream.drawImage() is used.
Now we will use few of these methods and create a simple pdf file with image.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
package com.kscodes.examples.pdfbox; import java.io.IOException; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.pdmodel.PDPage; import org.apache.pdfbox.pdmodel.PDPageContentStream; import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject; public class PdfImageExample { public static void main(String args[]) { // Create a Document object. PDDocument pdDocument = new PDDocument(); // Create a Page object PDPage pdPage = new PDPage(); // Add the page to the document and save the document to a desired file. pdDocument.addPage(pdPage); try { // Create a Content Stream PDPageContentStream pdPageContentStream = new PDPageContentStream(pdDocument, pdPage); // Creating an PDImageXObject object PDImageXObject pdImageXObj = PDImageXObject.createFromFile("K:\\Kscodes\\Images\\jobsImage.png", pdDocument); // Draw that image to the content stream pdPageContentStream.drawImage(pdImageXObj, 30, 650); // Once all the content is written, close the stream pdPageContentStream.close(); pdDocument.save("K:\\Kscodes\\pdf\\imageSample.pdf"); pdDocument.close(); System.out.println("PDF saved to the location !!!"); } catch (IOException ioe) { System.out.println("Error while saving pdf" + ioe.getMessage()); } } } |
Output