Search code examples
javaspringspring-bootclasspathpdfbox

Unable to Insert image from classpath into PDF using PDFBox


I have a springBoot project and i am trying to insert an image into PDF using PDFBox library. The image is present in src/main/resources/image folder (myImage.jpg). The implementation code is as given below. While running the program i am getting an error that image is not found at specified path. What is the correct way to retrieve the image from classpath in this scenario.

public class PDFImageService {  
  
public void insertImage() throws IOException {  
              
    //Loading an existing document   
      File file = new File("/eclipse-workspace/blank.pdf");  
      PDDocument doc = PDDocument.load(file);  
  
//Retrieving the page  
      PDPage page = doc.getPage(1);  
  
//Creating PDImageXObject object  
      PDImageXObject pdImage = PDImageXObject.createFromFile("/image/myImage.jpg",doc);  
  
//creating the PDPageContentStream object  
      PDPageContentStream contents = new PDPageContentStream(doc, page);  

//Drawing the image in the PDF document  
contents.drawImage(pdImage, 250, 300);  

      System.out.println("Image inserted Successfully.");  
  
//Closing the PDPageContentStream object  
contents.close();         
  
//Saving the document  
doc.save("/eclipse-workspace/blank.pdf");  
  
//Closing the document  
doc.close();  
}  

}

It works fine if i give the fully specified image path as

PDImageXObject pdImage = PDImageXObject.createFromFile("C:\Users\Dell\Desktop\PDF\myImage.jpg",doc);  

Solution

  • As discussed in the comments, it works by using

    PDImageXObject img;
    try (InputStream is = PDFImageService.class.getResourceAsStream("/image/myImage.jpg");
    {
        // check whether InputStream is null omitted
        byte [] ba = IOUtils.toByteArray(imageAsStream);
        img = PDImageXObject.createFromByteArray(document, ba, "myImage.jpg");
    }