I designed a jasper report using ireport designer in which I added logo image in the title of the report. This image is added from the hard coded path on the local machine. I need to add the logo image from my projects classpath. To do that I created a parameter for the image in the report which is supplied from the program.
InputStream imgInputStream = this.getClass().getResourceAsStream("header.png");
HashMap<String, Object> parameters = new HashMap<String, Object>();
parameters.put("dateFrom", datum1);
parameters.put("dateTo", datum2);
parameters.put("logo", imgInputStream);
strQuery = "Select calldate,src,dst,duration,disposition,cdrcost from cdrcost where date(calldate) between '" + datum1 + "' and '" + datum2 + "'";
rs = conexiondb.Consulta(strQuery);
JRResultSetDataSource resultSetDataSource = new JRResultSetDataSource(rs);
//JasperPrint jasperPrint = JasperFillManager.fillReport(reportStream, parameters);
JasperRunManager.runReportToPdfStream(reportStream, fos, parameters, resultSetDataSource);
And below is the image snippet from the report:
<image>
<reportElement x="0" y="1" width="555" height="61"/>
<imageExpression><![CDATA[$P{logo}]]>
</imageExpression>
</image>
We always pass in the image instead of the InputStream. First load up the image and set it in the parameter map:
BufferedImage image = ImageIO.read(getClass().getResource("/images/IMAGE.png"));
parameters.put("logo", image );
Then the parameter is just defined like:
<parameter name="logo" class="Object" isForPrompting="false">
<parameterDescription><![CDATA[The letterhead image]]></parameterDescription>
<defaultValueExpression><![CDATA[]]></defaultValueExpression>
</parameter>
And when placed in the report it looks like:
<image>
<reportElement x="324" y="16" width="154" height="38"/>
<imageExpression><![CDATA[$P{logo}]]></imageExpression>
</image>
You can easily get the URL form the classpath/classloader. This is a valid input for <imageExpression> and therefore you can use it to embed an image in your pdf. The following worked for me:
Setting the parameter:
URL url = this.getClass().getClassLoader().getResource("pdf/my_image.tif");
parameters.put("logo", url);
Declaration in the report:
<parameter name="logo" class="java.net.URL">
<defaultValueExpression><![CDATA[]]></defaultValueExpression>
</parameter>
Usage in the report.
<image>
<reportElement x="100" y="30" width="135" height="30"/>
<imageExpression><![CDATA[$P{logo}]]></imageExpression>
</image>
Some additional observations
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With