Add Image to PDF Example
This program demonstrates adding an image into a PDF file.
Problem Statement
Write a Java program that inserts an image into a PDF file using PDFBox.
Source Code
| 1 | import java.io.*; |
| 2 | import org.apache.pdfbox.pdmodel.*; |
| 3 | import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject; |
| 4 | public class AddImagePDFExample { |
| 5 | public static void main(String[] args) { |
| 6 | System.out.println("Eduinq Add Image PDF Example"); |
| 7 | try(PDDocument doc=new PDDocument()) { |
| 8 | PDPage page=new PDPage(); |
| 9 | doc.addPage(page); |
| 10 | PDImageXObject img=PDImageXObject.createFromFile("logo.png",doc); |
| 11 | PDPageContentStream cs=new PDPageContentStream(doc,page); |
| 12 | cs.drawImage(img,100,600,200,100); |
| 13 | cs.close(); |
| 14 | doc.save("image.pdf"); |
| 15 | System.out.println("Eduinq Image Added Successfully"); |
| 16 | } catch(IOException e) { |
| 17 | System.out.println("Eduinq Exception: "+e.getMessage()); |
| 18 | } |
| 19 | } |
| 20 | } |
Program Output
Eduinq Add Image PDF Example Eduinq Image Added Successfully
Explanation
PDFBox PDImageXObject embeds images. - drawImage() places image at coordinates. - Exception handling ensures safe operations. - In enterprise systems, adding images is used for branding and logos. Conclusion: Shows adding images to PDF files.