Hot questions for Using JasperReports in image

Question:

So in my jrxml file I have the following:

<parameter name="smileyfaceimage" class="java.lang.String"/>

Then I reference it in:

<image scaleImage="FillFrame" onErrorType="Blank">
    <reportElement x="167" y="62" width="363" height="171" backcolor="#333333"/>
    <imageExpression class="java.lang.String"><![CDATA[$P{smileyfaceimage}]]></imageExpression>
</image>

Is this not correct?

I've tried the base64 both with and without:

data:image/png;base64,

Here's the image im working with

Then I used https://www.base64-image.de/ or any random site to get the base64 string. I tested the string it produces and it's valid.

Now in my code;

  • set the value of a variable to the based64 string
  • on the template
    • set the parameter: <parameter name="smileyfaceimage" class="java.lang.String"/>
  • then add the image data to the page:

    • <image scaleImage="FillFrame" onErrorType="Blank">
          <reportElement x="167" y="62" width="363" height="171" backcolor="#333333"/>
          <imageExpression><![CDATA[new java.io.ByteArrayInputStream(org.apache.commons.codec.binary.Base64.decodeBase64($P{smileyfaceimage}.getBytes()))]]></imageExpression>
      </image>
      

Am I missing a step?


Answer:

Passing parameter as String makes jasper report believe its a absolute file path, so you need another class. The most obvious would be java.awt.Image or java.io.InputStream.

I choose java.io.InputStream since this will require less code, so the first thing we need to do now is to decode the base64 image String.

There are several Base64 class that will do the job, I choose the org.apache.commons.codec.binary.Base64 since apache commons-codec.jar is already distributed with jasper report (dependencies). The decode will give us a byte array byte[], so now we need only to add a ByteArrayInputStream

The java code would be:

InputStream stream = new ByteArrayInputStream(Base64.decodeBase64(smileyfaceimage.getBytes()));

Time to pass it into the jasper report imageExpression

<image scaleImage="FillFrame" onErrorType="Blank">
<reportElement x="167" y="62" width="363" height="171" backcolor="#333333"/>
    <imageExpression class="java.io.InputStream"><![CDATA[new java.io.ByteArrayInputStream(org.apache.commons.codec.binary.Base64.decodeBase64($P{smileyfaceimage}.getBytes()))]]></imageExpression>
</image>

Hope for the best and press the preview:

Important notice: The smileyfaceimage needs to be without:data:image/png;base64,

EDIT: The problem of the OP (comments) was that with old jasper report lib (3.0) you need to specify the class in the imageExpression @see class="java.io.InputStream" the post has been update consequently since this works also in 6.0.

Question:

I'm trying to wrap my text around an Image.

The structure I need to create is as in the picture bellow:

This is what I have tried

I have tried using table which did not succeed. I tough of using text field as html and passing image to it and set the alignment to left, but I found out that it is not possible to pass the image in text field. I started to solve the problem using jaspersoft Studio pro and with its html element. However I could not figure out how to pass the image field from data base as the html source. The expression in the html element is:

"<img src= '$F{Image}' align='left'/> <p>"+$F{KN_Zusatzinfo_DV_Einleitungstext} +"</p>"

This code does not show the image, but a box instead of the image. And the text which is printed is not stretched. The page style which I use is two column. The HTML out put is as in the picture

Using a static path like one bellow to an image works, but it is not an option for me since I need to read the Image from data base:

    "<style>.left { float: left;  margin-left: 1em; width :40%;}</style><p><img class = left src= C:/Users/iman/JaspersoftWorkspace/Qreport/sample1.png />

If I just use an Image Element with a text box under that the out put and design view are as these pictures:

The HTML source of the html approach is:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>

<head>
  <title></title>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
  <style type="text/css">
    a {
      text-decoration: none
    }
  </style>
</head>

<body text="#000000" link="#000000" alink="#000000" vlink="#000000">
  <table width="100%" cellpadding="0" cellspacing="0" border="0">
    <tr>
      <td width="50%">&nbsp;</td>
      <td align="center">

        <a name="JR_PAGE_ANCHOR_0_1"></a>
        <table class="jrPage" cellpadding="0" cellspacing="0" border="0" style="empty-cells: show; width: 595px; border-collapse: collapse; background-color: white;">
          <tr valign="top" style="height:0">
            <td style="width:10px"></td>
            <td style="width:20px"></td>
            <td style="width:40px"></td>
            <td style="width:210px"></td>
            <td style="width:32px"></td>
            <td style="width:58px"></td>
            <td style="width:10px"></td>
            <td style="width:182px"></td>
            <td style="width:9px"></td>
            <td style="width:24px"></td>
          </tr>
          <tr valign="top" style="height:25px">
            <td colspan="10">
            </td>
          </tr>
          <tr valign="top" style="height:5px">
            <td colspan="6">
            </td>
            <td colspan="3" rowspan="2" style="text-indent: 0px; text-align: right;">
              <span style="font-family: 'DejaVu Sans', Arial, Helvetica, sans-serif; color: #6B66FA; font-size: 10px; line-height: 1.2578125;">HCH-A - Aortenklappenchirurgie, isoliert (Konventionell chirurgisch)</span>
            </td>
            <td>
            </td>
          </tr>
          <tr valign="top" style="height:20px">
            <td>
            </td>
            <td colspan="2" style="text-indent: 0px; text-align: left;">
              <span style="font-family: 'DejaVu Sans', Arial, Helvetica, sans-serif; color: #BABABA; font-size: 10px; line-height: 1.2578125;">Ergebnisse</span>
            </td>
            <td colspan="3">
            </td>
            <td>
            </td>
          </tr>
          <tr valign="top" style="height:20px">
            <td colspan="7">
            </td>
            <td colspan="2" style="text-indent: 0px; text-align: right;">
              <span style="font-family: 'DejaVu Sans', Arial, Helvetica, sans-serif; color: #000000; font-size: 10px; line-height: 1.2578125;">Dr XYZ</span>
            </td>
            <td>
            </td>
          </tr>
          <tr valign="top" style="height:88px">
            <td colspan="10">
            </td>
          </tr>
          <tr valign="top" style="height:74px">
            <td colspan="5">
            </td>
            <td colspan="3" rowspan="2">
              <div style='width:250px;height:90px;background-color: #FFFFFF; overflow:hidden;'>
                <img src='((java.awt.Image)field_Image.getValue())' align='left' />
                <p>Bei der Aortenklappe handelt es sich um das „Ventil" zwischen der linken HerzkeAortenklappenchirurgie, isoliert - konventionell - Aortenklappenchirurgie, isoliert - kathetergestützt Die Qualitätsindikatoren der k........
                 appenchirauch die Indikationsstellung betrachtet. Sofern nicht anders angegeben, ist die Beschreibung der Qualitätsindikatoren eine Fortschreibung der QIDB 2014 des AQUA-Institutes.</p>
              </div>
            </td>
            <td colspan="2">
            </td>
          </tr>
          <tr valign="top" style="height:16px">
            <td colspan="2">
            </td>
            <td colspan="2" rowspan="2">
              <div style='width:250px;height:90px;background-color: #FFFFFF; overflow:hidden;'>
                <img src='((java.awt.Image)field_Image.getValue())' align='left' />
                <p>Bei der Aortenklappe handelt es sich um das „Ventil" zwischen der linken Herzkammer und der Hauptschlagader (Aorta). Schließt die Klappe nicht mehr dicht, spriitätsindikatoren der konventionellen Aortenklappenchirurgie fokussieren schwere Komplikationen und Sterblichkeit.
                  Bei der kathetergestützten Aortenklappenchirurgie wird darüber hinaus auch die Indikationsstellung betrachtet. Sofern nicht anders angegeben, ist die Beschreibung der Qualitätsindikatoren eine Fortschreibung der QIDB 2014 des AQUA-Institutes.</p>
              </div>
            </td>
            <td>
            </td>
            <td colspan="2">
            </td>
          </tr>
          <tr valign="top" style="height:74px">
            <td colspan="2">
            </td>
            <td colspan="6">
            </td>
          </tr>
          <tr valign="top" style="height:520px">
            <td colspan="10">
            </td>
          </tr>
        </table>
        <br/>
        <br/>

        <a name="JR_PAGE_ANCHOR_0_2"></a>
        <table class="jrPage" cellpadding="0" cellspacing="0" border="0" style="empty-cells: show; width: 595px; border-collapse: collapse; background-color: white;">
          <tr valign="top" style="height:0">
            <td style="width:10px"></td>
            ...
            <td style="width:24px"></td>
          </tr>
          <tr valign="top" style="height:27px">
            <td colspan="7">
            </td>
          </tr>
          <tr valign="top" style="height:20px">
            <td>
            </td>
            <td colspan="2" style="text-indent: 0px; text-align: left;">
              <span style="font-family: 'DejaVu Sans', Arial, Helvetica, sans-serif; color: #BABABA; font-size: 10px; line-height: 1.2578125;">Ergebnisse</span>
            </td>
            <td colspan="4">
            </td>
          </tr>
          <tr valign="top" style="height:7px">
            <td colspan="7">
            </td>
          </tr>
          <tr valign="top" style="height:21px">
            <td colspan="5">
            </td>
            <td style="text-indent: 0px; text-align: right;">
              <span style="font-family: 'DejaVu Sans', Arial, Helvetica, sans-serif; color: #6B66FA; font-size: 10px; line-height: 1.2578125;">HCH-A - Aortenklappenchirurgie, isoliert </span>
            </td>
            <td>
            </td>
          </tr>
          <tr valign="top" style="height:125px">
            <td colspan="7">
            </td>
          </tr>
          <tr valign="top" style="height:90px">
            <td colspan="2">
            </td>
            <td colspan="2">
              <div style='width:250px;height:90px;background-color: #FFFFFF; overflow:hidden;'>
                <img src='((java.awt.Image)field_Image.getValue())' align='left' />
                <p>....deleted some text because it exceeded the limit..</p>
              </div>
            </td>
            <td colspan="3">
            </td>
          </tr>
          <tr valign="top" style="height:552px">
            <td colspan="7">
            </td>
          </tr>
        </table>
        <br/>
        <br/>

        <a name="JR_PAGE_ANCHOR_0_3"></a>
        <table class="jrPage" cellpadding="0" cellspacing="0" border="0" style="empty-cells: show; width: 595px; border-collapse: collapse; background-color: white;">
          <tr valign="top" style="height:0">
            <td style="width:595px"></td>
          </tr>
          <tr valign="top" style="height:842px">
            <td>
            </td>
          </tr>
        </table>

        <![if IE]>
        <script>
          var links = document.querySelectorAll('link.jrWebFont');
          setTimeout(function() {
            if (links) {
              for (var i = 0; i < links.length; i++) {
                links.item(i).href = links.item(i).href;
              }
            }
          }, 0);
        </script>
        <![endif]>
      </td>
      <td width="50%">&nbsp;</td>
    </tr>
  </table>
</body>
</html>

And the HTML source of the Image element plus text field is:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>

<head>
  <title></title>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
  <style type="text/css">
    a {
      text-decoration: none
    }
  </style>
</head>

<body text="#000000" link="#000000" alink="#000000" vlink="#000000">
  <table width="100%" cellpadding="0" cellspacing="0" border="0">
    <tr>
      <td width="50%">&nbsp;</td>
      <td align="center">

        <a name="JR_PAGE_ANCHOR_0_1"></a>
        <table class="jrPage" cellpadding="0" cellspacing="0" border="0" style="empty-cells: show; width: 595px; border-collapse: collapse; background-color: white;">
          <tr valign="top" style="height:0">
            <td style="width:10px"></td>
            <td style="width:60px"></td>
            <td style="width:232px"></td>
            <td style="width:33px"></td>
            <td style="width:35px"></td>
            <td style="width:10px"></td>
            <td style="width:5px"></td>
            <td style="width:186px"></td>
            <td style="width:1px"></td>
            <td style="width:23px"></td>
          </tr>
          <tr valign="top" style="height:25px">
            <td colspan="10">
            </td>
          </tr>
          <tr valign="top" style="height:5px">
            <td colspan="5">
            </td>
            <td colspan="3" rowspan="2" style="text-indent: 0px; text-align: right;">
              <span style="font-family: 'DejaVu Sans', Arial, Helvetica, sans-serif; color: #6B66FA; font-size: 10px; line-height: 1.2578125;">HCH-A - Aortenklappenchirurgie, isoliert (Konventionell chirurgisch)</span>
            </td>
            <td colspan="2">
            </td>
          </tr>
          <tr valign="top" style="height:20px">
            <td>
            </td>
            <td style="text-indent: 0px; text-align: left;">
              <span style="font-family: 'DejaVu Sans', Arial, Helvetica, sans-serif; color: #BABABA; font-size: 10px; line-height: 1.2578125;">Ergebnisse</span>
            </td>
            <td colspan="3">
            </td>
            <td colspan="2">
            </td>
          </tr>
          <tr valign="top" style="height:20px">
            <td colspan="6">
            </td>
            <td colspan="2" style="text-indent: 0px; text-align: right;">
              <span style="font-family: 'DejaVu Sans', Arial, Helvetica, sans-serif; color: #000000; font-size: 10px; line-height: 1.2578125;">Dr XYZ</span>
            </td>
            <td colspan="2">
            </td>
          </tr>
          <tr valign="top" style="height:94px">
            <td colspan="10">
            </td>
          </tr>
          <tr valign="top" style="height:50px">
            <td colspan="4">
            </td>
            <td colspan="3">
              <img src="report7921484792758494686.html_files/img_0_0_3" style="width: 50px" alt="" />
            </td>
            <td colspan="3">
            </td>
          </tr>
          <tr valign="top" style="height:24px">
            <td colspan="10">
            </td>
          </tr>
          <tr valign="top" style="height:477px">
            <td colspan="3">
            </td>
            <td colspan="6" style="text-indent: 0px; text-align: left;">
              <span style="font-family: 'DejaVu Sans', Arial, Helvetica, sans-serif; color: #000000; font-size: 10px; line-height: 1.2578125;">Bei der Aortenklappe handelt es sinken Herzkammer und der Hauptschlagader (Aorta). Einsatz einer künstlichen Herzklappe behandelt.<br/><br/>Bei beiden kathetergestützten Methoden wird über ein spezielles Ballonkathetersystem zunächst der Bereich der </span>
            </td>
            <td>
            </td>
          </tr>
          <tr valign="top" style="height:127px">
            <td colspan="10">
            </td>
          </tr>
        </table>
        <br/>
        <br/>

        <a name="JR_PAGE_ANCHOR_0_2"></a>
        <table class="jrPage" cellpadding="0" cellspacing="0" border="0" style="empty-cells: show; width: 595px; border-collapse: collapse; background-color: white;">
          <tr valign="top" style="height:0">
            <td style="width:10px"></td>
            ...
            <td style="width:24px"></td>
          </tr>
          <tr valign="top" style="height:27px">
            <td colspan="7">
            </td>
          </tr>
          <tr valign="top" style="height:20px">
            <td>
            </td>
            <td colspan="2" style="text-indent: 0px; text-align: left;">
              <span style="font-family: 'DejaVu Sans', Arial, Helvetica, sans-serif; color: #BABABA; font-size: 10px; line-height: 1.2578125;">Ergebnisse</span>
            </td>
            <td colspan="4">
            </td>
          </tr>
          <tr valign="top" style="height:7px">
            <td colspan="7">
            </td>
          </tr>
          <tr valign="top" style="height:21px">
            <td colspan="5">
            </td>
            <td style="text-indent: 0px; text-align: right;">
              <span style="font-family: 'DejaVu Sans', Arial, Helvetica, sans-serif; color: #6B66FA; font-size: 10px; line-height: 1.2578125;">HCH-A - Aortenklappenchirurgie, isoliert </span>
            </td>
            <td>
            </td>
          </tr>
          <tr valign="top" style="height:139px">
            <td colspan="7">
            </td>
          </tr>
          <tr valign="top" style="height:264px">
            <td colspan="2">
            </td>
            <td colspan="2" style="text-indent: 0px; text-align: left;">
              <span style="font-family: 'DejaVu Sans', Arial, Helvetica, sans-serif; color: #000000; font-size: 10px; line-height: 1.2578125;">alten, verengten Aortenklappe erweitert. -  des AQUA-Institutes.</span>
            </td>
            <td colspan="3">
            </td>
          </tr>
          <tr valign="top" style="height:364px">
            <td colspan="7">
            </td>
          </tr>
        </table>
        <br/>
        <br/>

        <a name="JR_PAGE_ANCHOR_0_3"></a>
        <table class="jrPage" cellpadding="0" cellspacing="0" border="0" style="empty-cells: show; width: 595px; border-collapse: collapse; background-color: white;">
          <tr valign="top" style="height:0">
            <td style="width:10px"></td>
            <td style="width:10px"></td>
           ...
            <td style="width:1px"></td>
            <td style="width:23px"></td>
          </tr>
          <tr valign="top" style="height:27px">
            <td colspan="11">
            </td>
          </tr>
          <tr valign="top" style="height:20px">
            <td>
            </td>
            <td colspan="3" style="text-indent: 0px; text-align: left;">
              <span style="font-family: 'DejaVu Sans', Arial, Helvetica, sans-serif; color: #BABABA; font-size: 10px; line-height: 1.2578125;">Ergebnisse</span>
            </td>
            <td colspan="7">
            </td>
          </tr>
          <tr valign="top" style="height:7px">
            <td colspan="11">
            </td>
          </tr>
          <tr valign="top" style="height:21px">
            <td colspan="8">
            </td>
            <td style="text-indent: 0px; text-align: right;">
              <span style="font-family: 'DejaVu Sans', Arial, Helvetica, sans-serif; color: #6B66FA; font-size: 10px; line-height: 1.2578125;">HCH-A - Aortenklappenchirurgie, isoliert </span>
            </td>
            <td colspan="2">
            </td>
          </tr>
          <tr valign="top" style="height:65px">
            <td colspan="11">
            </td>
          </tr>
          <tr valign="top" style="height:66px">
            <td colspan="7">
            </td>
            <td colspan="3" rowspan="4" style="text-indent: 0px; text-align: left;">
              <span style="font-family: 'DejaVu Sans', Arial, Helvetica, sans-serif; color: #000000; font-size: 10px; line-height: 1.2578125;"><br/>Bei beiden kathetergestützten Me die Indikationsstellung betrachtet.<br/><br/>Sofern nicht anders angegeben, ist die Beschreibung der Qualitätsindikatoren eine Fortschreibung der QIDB 2014 des AQUA-Institutes.</span>
            </td>
            <td>
            </td>
          </tr>
          <tr valign="top" style="height:50px">
            <td colspan="3">
            </td>
            <td colspan="2">
              <img src="report7921484792758494686.html_files/img_0_2_2" style="width: 50px" alt="" />
            </td>
            <td colspan="2">
            </td>
            <td>
            </td>
          </tr>
          <tr valign="top" style="height:24px">
            <td colspan="7">
            </td>
            <td>
            </td>
          </tr>
          <tr valign="top" style="height:161px">
            <td colspan="2">
            </td>
            <td colspan="4" rowspan="2" style="text-indent: 0px; text-align: left;">
              <span style="font-family: 'DejaVu Sans', Arial, Helvetica, sans-serif; color: #000000; font-size: 10px; line-height: 1.2578125;">Bei der Aortenklapprzspitze über einen 3 bis 5 cm langen Hautschnitt im Rippenbereich (linker Brustkorb, im 4. oder 5. Rippenzwischenraum) freigelegt. <br/>- Beim endovaskulären Aortenklappenersatz ist lediglich ein gezielter Einstich (Punktion), zumeist in die Leistenarterie, notwendig. <br/></span>
            </td>
            <td>
            </td>
            <td>
            </td>
          </tr>
          <tr valign="top" style="height:279px">
            <td colspan="2">
            </td>
            <td colspan="5">
            </td>
          </tr>
          <tr valign="top" style="height:122px">
            <td colspan="11">
            </td>
          </tr>
        </table>
        <br/>
        <br/>

        <a name="JR_PAGE_ANCHOR_0_4"></a>
        <table class="jrPage" cellpadding="0" cellspacing="0" border="0" style="empty-cells: show; width: 595px; border-collapse: collapse; background-color: white;">
          <tr valign="top" style="height:0">
            <td style="width:10px"></td>
            <td style="width:60px"></td>
           ...
            <td style="width:1px"></td>
            <td style="width:23px"></td>
          </tr>
          <tr valign="top" style="height:27px">
            <td colspan="9">
            </td>
          </tr>
          <tr valign="top" style="height:20px">
            <td>
            </td>
            <td style="text-indent: 0px; text-align: left;">
              <span style="font-family: 'DejaVu Sans', Arial, Helvetica, sans-serif; color: #BABABA; font-size: 10px; line-height: 1.2578125;">Ergebnisse</span>
            </td>
            <td colspan="7">
            </td>
          </tr>
          <tr valign="top" style="height:7px">
            <td colspan="9">
            </td>
          </tr>
          <tr valign="top" style="height:21px">
            <td colspan="5">
            </td>
            <td colspan="2" style="text-indent: 0px; text-align: right;">
              <span style="font-family: 'DejaVu Sans', Arial, Helvetica, sans-serif; color: #6B66FA; font-size: 10px; line-height: 1.2578125;">HCH-A - Aortenklappenchirurgie, isoliert </span>
            </td>
            <td colspan="2">
            </td>
          </tr>
          <tr valign="top" style="height:91px">
            <td colspan="9">
            </td>
          </tr>
          <tr valign="top" style="height:50px">
            <td colspan="4">
            </td>
            <td colspan="2">
              <img src="report7921484792758494686.html_files/img_0_3_2" style="width: 50px" alt="" />
            </td>
            <td colspan="3">
            </td>
          </tr>
          <tr valign="top" style="height:24px">
            <td colspan="9">
            </td>
          </tr>
          <tr valign="top" style="height:477px">
            <td colspan="3">
            </td>
            <td colspan="5" style="text-indent: 0px; text-align: left;">
              <span style="font-family: 'DejaVu Sans', Arial, Helvetica, sans-serif;r Brustkorb, im 4. oder 5. Rippenzwischenraum) freigelegt. <br/>- Beim endovaskulären Aortenklappenersatz ist lediglich ein gezielter Einstich (Punktion), zumeist in die Leistenarterie, notwendig. <br/><br/>Bei beiden kathetergestützten Methoden wird über ein spezielles Ballonkathetersystem zunächst der Bereich der </span>
            </td>
            <td>
            </td>
          </tr>
          <tr valign="top" style="height:125px">
            <td colspan="9">
            </td>
          </tr>
        </table>
        <br/>
        <br/>

        <a name="JR_PAGE_ANCHOR_0_5"></a>
        <table class="jrPage" cellpadding="0" cellspacing="0" border="0" style="empty-cells: show; width: 595px; border-collapse: collapse; background-color: white;">
          <tr valign="top" style="height:0">
            <td style="width:10px"></td>
            <td style="width:10px"></td>
            <td style="width:50px"></td>
            <td style="width:220px"></td>
            <td style="width:80px"></td>
            <td style="width:201px"></td>
            <td style="width:24px"></td>
          </tr>
          <tr valign="top" style="height:27px">
            <td colspan="7">
            </td>
          </tr>
          <tr valign="top" style="height:20px">
            <td>
            </td>
            <td colspan="2" style="text-indent: 0px; text-align: left;">
              <span style="font-family: 'DejaVu Sans', Arial, Helvetica, sans-serif; color: #BABABA; font-size: 10px; line-height: 1.2578125;">Ergebnisse</span>
            </td>
            <td colspan="4">
            </td>
          </tr>
          <tr valign="top" style="height:7px">
            <td colspan="7">
            </td>
          </tr>
          <tr valign="top" style="height:21px">
            <td colspan="5">
            </td>
            <td style="text-indent: 0px; text-align: right;">
              <span style="font-family: 'DejaVu Sans', Arial, Helvetica, sans-serif; color: #6B66FA; font-size: 10px; line-height: 1.2578125;">HCH-A - Aortenklappenchirurgie, isoliert </span>
            </td>
            <td>
            </td>
          </tr>
          <tr valign="top" style="height:139px">
            <td colspan="7">
            </td>
          </tr>
          <tr valign="top" style="height:264px">
            <td colspan="2">
            </td>
            <td colspan="2" style="text-indent: 0px; text-align: left;">
              <span style="font-family: 'DejaVu Sans', Arial, Helvetica, sans-serif; color: #000000; font-size: 10px; line-height: 1.2578125;">alten, verengten Aortenklappe erweitert. Anschließend wird eine zusammengefaltete Herzklappenchirurgie fokussieren schwere Komplikationen und Sterblichkeit. Bei der kathetergestützten Aortenklappenchirurgie wird darüber hinaus auch die Indikationsstellung betrachtet.<br/><br/>Sofern nicht anders angegeben, ist die Beschreibung der Qualitätsindikatoren des AQUA-Institutes.</span>
            </td>
            <td colspan="3">
            </td>
          </tr>
          <tr valign="top" style="height:364px">
            <td colspan="7">
            </td>
          </tr>
        </table>
        <br/>
        <br/>

        <a name="JR_PAGE_ANCHOR_0_6"></a>
        <table class="jrPage" cellpadding="0" cellspacing="0" border="0" style="empty-cells: show; width: 595px; border-collapse: collapse; background-color: white;">
          <tr valign="top" style="height:0">
            <td style="width:595px"></td>
          </tr>
          <tr valign="top" style="height:842px">
            <td>
            </td>
          </tr>
        </table>

        <![if IE]>
        <script>
          var links = document.querySelectorAll('link.jrWebFont');
          setTimeout(function() {
            if (links) {
              for (var i = 0; i < links.length; i++) {
                links.item(i).href = links.item(i).href;
              }
            }
          }, 0);
        </script>
        <![endif]>
      </td>
      <td width="50%">&nbsp;</td>
    </tr>
  </table>
</body>

</html>

How can I achieve this structure?


Answer:

If you use the html component to wrap text around image, not only do you have a problem of pulling the image from the database, the html component also creates an image of the html, hence the content may be resized/clipped depending on text length and settings on html (image) component.

I would suggest to use two textFields wrapped around the image (see jrxml) and then calculate where the text will break into next field, so you get first part of text in first textField and second part in second textField

Java code to calculate text's break point

This code demonstrate how you can use FontMetric to calculate where Jasper Report will break the text depending on the size of your textField (explanation of code is in comments). The code is not perfectly safe on NullPointer (null text) and on non over-flowing text, furthermore it can be optimized but I will leave this to OP

import java.awt.Font;
import java.awt.font.FontRenderContext;
import java.awt.geom.AffineTransform;

public class WrapImage {

    /**
     * Get position where string will break
     * @param text, the text
     * @param width, the width of the component
     * @param height, the height of the component
     * @return the position
     */
    public static int getBreakPosition(String text, int width, int height){
        //Start font context
        AffineTransform affinetransform = new AffineTransform();     
        FontRenderContext frc = new FontRenderContext(affinetransform,true,true);     

        //Set same font as used in jasper-report
        Font font = new Font("SansSerif", Font.PLAIN, 10);
        //Get height to understand how many lines
        double textheight = font.getStringBounds(text, frc).getHeight();
        int nrLines = (int)Math.floor(height/textheight);

        //init variables
        int breakPos = 0;
        int line = 1;

        //loop the lines
        while (line<=nrLines){
            //get remaining text
            String textPart = text.substring(breakPos,text.length());
            //get how much text will fit in line
            breakPos += getLineBreakPosition(textPart, width, font, frc)+1;
            line++;
        }

        return breakPos;

    }

    /**
     * Get where a single line will break
     * @param text, the text
     * @param width, width of component
     * @param font, the font used
     * @param frc, the FontRenderContext
     * @return
     */
    protected static int getLineBreakPosition(String text, int width, Font font, FontRenderContext frc){
        int breakPos  = 0;
        String tmpText = text;
        while (font.getStringBounds(tmpText, frc).getWidth()>width){
            //the break position is space
            breakPos = tmpText.lastIndexOf(' ');
            if (breakPos<=0){
                breakPos = 0;
                break;
            }
            tmpText = tmpText.substring(0,breakPos);
        }
        return breakPos;
    }
}
jrxml example using java code

In this short example, I use a parameter with some arbitrary sample text. The WrapImage class is in class path. I set a variable to the calculated break point. Then use substring on the text to get first part in first textfield, second in second textField To simplify example, I'm using an image from desktop, for how to pull image from database see: Using images stored in database

<?xml version="1.0" encoding="UTF-8"?>
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="wrappingText" pageWidth="595" pageHeight="842" whenNoDataType="AllSectionsNoDetail" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" isSummaryWithPageHeaderAndFooter="true" uuid="cd3e4316-a3c4-4847-a085-3bfa1d9425af">
    <parameter name="longText" class="java.lang.String">
        <defaultValueExpression><![CDATA["Whether you've come to ask questions, or to generously share what you know, remember that we’re all here to learn, together. Be welcoming and patient, especially with those who may not know everything you do. Oh, and bring your sense of humor. Just in case. That basically covers it. But these three guidelines may help: Rudeness and belittling language are not okay. Your tone should match the way you'd talk in person with someone you respect and whom you want to respect you. If you don't have time to say something politely, just leave it for someone who does. Be welcoming, be patient, and assume good intentions. Don't expect new users to know all the rules — they don't. And be patient while they learn. If you're here for help, make it as easy as possible for others to help you. Everyone here is volunteering, and no one responds well to demands for help. Don't be a jerk. These are just a few examples. If you see them, flag them. In summary, have fun, and be good to each other."]]></defaultValueExpression>
    </parameter>
    <variable name="breakPos" class="java.lang.Integer">
        <initialValueExpression><![CDATA[WrapImage.getBreakPosition($P{longText}, 250, 100)]]></initialValueExpression>
    </variable>
    <title>
        <band height="220" splitType="Stretch">
            <image>
                <reportElement x="10" y="20" width="80" height="80" uuid="6b4bb467-f7fd-4a15-994b-7c1a01b86428"/>
                <imageExpression><![CDATA["C:\\Users\\pette\\Desktop\\queen_bee.jpg"]]></imageExpression>
            </image>
            <textField>
                <reportElement x="100" y="0" width="250" height="100" uuid="f4507624-0410-4feb-9dc5-7d3342b882f0"/>
                <textElement textAlignment="Justified" verticalAlignment="Bottom"/>
                <textFieldExpression><![CDATA[$P{longText}.substring(0,$V{breakPos}.intValue())]]></textFieldExpression>
            </textField>
            <textField>
                <reportElement x="0" y="100" width="350" height="120" uuid="8790bbdd-2066-4ceb-9fc9-dad6154df88c"/>
                <textElement textAlignment="Justified"/>
                <textFieldExpression><![CDATA[$P{longText}.substring($V{breakPos}.intValue()+1)]]></textFieldExpression>
            </textField>
        </band>
    </title>
</jasperReport>
Output example

Question:

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.


Answer:

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

Question:

I searched a bit, and found a very similar question that unfortunatly doesn't solve my problem.

The similar question : here

I'm using Jaspert Report 6.6.0 and Java 1.8.

My goal is to insert an image in the report, I can't change much of java code, and the image is stored as byte[].

So, I tried this :

<field name="logo" class="java.io.InputStream"/>
// ... other stuff that is displayed properly
<image scaleImage="FillFrame" onErrorType="Blank">
    <reportElement style="Column header" x="0" y="-1" width="80" height="75" backcolor="#333333" uuid="80bcba32-4e50-4a3a-949c-39e7c22ddff4"/>
    <imageExpression><![CDATA[new java.io.ByteArrayInputStream(org.apache.commons.codec.binary.Base64.decodeBase64($P{logo}.getBytes()))]]></imageExpression>
</image>

With this Java code :

//a big bunch of fileds that I managed to display properly

private InputStream logo;

public Constructor(some, stuff, imageAsByteArray) {
    // setting lots of things that are displayed properly

    this.setLogo(new ByteArrayInputStream(Base64.decodeBase64(imageAsByteArray)));
}

But, in Jasper Studio, when I try to save my jrxml file, I have this error :

The method getBytes() is undefined for the type InputStream value = new java.io.ByteArrayInputStream(org.apache.commons.codec.binary.Base

I'm not very familiar with Jasper, and I tried few different ways to insert the image, but the closest thing I found is the link I gave above. I understood that I can't set class="java.io.InputStream" anymore in , is it the problem ?

Anyone would know what I missed here ?


Answer:

Ok, solution was actually very simple, thanks to @dada67.

First, I confused $P and $F, as I was using a Field, I had to use $F.

Then, decoding base64 was a mistake, I didn't need it. To sum it up, right code should be :

<field name="logo" class="java.io.InputStream"/>
// ... other stuff that is displayed properly
<image scaleImage="FillFrame" onErrorType="Blank">
    <reportElement style="Column header" x="0" y="-1" width="80" height="75" backcolor="#333333" uuid="80bcba32-4e50-4a3a-949c-39e7c22ddff4"/>
    <imageExpression><![CDATA[$F{logo}]]></imageExpression>
</image>

And :

//a big bunch of fileds that I managed to display properly

private InputStream logo;

public Constructor(some, stuff, imageAsByteArray) {
    // setting lots of things that are displayed properly

    this.setLogo(new ByteArrayInputStream(imageAsByteArray));
}

P.S : I'll remove this post if @dada67 wants to post his answer, since all credits are his.

Question:

I have a unique case where I have a Logo on the PageHeader Band of Jasper and I was expecting that since it is on the Page header, it should be printed on every page but it is getting printed only on the first Page. Same Jrxml is generating logo on all pages if I run it from ireport designer, but on my Java application, it is generating the logo only on the first page. Is there anything I am doing wrong?

My Java method:

public void formatreport(String foracid, String reportDir, String fromdate, String todate, String currdate, int pid, String suffix) {
        Connection conn = null;
        try {
            conn = db.prepareConn();
            Map parameters = new HashMap();
            ClassLoader classLoader = getClass().getClassLoader();
            InputStream logourl = classLoader.getResourceAsStream("/com/sim/bulk/jrxml/logo.jpg");
            parameters.put("account", foracid);
            parameters.put("from_date", fromdate);
            parameters.put("to_date", todate);
            parameters.put("period_id", pid);
            parameters.put("suffix", suffix);
            parameters.put("logo", logourl);
            log.debug("Bulk statement Parameters: account:" + foracid + "\nfrom_date:" + fromdate + "\nto_date:" + todate + "\nperiod_id:" + pid);
            InputStream url = classLoader.getResourceAsStream("com/sim/bulk/jrxml/Bulkstatement.jrxml");
            JasperReport jasperReport = JasperCompileManager.compileReport(url);
            JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, conn);
            reportDestination = reportDir + "/Statement_" + foracid + "_" + currdate + ".pdf";
            JasperExportManager.exportReportToPdfFile(jasperPrint, reportDestination);
        } catch (JRException asd) {

            log.fatal(asd.getMessage());

        } finally {
            try {
                if (conn != null) {
                    conn.close();
                }
            } catch (SQLException asd) {

                System.out.println(asd.getMessage());

            }
        }
    }

and the extract from the jrxml:

<pageHeader>
        <band height="162" splitType="Stretch">     
            <image onErrorType="Blank" evaluationTime="Now">
                <reportElement uuid="a49076f0-b945-4742-bb15-737b2a927da2" x="12" y="12" width="74" height="50"/>
                <imageExpression><![CDATA[$P{logo}]]></imageExpression>
            </image>
        </band>
    </pageHeader>

Answer:

Set isUsingCache="true" for the image. Otherwise the image would try to read the data from the input stream several times, which doesn't work.

Alternatively you can directly use the resource path ("/com/sim/bulk/jrxml/logo.jpg") as image expression, in most cases JasperReports would be able to load it from the classloader.

Question:

I'm using JasperSoft Studio 6.8.0 and I've a struggling error:

I've a logo property of my Java class EnvParameter.

this property is a byte[]

I pass my Java class to Jasper Studio, so I try to load the image inside logo property as follow:

net.sf.jasperreports.engine.util.JRImageLoader.loadAwtImageFromBytes($P{EnvParameter}.logo)

EDIT

I've also tried with

net.sf.jasperreports.engine.util.JRImageLoader.loadAwtImageFromBytes($P{EnvParameter}.getLogo())

But I have this error at runtime (compile it's OK):

net.sf.jasperreports.engine.fill.JRExpressionEvalException: Error evaluating expression for source text: net.sf.jasperreports.engine.util.JRImageLoader.loadAwtImageFromBytes($P{EnvParameter}.logo) at net.sf.jasperreports.engine.fill.JREvaluator.handleEvaluationException(JREvaluator.java:284) at net.sf.jasperreports.compilers.GroovyEvaluator.handleEvaluationException(GroovyEvaluator.java:98) at net.sf.jasperreports.engine.fill.JREvaluator.evaluate(JREvaluator.java:316) at net.sf.jasperreports.engine.fill.JRCalculator.evaluate(JRCalculator.java:672) at net.sf.jasperreports.engine.fill.JRCalculator.evaluate(JRCalculator.java:640) at net.sf.jasperreports.engine.fill.JRFillElement.evaluateExpression(JRFillElement.java:1169) at net.sf.jasperreports.engine.fill.JRFillImage.evaluateImage(JRFillImage.java:466) at net.sf.jasperreports.engine.fill.JRFillImage.evaluate(JRFillImage.java:440) at net.sf.jasperreports.engine.fill.JRFillElementContainer.evaluate(JRFillElementContainer.java:383) at net.sf.jasperreports.engine.fill.JRFillBand.evaluate(JRFillBand.java:548) at net.sf.jasperreports.engine.fill.JRVerticalFiller.fillTitle(JRVerticalFiller.java:323) at net.sf.jasperreports.engine.fill.JRVerticalFiller.fillReport(JRVerticalFiller.java:150) at net.sf.jasperreports.engine.fill.JRBaseFiller.fill(JRBaseFiller.java:615) at net.sf.jasperreports.engine.fill.BaseReportFiller.fill(BaseReportFiller.java:414) at net.sf.jasperreports.engine.fill.JRFillSubreport.fillSubreport(JRFillSubreport.java:814) at net.sf.jasperreports.engine.fill.JRSubreportRunnable.run(JRSubreportRunnable.java:61) at net.sf.jasperreports.engine.fill.AbstractThreadSubreportRunner.run(AbstractThreadSubreportRunner.java:221) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) at java.lang.Thread.run(Thread.java:745) Caused by: groovy.lang.MissingMethodException: No signature of method: static net.sf.jasperreports.engine.util.JRImageLoader.loadAwtImageFromBytes() is applicable for argument types: ([B) values: [[-119, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13, 73, 72, 68, ...]] Possible solutions: loadAwtImageFromBytes([B) at groovy.lang.MetaClassImpl.invokeStaticMissingMethod(MetaClassImpl.java:1518) at groovy.lang.MetaClassImpl.invokeStaticMethod(MetaClassImpl.java:1504) at org.codehaus.groovy.runtime.callsite.StaticMetaClassSite.call(StaticMetaClassSite.java:52) at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:47) at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:116) at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:128) at rptVTitolo_1558437271760_434544.evaluate(calculator_rptVTitolo_1558437271760_434544:203) at net.sf.jasperreports.engine.fill.JREvaluator.evaluate(JREvaluator.java:302) ... 17 common frames omitted mag 21, 2019 1:17:36 PM org.apache.catalina.core.StandardWrapperValve invoke


Answer:

What is wrong?

Looks like you are using wrong method for loading image. The class JRImageLoader was changed during moving to 6.x version of engine and there is no static method loadAwtImageFromBytes(bytep[]) at this class at new versions of JasperReports (I believe that it was there at JR 5.5.0).

Working example

You can try this small example.

Small Bean for testing:

package ru.alex.model;

public class MyBean {

    private byte[] logo;

    public byte[] getLogo() {
        return logo;
    }

    public void setLogo(byte[] logo) {
        this.logo = logo;
    }
}

The template (jrxml file) is very simple (I'm using JasperReports 6.4):

<?xml version="1.0" encoding="UTF-8"?>
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="ImageExample" pageWidth="612" pageHeight="792" whenNoDataType="AllSectionsNoDetail" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20">
    <parameter name="mybean" class="ru.alex.model.MyBean" isForPrompting="false"/>
    <title>
        <band height="72">
            <image>
                <reportElement x="200" y="10" width="50" height="50"/>
                <imageExpression><![CDATA[net.sf.jasperreports.engine.util.JRImageLoader.getInstance(DefaultJasperReportsContext.getInstance()).loadAwtImageFromBytes($P{mybean}.getLogo())]]></imageExpression>
            </image>
        </band>
    </title>
</jasperReport>

I used JRImageLoader.loadAwtImageFromBytes(byte[]) method for loading image from bytes array. As you can see we need to get instance of JRImageLoader first - I used default context using this code: JRImageLoader.getInstance(DefaultJasperReportsContext.getInstance()).

The code for generating report is simple as usual:

JasperReport jasperReport;
try (InputStream inputStream = JRLoader.getResourceInputStream("image.jrxml")) {
    jasperReport = JasperCompileManager.compileReport(JRXmlLoader.load(inputStream));
}
Map<String, Object> params = new HashMap<>();
MyBean myBean = new MyBean();

File file = new File(getClass().getClassLoader().getResource("smile.jpg").getFile());
myBean.setLogo(Files.readAllBytes(file.toPath()));

params.put("mybean", myBean);
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, params, new JREmptyDataSource());

SimplePdfExporterConfiguration configuration = new SimplePdfExporterConfiguration();
File outputFile = new File("output.pdf");
try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
     OutputStream fileOutputStream = new FileOutputStream(outputFile)) {
    JRPdfExporter exporter = new JRPdfExporter();
    exporter.setExporterInput(new SimpleExporterInput(jasperPrint));
    exporter.setExporterOutput(new SimpleOutputStreamExporterOutput(byteArrayOutputStream));
    exporter.setConfiguration(configuration);
    exporter.exportReport();
    byteArrayOutputStream.writeTo(fileOutputStream);
}

The generated report looks like:

Question:

I'm working on a shop management software, I got the db and everything set up, but when I want to generate pics for the reports. simple pics, just company logo.

But I want the pic to be stored on DB.

this is how you can manually set a pic. But how can I get it from the db?

pic 1

The reason why I want it from DB is because the user will use the same software in different shops, and I dont want him to generate a new jasper report file just to change the logo.


Answer:

Save it on db as blob and retrieve the image from db as imgStream

Question:

I am working on a spring-mvc project and I am using JasperReports for reporting purposes. I have a link that generates a report in pdf format. Link is working fine and report is generated, but the problem is pdf report is not displaying the image. Snippet from my jrxml file:

<frame>
    <reportElement x="0" y="0" width="70" height="67" uuid="0af2e978-7c0c-4805-afb4-4069d1297a12"/>
    <image onErrorType="Blank" evaluationTime="Report">
        <reportElement mode="Opaque" x="0" y="0" width="70" height="67" uuid="c572c836-8d67-480a-b1b1-d603940e6c74"/>
        <imageExpression><![CDATA["images/geLogo.jpg"]]></imageExpression>
    </image>
</frame>

I checked again and the image is present in my webapp/images folder in my project. I have used this same image in my jsp page, it is working. Code used to generate the pdf from JasperReport:

try {
        JasperPrint print = service.loadReceipt(RECEIPT_NAME, paymentId);
        pdfFile = JasperExportManager.exportReportToPdf(print);
        OutputStream outStream = res.getOutputStream();
        res.setContentType("application/pdf");
        res.addHeader("Content-disposition", "inline; filename=Receipt.pdf");
        outStream.write(pdfFile);
        outStream.flush();
        outStream.close();
    } 

Can you tell me why image is not coming in the pdf, though the displays the image in JasperReport Designer with the same path. I have used JasperReports plugin in my eclipse to design reports. I deploy the project in jboss 6.4 through war file. Thank you in advance. -------UPDATE-------- I got the idea of checking the structure of project inside war from @KDavid-Valerio answer. It is different from the actual project structure. war structure looks something like this:

Project
    images
        image1.jpg
        image2.jpg
    WEB-INF
        classes
            reports
                report1.jrxml
                report2.jrxml

It still doesn't seem to work. -------UPDATE-------- Code that fills the jasper report:

public JasperPrint loadReceipt(String reportName, String paymentId, String imagePath) {
        HashMap<String, Object> params = new HashMap<String, Object>();
        JasperReport report = null;
        JasperPrint print = null;

        try {
            if (jrReportMap == null) {
                jrReportMap = new HashMap<String, JasperReport>();
            }           

            if (jrReportMap.get(reportName) == null) {
                report = JasperCompileManager.compileReport(reportManager.load(reportName));
                jrReportMap.put(reportName, report);
                log.info(Logger.EVENT_SUCCESS, "--- Report Compilation done --- " + reportName);
            } else {
                report = jrReportMap.get(reportName);
                log.info(Logger.EVENT_SUCCESS, "--- Report already Compiled --- " + reportName);
            }

            params.put("paymentId", paymentId);
            params.put("realPath", imagePath);

            try {
                Connection conn = reportDataSource.getConnection();
                print = JasperFillManager.fillReport(report, params, conn);
                conn.close();
            } catch (SQLException e) {
                System.err.println("--- SQL ERR - to get connection -----");
                log.error(Logger.EVENT_FAILURE, "--- Report already Compiled --- " + reportName);
                e.printStackTrace();
            }
        } catch (JRException e1) {
            log.error(Logger.EVENT_FAILURE, "Oops... Something wrong while rendering the report !!!");
            e1.printStackTrace();
        }
        return print;
    }

Answer:

Instead of using <imageExpression><![CDATA["images/geLogo.jpg"]]></imageExpression>

use a parameter. E.g.,:

<imageExpression><![CDATA[$P{imagePath}]]></imageExpression>

imagePath it's a String that contains the relative URL of the image inside the WAR.

For example, if your WAR has the following structure:


 YourWebProject
      WebContent
           reports
                report1.jasper
                report2.jasper
                ...
                reportn.jasper
            images
                geLogo.jpg

When you fill the imagePath parameter you have to give it the path of the image relative to the report path. If you want to user geLogo.jpg image, it will be:

String imagePath = "../images/geLogo.jpg";

Question:

I want to display some tiff's which a stored in BLOB's in an oracle database. I just tried to convert them from tiff to jpg or png using im4java, but that didn't work. Maybe there is a possibility to display .tiff and other img data types in Jasper without converting them?! Or if not, does anybody have a detailed solution how to convert them? (which image class do I need to configure, how to implement in a scriptlet etc.)

Thanks everybody!

      IMOperation op = new IMOperation();
      op.addImage();
      op.addImage(); 

      ConvertCmd convert = new ConvertCmd();
      convert.run(op, new Object[]{inputImage.getAbsolutePath(), outputImage.getAbsolutePath()});
    return outputImage;`

Answer:

Solved the problem, here's the code worked for me using jai-imageIO.jar to convert tiff to jpg:

import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream;

import javax.imageio.ImageIO; import javax.imageio.spi.IIORegistry;

import net.sf.jasperreports.engine.JRAbstractScriptlet; import net.sf.jasperreports.engine.JRScriptletException;

public static InputStream convertTifToPng(InputStream inputImage)
        throws IOException, InterruptedException {
    IIORegistry registry = IIORegistry.getDefaultInstance();
    registry.registerServiceProvider(new com.sun.media.imageioimpl.plugins.tiff.TIFFImageWriterSpi());
    registry.registerServiceProvider(new com.sun.media.imageioimpl.plugins.tiff.TIFFImageReaderSpi());

    BufferedImage image;

    if (inputImage != null) {
        image = ImageIO.read(inputImage);
    } else {
        return null;
    }

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ImageIO.write(image, "jpg", baos);
    InputStream outputImage = new ByteArrayInputStream(baos.toByteArray());

    return outputImage;
}