问题
My project uses itext7 to create PDF files. When I launch from eclipse everything works perfectly. When I package it as a jar, everything works until I get to the point that I want to create a PDF. I then get:
Exception in thread "JavaFX Application Thread" com.itextpdf.io.IOException: I/O exception.
.....Caused by: java.io.FileNotFoundException: C:\Users\puser\eclipse-workspace\Document\target\SE001-0.1.1-SNAPSHOT.jar\img\Safety.png (The system cannot find the path specified)
The project folder keeps the images at src/main/resources/img
. Once the jar is created it simply has /img
at root. This means you can't just specify a direct path because it changes when the jar is made. JavaFX Images work fine with..
Image user = new Image(getClass().getResourceAsStream("/img/Document.png"));
Using that with itext7 doesn't work because ImageDataFactory.create()
is looking for byte[] and that is an input stream.
Now trying to use:
Image safetyImage = new Image(ImageDataFactory.create(System.getProperty("user.dir") + "/img/Safety.png"));
Does not work because the Jar is not inside the path.
What can I use to point to an image file inside the jar and use it with it ext7?
回答1:
mkl was correct and thank you!
I created a utility method to convert an input steam to a byte array.
public static byte[] toByteArray(InputStream in) throws IOException {
//InputStream is = new BufferedInputStream(System.in);
ByteArrayOutputStream os = new ByteArrayOutputStream();
byte [] buffer = new byte[1024];
int len;
// read bytes from the input stream and store them in buffer
while ((len = in.read(buffer)) != -1) {
// write bytes from the buffer into output stream
os.write(buffer, 0, len);
}
return os.toByteArray();
}
I then used that utility inside the ImageDataFactory.create() method.
Image safetyImage = new Image(ImageDataFactory.create(toByteArray(getClass().getResourceAsStream("/img/Safety.png"))));
来源:https://stackoverflow.com/questions/54191804/project-works-in-eclipse-but-not-after-being-packaged-in-a-jar