how to display image in jasper reports

2020-04-19 05:00发布

问题:

I created a jasper report .but now I need to place logo in that jasper reports, I placed report and logo in same folder , but i am not able to run the report , its say

   net.sf.jasperreports.engine.JRException: Byte data not found at : kh_logo.jpg

if i am giving full path then jar file creates problem , then in jar file report is not able to find that logo image , i am using net beans please help

 I am using netbeans and i am placing report and logo in the src folder , but when I 
click on print report it is not able to find that logo

回答1:

Your image needs to be in a folder on your classpath and referenced in a relative manner.



回答2:

There are two possible solutions I've found to this problem:

Solution 1: Using relative paths.

Using an absolute path may not work in your server environment. Hence it will be better to use a relative path. It would be good to place the 'kh_logo.png' file in the same folder as the .jrmxl or .jasper file and reference it using something like this:

<image>
            <reportElement uuid="generated_uuid" x="8" y="9" width="170" height="51"/>
            <imageExpression><![CDATA["kh_logo.png"]]></imageExpression>
</image>

If that doesn't work.....

Solution 2: Using file resolver

This solution is only to be used in Java code. Here you pass your own file resolver to the report as a parameter. Like so..

 ///Jasper Resolver
       FileResolver fileResolver = new FileResolver() {

        @Override
        public File resolveFile(String fileName) {
           URI uri;
           try {
             uri = new URI(this.getClass().getResource(fileName).getPath());
             return new File(uri.getPath());
           } catch (URISyntaxException e) {
             e.printStackTrace();
             return null;
           }
       }
   };
       parameters.put("REPORT_FILE_RESOLVER", fileResolver);

Then you reference it as you'd do above.

Hope this helps someone.