Jasper Reports (quick and dirt) tutorial
If you want a simple Jasper Reports tutorial, you will have a bad time googling it. The official site has a nice theorical introduction, but after reading it, you will not have a working “hello world” example. Unfortunatelly, the “definitive guide” is a book you need to buy.
Since I prefer a “try-before-you-buy” approach, I asked Google and I’ve found a simple “hello world” JRXML reading this tutorial from David Heffelfinger’s article. Good one, but I will upgrade it. The XML can use XSD:
<?xml version="1.0" encoding="UTF-8"?>
<jasperReport name="report name"
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">
<detail>
...
</detail>
</jasperReport>
If you are using NetBeans 6, go to “Tools > Options > Miscellaneous > Files”, add “jrxml” extension and associate with “application/xml”. Now, it will autocomplete jasper tags for you. You can use iReport NB plugin, too, but I like to know how it work.
Well, you need to compile this JRXML before using it. David shows how to do programmatically. If you want to add only the compiled version to your JAR file, you can add this to your Ant build file (this is a NB version, change parameters as needed):
<target name="-post-init">
<!-- Init jasper ant task -->
<taskdef classpath="${javac.classpath}"
classname="net.sf.jasperreports.ant.JRAntCompileTask"
name="jrc" />
</target>
<target name="-post-compile">
<!-- without a tempdir, JR may
create files on NB folder! -->
<mkdir dir="${build.dir}/jasper"/>
<!-- compile "src/JRXML" to "build/JASPER" -->
<jrc destdir="${build.classes.dir}"
tempdir="${build.dir}/jasper">
<src>
<fileset dir="${src.dir}" includes="**/*.jrxml" />
</src>
<classpath>
<path path="${javac.classpath}"/>
</classpath>
</jrc>
</target>
Now you have a “.jasper” file on your build dir, together with your compiled classes - just ready for use! Let’s use it:
InputStream in = getClass().getResourceAsStream("/my-pkg/myReport.jasper");
JasperPrint jasperPrint = JasperFillManager.fillReport(in,
new HashMap(), new JREmptyDataSource());
JasperExportManager.exportReportToHtmlFile(jasperPrint,
"output-path/report.html");
Pretty easy, huh? One last note - you will need more libs than just “jasperreports.jar” on your classpath:
- commons-digester
- commons-logging
- commons-collections
- commons-beanutils
- itext (only if you want to export as PDF)
March 16th, 2009 at 8:20 am
[…] Extreme Java I’m not a guru, but sometimes I need to do some “unusual” things in Java. These things are so extreme that are not well documented. To help other Java users, I post my discoveries here. « Jasper Reports (quick and dirt) tutorial […]