Search code examples
javajasper-reports

How to validate empty report in JasperReports?


My situation is when I'm not able to retrieve anything with my query, that is found inside the jasper file, a report is still generated.

I'm using this line of code to generate report.

ByteArrayOutputStream baos = new ByteArrayOutputStream();

JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReportStream, params, jdbcConnection);
long start = System.currentTimeMillis();
Exporter jrExporter = getJRExporter(format, jasperPrint, baos);
jrExporter.exportReport();
bytes = baos.toByteArray();

Is there a way to use the exporter object to detect if my report is empty? I have tried to validate null using the byteArray then converted to String when producing a pdf format.

However I cannot easily check if byteArray is null since it produces this output despite returning no results from my query:

%PDF-1.4
%����
1 0 obj <</Length 45/Filter/FlateDecode>>stream
x�3P0T�5T0P0�4�ɹ\�\N!\�f
���
!)\�!\�\\   

Solution

  • Set on jasperReport tag whenNoDataType="NoPages" or remove whenNoDataType attribute (default is "NoPages")

    Check how many pages there are in the JasperPrint, if 0 you have NoData

        JasperPrint print = JasperFillManager.fillReport(jasperReportStream, params, jdbcConnection);
        List<JRPrintPage> pages = print.getPages();
        if (pages.size()==0){
                //No pages, do not export instead do other stuff
        }