项目可以在日食中工作,但不能打包在罐子中

时间:2019-01-15 02:06:37

标签: java maven jar itext7

我的项目使用itext7创建PDF文件。当我从eclipse启动时,一切正常。当我将其包装为罐子时,一切正常,直到我要创建PDF为止。然后我得到:

  

线程“ JavaFX Application Thread”中的异常com.itextpdf.io.IOException:I / O异常。
      .....

     

原因:java.io.FileNotFoundException:C:\ Users \ puser \ eclipse-workspace \ Document \ target \ SE001-0.1.1-SNAPSHOT.jar \ img \ Safety.png(系统找不到指定的路径)

项目文件夹将图像保存在src/main/resources/img。创建罐子后,它的根目录只是/img。这意味着您不能仅指定直接路径,因为它在创建jar时会改变。 JavaFX Images可以正常使用。

Image user = new Image(getClass().getResourceAsStream("/img/Document.png"));

将它与itext7一起使用是行不通的,因为ImageDataFactory.create()正在寻找byte [],并且这是输入流。

现在尝试使用:

Image safetyImage = new Image(ImageDataFactory.create(System.getProperty("user.dir") + "/img/Safety.png"));

不起作用,因为Jar不在路径内。

我可以使用什么指向jar中的图像文件并将其与ext7一起使用?

1 个答案:

答案 0 :(得分:0)

mkl是正确的,谢谢!

我创建了一个实用程序方法来将输入流转换为字节数组。

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

然后我在ImageDataFactory.create()方法中使用了该实用程序。

Image safetyImage = new Image(ImageDataFactory.create(toByteArray(getClass().getResourceAsStream("/img/Safety.png"))));
相关问题