这个问题在这里已有答案:
在我的Spring启动webapp中,我试图使用JasperReports
实现一些后端功能来生成PDF文件。
我有一个看起来像这样的文件结构:
该应用程序在运行时,可以看到application-*.properties
或static
文件夹中的任何文件。
我写了一段代码来生成报告并在JasperViewer
中显示:
JasperPrint print = null;
try {
JasperCompileManager.compileReportToFile("invoices/invoice.jrxml");
print = JasperFillManager.fillReport("invoices/invoice.jasper", new HashMap<>());
JasperViewer jasperViewer = new JasperViewer(print);
jasperViewer.setVisible(true);
} catch (JRException e) {
e.printStackTrace();
}
但是当我试图运行应用程序时,我得到的只是:
net.sf.jasperreports.engine.JRException: java.io.FileNotFoundException: invoices/invoice.jrxml (No such file or directory)
您正在使用java.io
文件api操作从类路径加载资源。它在IDE中开发期间解压缩应用程序时有效,但当应用程序打包到JAR时会失败,因此FileNotFoundException
更改代码以使用InputStream
从类路径加载资源,例如通过使用JasperCompileManager.compileReport()
:
try (InputStream in = getClass().getResourceAsStream("/invoices/invoice.jrxml")) {
JasperCompileManager.compileReport(in);
...
}