user3244519
user3244519

Reputation: 681

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);  

Upvotes: 0

Views: 1486

Answers (3)

Washim Billing
Washim Billing

Reputation: 1

String IMAGE_NAME = "src/mse.png";
Path imgPath_mse = Paths.get(IMAGE_NAME);
PDImageXObject image_m = PDImageXObject.createFromFile(imgPath_mse , document);

Above code works fine for IDE run but it was giving 'image not found' error for run through JAR.

I tried following and it worked in both IDE and JAR:

InputStream imageAsStream = ClassLoader.getSystemResourceAsStream("mse.png"); 
byte [] ba = IOUtils.toByteArray(imageAsStream);
PDImageXObject image_m = PDImageXObject.createFromByteArray(document, ba, null);

Upvotes: 0

Tilman Hausherr
Tilman Hausherr

Reputation: 18916

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");
}

Upvotes: 3

Samuel Marchant
Samuel Marchant

Reputation: 330

Unless eclipse-workspace folder is on / (root) the top file in the OS then it would be implicit and incorrectly stated, when you installed configured eclipse it usually asserts the user home folder to put workspace into. If it is on root / then i suggest you add a FileNotFoundException before the IOException.

Upvotes: 0

Related Questions