如何设置图片表情始终存储正确的图片路径

How to set the image expression to always store the right image path

我正在使用 JasperReports 通过 Java 动态创建报告。我对图像表达(图像路径)有疑问。这是我现在通过的方式:

JRDefaultStyleProvider JRDefaultStyleProvider = null;
JRDesignImage image = new JRDesignImage(JRDefaultStyleProvider);
image.setX(0);
image.setY(0);
image.setWidth(200);
image.setHeight(200);
exp = new JRDesignExpression();
**exp.setText("\"D:/MyProgram/src/myprogram/images/logo.png\"");**
image.setExpression(exp);
image.setStyle(styles.imageStyle);
title_band.addElement(image);

它工作正常,但如果我更改 MyProgram 的位置,我还必须更改表达式中的路径。 我尝试将表达式设置为:../images/logo.png 但出现错误“未在以下位置找到字节数据:../images/logo.png”。任何帮助,将不胜感激。

您可以做几件事。

一种是在报表中手动添加一个名为ProjectRoot的参数,使用$P{ProjectRoot} + "images/logo.png"作为图像表达式,并在运行报表时为ProjectRoot传递一个值(取自环境)。

另一种方法是利用 JasperReports 还尝试将图像位置解析为类加载器资源这一事实。因此,如果您将 src/myprogram 添加为源文件夹,以便 images/logo.png 在 运行 时成为项目类路径的一部分,您将能够使用 "images/logo.png"作为图像表达。

第三种解决方案是在 JasperReportsContext 实例中注册一个 FileRepositoryService 扩展,您将使用它来填写报告。文件存储库服务将使用当前项目根路径创建,您需要以某种方式从环境中确定该路径。拥有存储库服务还可以让您使用 "images/logo.png" 作为图像表达。代码看起来像这样:

SimpleJasperReportsContext context = new SimpleJasperReportsContext();
FileRepositoryService fileRepository = new FileRepositoryService(context, "D:/MyProgram/src/myprogram/", false);
context.setExtensions(RepositoryService.class, Collections.singletonList(fileRepository));
context.setExtensions(PersistenceServiceFactory.class, Collections.singletonList(FileRepositoryPersistenceServiceFactory.getInstance()));

JasperPrint jasperPrint = JasperFillManager.getInstance(context).fill(jasperReport, params);