Tuesday, August 2, 2011

JasperReport from XML Datasource with Inline Images

There are many library for creating reports. But personally I use Jasper Report. JasperReports is an open source Java reporting tool that can write to screen, to a printer or into PDF, HTML, Microsoft Excel, RTF, ODT, Comma-separated values and XML files. It can be used in Java-enabled applications, including Java EE or Web applications, to generate dynamic content.

I'm adding XML datasources for reports @ my work place and needed to embed the image signature for every report document.



If you're creating your XML dynamically using Java you can do:
...
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
// Read the byte array from DB or whatever
byte[] imageByteArray = getImageByteArray();
String base64Image = Base64.encodeBase64String(imageByteArray);
...

NOTE: If u do this in alfresco I advice u read my old post and use it simple.

then write the Base64 encoded data in your XML as:
<signature> ... Your base64 image string... </signature>

As the post says, in your JasperReport (I currently use iReport  as a report editor) define a String field, let's call it signature, for the image:
<field name="signature" class="java.lang.String">
  <fieldDescription><![CDATA[/data/person/signature]]></fieldDescription>
 </field>

then define a variable, let’s call it IMAGE_BYTES, which uses that field:
with the Variable Expression:
ImageIO.read(new ByteArrayInputStream(Base64.decode($F{signature})))
NOTE:don’t forget to add com.sun.org.apache.xerces.internal.impl.dv.util.Base64 to the imports of the report properties
Additional import javax.imageio.ImageIO
and in the image element on your layout use the IMAGE_BYTES variable:

That is all u need to know (I am about for this problem :) )

No comments:

Post a Comment