How to show an image on jasper report?

user297339 picture user297339 · Apr 30, 2010 · Viewed 98.4k times · Source

I want to show an image on a jasper report. I have the following on the .jrxml:

<image>
  <reportElement x="181" y="0" width="209" height="74"/>
  <imageExpression class="java.lang.String"><![CDATA["logo.jpg"]]></imageExpression>
</image>

The image logo.jpg is in the same directory as the .jrxml. By just putting that it didn't work for me. I googled a bit and found out that jasper report considers what i put on the .jrxml as a relative path to the JVM directory and that to change this I need to pass as a "REPORT_FILE_RESOLVER" parameter a FileResolver that returns the file. So, I did the following in my .java (is located in same place as the .jrxml and the image)

FileResolver fileResolver = new FileResolver() {

 @Override
 public File resolveFile(String fileName) {
  return new File(fileName);
 }
};
HashMap<String, Object> parameters = new HashMap<String, Object>();

parameters.put("REPORT_FILE_RESOLVER", fileResolver);
...

Which should return the expected file, but I still get a

net.sf.jasperreports.engine.JRException: Error loading byte data : logo.jpg
    at net.sf.jasperreports.engine.util.JRLoader.loadBytes(JRLoader.java:301)
    at net.sf.jasperreports.engine.util.JRLoader.loadBytesFromLocation(JRLoader.java:479)
    at net.sf.jasperreports.engine.JRImageRenderer.getInstance(JRImageRenderer.java:180)
...

What am I doing wrong?

Thanks!

Answer

Bozho picture Bozho · Apr 30, 2010

I've made this work by passing a parameter specifying the absolute location of the file:

<imageExpression class="java.lang.String">
      <![CDATA[$P{REPORTS_DIR} + "/images/logo.jpg"]]>
</imageExpression>