1

I want to print a JasperReports's report via Java.

So I wrote a code as follows

 try {
            String r ="C:\\ireport\\Foods.jrxml";
            JasperReport jr =JasperCompileManager.compileReport(r);
            JasperPrint jp = JasperFillManager.fillReport(jr, null, conn);
            JasperViewer.viewReport(jp);
        } catch(Exception e) {
            System.out.println(e);
        }

But when I run the program I got following error.

net.sf.jasperreports.engine.JRException: Byte data not found at : flower1.png

I searched about this error in jasper community but I can't get understand the way they have explained the solution since I'm atotally newbie to the programming. So can anyone give me a solution please?

My jrxml had following code snippet

<imageExpression><![CDATA["flower1.png"]]></imageExpression>
Alex K
  • 22,315
  • 19
  • 108
  • 236
  • Please post you jrxml creating a [mcve], I bet it contains a flower1.png – Petter Friberg Apr 06 '16 at 19:37
  • @PetterFriberg Yep.You are correct.I found it.Now what should I do? –  Apr 06 '16 at 19:57
  • Alex has answered your question thoroughly use that method or pass an absolute path to jrxml (the absolute path is normally passed through parameter.). Furthermore consider to accept Alex answer, so future users can find it. – Petter Friberg Apr 07 '16 at 09:01

1 Answers1

3

The good way it to use report's parameter for passing the image. And I believe that passing image as BufferedImage object is a good choice in your case.

The sample of usage

The Java code snippet

Map<String, Object> parameters = new HashMap<>();
try (InputStream inputStream = YourClass.class.getClassLoader().getResourceAsStream("images/flower1.png")) {
    parameters.put("flowerImage", ImageIO.read(new ByteArrayInputStream(JRLoader.loadBytes(inputStream))));
} catch (JRException | IOException e) {
     throw new RuntimeException("Failed to load images", e);
}
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, connection);

The snippet of jrxml file

<parameter name="logoImage" class="java.awt.Image"/>
...
<image scaleImage="FillFrame">
    <reportElement x="10" y="0" width="224" height="43"/>
    <imageExpression><![CDATA[$P{flowerImage}]]></imageExpression>
</image>

  1. The more information about using images you can find here

  2. Info about reading resources with Java and where to store it:

  3. Info about how to read image with Java:

Community
  • 1
  • 1
Alex K
  • 22,315
  • 19
  • 108
  • 236