Search code examples
jasper-reports

How to do loop inside subreports in Jasper Reports


How to create a subreports inside of a single main report and this subreport should loop twice or thrice based on the data . I want to fill the data in my Java Spring Boot application only from the Java side. I able to create a PDF with just subreport displayed only once.

Example:
//Main report.jrxml
User No:u123

//sub reports.jrxml
Sub User Number: u123-01

Item Cost Price Sell Price
Orange 90.00 50.00
Banana 10.00 9.00
Apple 100.00 90.00

//sub reports.jrxml
Sub User Number: u123-02

Item Cost Price Sell Price
Cake 9.00 5.00
Milk 10.00 9.00
Chips 10.00 8.00

enter image description here

I tried generating one pdf with one table data, couldn't find a way to loop the sub report.


Solution

  • I discovered a method to cycle through subreports by passing data from Java as a JRBeanCollectionDataSource. In my primary report, I retrieve the data as follows: <field name="subreportDTOList" class="java.util.List"/>.

    This data is then passed to the subreport via the dataSourceExpression: <dataSourceExpression><![CDATA[new net.sf.jasperreports.engine.data.JRBeanCollectionDataSource($F{subreportDTOList})]]></dataSourceExpression>

    In the subreport, I can directly access the values within my DTO. Since the DTO is a list, it automatically loops through the subreport as needed.