Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
749 views
in Technique[技术] by (71.8m points)

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

I'm using JasperReports to create a report dynamically through Java. I have problem with the image expression (image path). This is the way I pass it now :

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

It works fine, but if I change the location of MyProgram I'll have to also change the path in the expression. I tried setting the expression to : ../images/logo.png but I got an error of "Byte data not found at : ../images/logo.png". Any help would be appreciated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There are several things that you could do.

One is to manually add a parameter called ProjectRoot in the report, use $P{ProjectRoot} + "images/logo.png" as image expression, and pass a value for ProjectRoot (taken from the environment) when you run the report.

Another approach is to leverage the fact that JasperReports also attempts to resolve image locations as classloader resources. Therefore if you add src/myprogram as a source folder so that images/logo.png gets to be part of your project's classpath at runtime, you'll be able to use "images/logo.png" as image expression.

A third solution is to register a FileRepositoryService extension in a JasperReportsContext instance that you would use for filling the report. The file repository service would be created with the current project root path, that you need to somehow determine from the environment. Having a repository service would also allow you to use "images/logo.png" as image expression. The code would look something like this:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...