joe
joe

Reputation: 41

Apache poi java: Image not showing in document when running JAR file in another computer

I created an app that works with files and works perfectly in the computer where I wrote the code, however it does not work correctly in other computers. After reviewing the entire code I was able to find the issue. I removed the following method that adds an image and the jar file works fine in multiple computers, however I need the image to be added. The method is the following: (doc is a static variable declared in another class, in case you wonder)

            public void AddImage() throws IOException, InvalidFormatException {

        XWPFParagraph parag = document.createParagraph();
        XWPFRun r = parag.createRun();

        URL imageURL = ClassLoader.getSystemResource("TheImage.png");
        String imageName = imageURL.getPath();
        File image = new File(imageName);
        FileInputStream fis = new FileInputStream(image);

        BufferedImage bimg1 = ImageIO.read(image);
        int width = 160;//bimg1.getWidth();
        int height = 26;//bimg1.getHeight();  

        String imgFile = image.getName(); 

        r.addPicture(fis, document.PICTURE_TYPE_PNG, imgFile, Units.toEMU(width), Units.toEMU(height));
    }

To give you more details, I created a source file in the project in eclipse where I added the image, does anybody know how to solve this?

Upvotes: 1

Views: 199

Answers (1)

Marc Stroebel
Marc Stroebel

Reputation: 2357

Perhaps on your computer the image is taken from the file system instead from the jar. Is the image packaged in the jar file? Then try

Inputstream logo = getClass().getResourceAsStream("/path/in/jar/img.png");

to load it.

How to read a file from jar in Java?

Upvotes: 3

Related Questions