jasperreport Posts

Creating Alphabet Numbering on Jasper Report

Usually jasper report provide a numbering, accessible using REPORT_COUNT variable, but today my friend Edward Barchia asked me something interesting, how can i create a simple numbering using alphabet instead of number. Well basically, it’s actually quite easy.

Below is the image, how i do it.
jasperreportcharat

Here is my complete jasper xml file,

<?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="report1" language="groovy" pageWidth="595" pageHeight="842" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" uuid="97dae3d4-5e81-4825-b4e7-cf3d1f77190f">
	<property name="ireport.zoom" value="1.2100000000000002"/>
	<property name="ireport.x" value="0"/>
	<property name="ireport.y" value="42"/>
	<queryString language="SQL">
		<![CDATA[select * from testing]]>
	</queryString>
	<field name="id" class="java.lang.Integer">
		<fieldDescription><![CDATA[]]></fieldDescription>
	</field>
	<field name="name" class="java.lang.String">
		<fieldDescription><![CDATA[]]></fieldDescription>
	</field>
	<field name="address" class="java.lang.String">
		<fieldDescription><![CDATA[]]></fieldDescription>
	</field>
	<background>
		<band splitType="Stretch"/>
	</background>
	<title>
		<band height="79" splitType="Stretch"/>
	</title>
	<pageHeader>
		<band height="35" splitType="Stretch"/>
	</pageHeader>
	<columnHeader>
		<band height="20" splitType="Stretch">
			<staticText>
				<reportElement x="50" y="0" width="100" height="20" uuid="f68bc18a-5471-4d4f-89ed-34d98bb06b6e"/>
				<text><![CDATA[name]]></text>
			</staticText>
			<staticText>
				<reportElement x="150" y="0" width="100" height="20" uuid="155f7ce1-e70c-4d93-8ebc-bad45d9f0ae1"/>
				<text><![CDATA[address]]></text>
			</staticText>
			<staticText>
				<reportElement x="0" y="0" width="50" height="20" uuid="48b8e6ef-1efd-4233-98f5-b2da6d273333"/>
				<text><![CDATA[No]]></text>
			</staticText>
		</band>
	</columnHeader>
	<detail>
		<band height="20" splitType="Stretch">
			<textField>
				<reportElement x="50" y="0" width="100" height="20" uuid="3ffd3edf-b950-4dd9-8f13-ac8942e5bb8e"/>
				<textFieldExpression><![CDATA[$F{name}]]></textFieldExpression>
			</textField>
			<textField>
				<reportElement x="150" y="0" width="100" height="20" uuid="236aec6c-34dc-4a54-ae2d-086c2a23786c"/>
				<textFieldExpression><![CDATA[$F{address}]]></textFieldExpression>
			</textField>
			<textField>
				<reportElement x="0" y="0" width="50" height="20" uuid="704b47d3-7dca-4f33-950a-a3efd0fb764b"/>
				<textFieldExpression><![CDATA["abcdefghijklmnopqrstuvwxyz".charAt( $V{REPORT_COUNT}-1 )]]></textFieldExpression>
			</textField>
		</band>
	</detail>
	<columnFooter>
		<band height="45" splitType="Stretch"/>
	</columnFooter>
	<pageFooter>
		<band height="54" splitType="Stretch"/>
	</pageFooter>
	<summary>
		<band height="42" splitType="Stretch"/>
	</summary>
</jasperReport>
Google+

Fixing Jasper Report Error, “Font ‘Arial’ is not available to the JVM.”

Yesterday, i had a weird error when deploying to my Red Hat machine. Somehow my pdf generated report is throwing exceptions, it said “Font ‘Arial’ is not available to the JVM.”. A little bit weird since on my development machine, everything is running well.

After i run this command,

fc-list | grep "Arial"

I found out that “Arial” font isnt installed on my RedHat server, a little bit tricky due to im unable to run “yum” command because the server is behind a network firewall. So my workaround is download a .rpm, and installed it manually. After several minutes googling, i found a very recommended .rpm installer.


http://www.mjmwired.net/resources/mjm-fedora-f11.html#ttf

I installed it using

 sudo rpm -ivh msttcore-fonts-2.0-3.noarch.rpm

And check my installed fonts

fc-list | grep "Arial"

Now i can see “Arial” fonts on my list of installed fonts on RedHat, restart my tomcat and my pdf reporting is running well again.

Here is the complete stacktrace of the error,

21:57:12,135 INFO  [stdout] (AsyncLogger-1) <2014-09-29 21:57:12,131>,[http-/0.0.0.0:80-94]>>[ERROR]Font 'Arial' is not available to the JVM. See the Javadoc for more details. net.sf.jasperreports.engine.util.JRFontNotFoundException: Font 'Arial' is not available to the JVM. See the Javadoc for more details.
21:57:12,135 INFO  [stdout] (AsyncLogger-1) 	at net.sf.jasperreports.engine.fonts.FontUtil.checkAwtFont(FontUtil.java:357)
21:57:12,135 INFO  [stdout] (AsyncLogger-1) 	at net.sf.jasperreports.engine.fill.SimpleTextLineWrapper.loadFont(SimpleTextLineWrapper.java:369)
21:57:12,135 INFO  [stdout] (AsyncLogger-1) 	at net.sf.jasperreports.engine.fill.SimpleTextLineWrapper.getGeneralFontInfo(SimpleTextLineWrapper.java:339)
21:57:12,135 INFO  [stdout] (AsyncLogger-1) 	at net.sf.jasperreports.engine.fill.SimpleTextLineWrapper.createFontInfo(SimpleTextLineWrapper.java:279)
21:57:12,135 INFO  [stdout] (AsyncLogger-1) 	at net.sf.jasperreports.engine.fill.SimpleTextLineWrapper.start(SimpleTextLineWrapper.java:241)
21:57:12,135 INFO  [stdout] (AsyncLogger-1) 	at net.sf.jasperreports.engine.fill.TextMeasurer.measure(TextMeasurer.java:537)
21:57:12,136 INFO  [stdout] (AsyncLogger-1) 	at net.sf.jasperreports.engine.fill.JRFillTextElement.chopTextElement(JRFillTextElement.java:623)
21:57:12,136 INFO  [stdout] (AsyncLogger-1) 	at net.sf.jasperreports.engine.fill.JRFillTextField.prepare(JRFillTextField.java:699)
Google+

A Simple Java Desktop JasperReport Example

Hi, im currently testing the latest version of iReport, iReport 4.5.1. For the test, im trying to create a very simple reporting, consist of 2 column and without database connection. Im using a simple Array of Maps to fill my jasper report’s data using the JRMapCollectionDataSource class.

Here is my report example,

<?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="report" pageWidth="595" pageHeight="842" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20">
	<property name="ireport.zoom" value="1.0"/>
	<property name="ireport.x" value="0"/>
	<property name="ireport.y" value="0"/>
	<field name="name" class="java.lang.String"/>
	<field name="address" class="java.lang.String"/>
	<background>
		<band splitType="Stretch"/>
	</background>
	<title>
		<band height="31" splitType="Stretch">
			<staticText>
				<reportElement x="235" y="0" width="100" height="31"/>
				<textElement>
					<font size="24"/>
				</textElement>
				<text><![CDATA[Judul Saya]]></text>
			</staticText>
		</band>
	</title>
	<pageHeader>
		<band height="35" splitType="Stretch"/>
	</pageHeader>
	<columnHeader>
		<band height="22" splitType="Stretch">
			<staticText>
				<reportElement x="0" y="2" width="100" height="20"/>
				<textElement/>
				<text><![CDATA[name]]></text>
			</staticText>
			<staticText>
				<reportElement x="200" y="2" width="100" height="20"/>
				<textElement/>
				<text><![CDATA[address]]></text>
			</staticText>
		</band>
	</columnHeader>
	<detail>
		<band height="20" splitType="Stretch">
			<textField>
				<reportElement x="0" y="0" width="200" height="20"/>
				<textElement/>
				<textFieldExpression><![CDATA[$F{name}]]></textFieldExpression>
			</textField>
			<textField>
				<reportElement x="200" y="0" width="221" height="20"/>
				<textElement/>
				<textFieldExpression><![CDATA[$F{address}]]></textFieldExpression>
			</textField>
		</band>
	</detail>
	<columnFooter>
		<band height="13" splitType="Stretch"/>
	</columnFooter>
	<pageFooter>
		<band height="14" splitType="Stretch"/>
	</pageFooter>
	<summary>
		<band height="8" splitType="Stretch"/>
	</summary>
</jasperReport>

Dont forget to compile it, and this is my java code to call my report. It call for .jasper file instead of .jrxml files.

package com.edw.main;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.util.ArrayList;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.data.JRMapCollectionDataSource;
import net.sf.jasperreports.engine.util.JRLoader;
import net.sf.jasperreports.view.JasperViewer;
import org.apache.log4j.Logger;

public class Main {

    private Logger logger = Logger.getLogger(Main.class);

    public Main() {
    }

    private void start() {
        try {                                            
            // load report location
            FileInputStream fis = new FileInputStream("report.jasper");
            BufferedInputStream bufferedInputStream = new BufferedInputStream(fis);

            // fill report
            List<Map<String,?>> maps = new ArrayList<Map<String, ?>> (); 
            for (int i = 0; i < 10; i++) {
                Map<String,Object> map = new HashMap<String, Object>();
                map.put("name", getRandomString());
                map.put("address", getRandomString());
                maps.add(map);
            }            
            JRMapCollectionDataSource dataSource = new JRMapCollectionDataSource(maps);
            
            // compile report
            JasperReport jasperReport = (JasperReport) JRLoader.loadObject(bufferedInputStream);
            JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, new HashMap(), dataSource);

            // view report to UI
            JasperViewer.viewReport(jasperPrint, false);

        } catch (Exception e) {
            logger.error(e, e);
        }
    }
    
    private String getRandomString(){
        return UUID.randomUUID().toString();
    }

    public static void main(String[] args) {
        Main main = new Main();
        main.start();
    }
}

And some screenshots from my project,

Have fun with Jasper Report ;)

Google+

Weird Blank Report When Using JasperReport

Yesterday, ive found a very weird error when im trying to print my report to pdf using jasper report. Somehow it show a blank report when i’m printing my report and my log file shows no error at all despite there is nothing on my pdf file. I’m using a simple servlet and jasper report classes to generate my pdf files and show it on browser.

This is what my report looks like

And this is part of my sourcecode

   protected void doPost(HttpServletRequest request, HttpServletResponse response) 
        throws ServletException, IOException {
		// set header as pdf
        response.setContentType("application/pdf");

        // set input and output stream
        ServletOutputStream servletOutputStream = response.getOutputStream();   
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        
        FileInputStream fis;
        BufferedInputStream bufferedInputStream;
        
        String nama = "";
        String alamat = "";

        try {        	
        	if(request.getParameter("nama")!=null)
            	nama = request.getParameter("nama");
			
			if(request.getParameter("alamat")!=null)
				alamat = request.getParameter("alamat");
        	
        	// get report location
            ServletContext context = getServletContext();
            String reportLocation = context.getRealPath("WEB-INF");
            
            // get report
            fis = new FileInputStream(reportLocation + "/report/LaporanSatu.jasper");
            bufferedInputStream = new BufferedInputStream(fis);
            
            // fill parameters
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("nama", "%"+nama+"%");
            map.put("alamat", alamat);
                                               	
            // export to pdf            
            JasperReport jasperReport = (JasperReport) JRLoader.loadObject(bufferedInputStream);
            JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, map);
            JasperExportManager.exportReportToPdfStream(jasperPrint, baos);

            response.setContentLength(baos.size());
            baos.writeTo(servletOutputStream);

            // close it
            fis.close();
            bufferedInputStream.close();            
		} catch (Exception e) {
			e.printStackTrace();
		} finally{
			servletOutputStream.flush();
            servletOutputStream.close();
            baos.close();
		}        
	}

Well the workaround is actually very easy, i only need to add a new empty datasource (JREmptyDataSource) in JasperFillManager parameters

   protected void doPost(HttpServletRequest request, HttpServletResponse response) 
        throws ServletException, IOException {
		// set header as pdf
        response.setContentType("application/pdf");

        // set input and output stream
        ServletOutputStream servletOutputStream = response.getOutputStream();   
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        
        FileInputStream fis;
        BufferedInputStream bufferedInputStream;
        
        String nama = "";
        String alamat = "";

        try {        	
        	if(request.getParameter("nama")!=null)
            	nama = request.getParameter("nama");
			
			if(request.getParameter("alamat")!=null)
				alamat = request.getParameter("alamat");
        	
        	// get report location
            ServletContext context = getServletContext();
            String reportLocation = context.getRealPath("WEB-INF");
            
            // get report
            fis = new FileInputStream(reportLocation + "/report/LaporanSatu.jasper");
            bufferedInputStream = new BufferedInputStream(fis);
            
            // fill parameters
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("nama", "%"+nama+"%");
            map.put("alamat", alamat);
                       
                        	
            // export to pdf            
            JasperReport jasperReport = (JasperReport) JRLoader.loadObject(bufferedInputStream);
            JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, 
              map, new JREmptyDataSource());
            JasperExportManager.exportReportToPdfStream(jasperPrint, baos);

            response.setContentLength(baos.size());
            baos.writeTo(servletOutputStream);

            // close it
            fis.close();
            bufferedInputStream.close();
            
		} catch (Exception e) {
			e.printStackTrace();
		} finally{
			servletOutputStream.flush();
            servletOutputStream.close();
            baos.close();
		}        
	}

This is the screenshot for my successful report.

Google+

How to Handle Jasper Report’s NoSuchMethodException

I was generating an ordinary report, when suddenly i met a weird error. My Exception showed a net.sf.jasperreports.engine.JRException and a java.lang.NoSuchMethodException: Unknown property '' when im using Jasper Report’s JRBeanCollectionDataSource. I tought it was because my java bean is not Serializable, but changing my bean to Serializable still didnt fix my errors.
Here is my complete stacktrace

net.sf.jasperreports.engine.JRException: Error retrieving field value from bean : 
        at net.sf.jasperreports.engine.data.JRAbstractBeanDataSource.getBeanProperty(JRAbstractBeanDataSource.java:123)
        at net.sf.jasperreports.engine.data.JRAbstractBeanDataSource.getFieldValue(JRAbstractBeanDataSource.java:96)
        at net.sf.jasperreports.engine.data.JRBeanCollectionDataSource.getFieldValue(JRBeanCollectionDataSource.java:100)
        at net.sf.jasperreports.engine.fill.JRFillDataset.setOldValues(JRFillDataset.java:818)
        at net.sf.jasperreports.engine.fill.JRFillDataset.next(JRFillDataset.java:782)
        at net.sf.jasperreports.engine.fill.JRBaseFiller.next(JRBaseFiller.java:1433)
        at net.sf.jasperreports.engine.fill.JRVerticalFiller.fillReport(JRVerticalFiller.java:108)
        at net.sf.jasperreports.engine.fill.JRBaseFiller.fill(JRBaseFiller.java:908)
        at net.sf.jasperreports.engine.fill.JRBaseFiller.fill(JRBaseFiller.java:830)
        at net.sf.jasperreports.engine.fill.JRFiller.fillReport(JRFiller.java:85)
        at net.sf.jasperreports.engine.JasperFillManager.fillReport(JasperFillManager.java:624)

Caused by: java.lang.NoSuchMethodException: Unknown property ''
        at org.apache.commons.beanutils.PropertyUtilsBean.getSimpleProperty(PropertyUtilsBean.java:1122)
        at org.apache.commons.beanutils.PropertyUtilsBean.getNestedProperty(PropertyUtilsBean.java:686)
        at org.apache.commons.beanutils.PropertyUtilsBean.getProperty(PropertyUtilsBean.java:715)

Here is my source code snippet, take a look at line 12, that is where my exception happen.

  @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {     

        List<Log> logs = logService.select();

        FileInputStream fis = new FileInputStream("/ejournal.jasper");
        BufferedInputStream bufferedInputStream = new BufferedInputStream(fis);

        Map<String, String> map = new HashMap<String, String>();
        JRBeanCollectionDataSource jrbcds = new JRBeanCollectionDataSource(logs);

        JasperReport jasperReport = (JasperReport) JRLoader.loadObject(bufferedInputStream);
        JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, map, jrbcds);
    }

Well actually it’s very easy to fix it, you should either

  • Remove the empty field descriptions from the JRXML.
  • Set the field descriptions to match the bean property names.
  • Pass false as isUseFieldDescription when creating the bean data source, e.g. new JRBeanCollectionDataSource(data, false).

This is how i fixed it,

 @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {     

        List<Log> logs = logService.select();

        FileInputStream fis = new FileInputStream("/ejournal.jasper");
        BufferedInputStream bufferedInputStream = new BufferedInputStream(fis);

        Map<String, String> map = new HashMap<String, String>();
        JRBeanCollectionDataSource jrbcds = new JRBeanCollectionDataSource(logs,false);

        JasperReport jasperReport = (JasperReport) JRLoader.loadObject(bufferedInputStream);
        JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, map, jrbcds);
    }

I hope it can help others, because i spend some ridicoulously amount of time looking for this workaround.
;-)

Google+