Vicky Vicky - 4 months ago 56
Java Question

Combining two jasper reports

I have a web application with a dropdown from where user could select the type of report viz. report1, report2, report3, etc.

Based on the report selected, a jasper report is compiled on the server and opens as a pop up in pdf format.

On the server side, I am implementing each report in a separate method using below code say for e.g. for report1:

JRBeanCollectionDataSource report1DataSource = new JRBeanCollectionDataSource(resultSetBeanListReport1);

InputStream inputStreamReport1 = new FileInputStream(request.getSession().getServletContext ().getRealPath(jrxmlFilePath + "report1.jrxml"));

JasperDesign jasperDesignReport1 = JRXmlLoader.load(inputStreamReport1);

JasperReport jasperReportReport1 = JasperCompileManager.compileReport(jasperDesignReport1);

bytes = JasperRunManager.runReportToPdf(jasperReportReport1, titleMapReport1, report1DataSource);

Similarly, report2 is in a separate method with below code:

JRBeanCollectionDataSource invstSummDataSource = new JRBeanCollectionDataSource(resultSetBeanListInvstOfSumm);

InputStream inputStreamInvstSumm = new FileInputStream(request.getSession().getServletContext().getRealPath(jrxmlFilePath + "investSummary.jrxml"));

JasperDesign jasperDesignInvstSumm = JRXmlLoader.load(inputStreamInvstSumm);

JasperReport jasperReportInvstSumm = JasperCompileManager.compileReport(jasperDesignInvstSumm);

bytes = JasperRunManager.runReportToPdf(jasperReportInvstSumm, titleMapInvstSumm, invstSummDataSource);

Now I have a requirement that if report1 is selected from the dropdown, the resulting pdf should contain all the reports one after other in the same pdf.

How can I combine above two lines of codes to finally generate a single pdf?


Here is sample code for combining multiple jasper prints

List<JasperPrint> jasperPrints = new ArrayList<JasperPrint>();
// Your code to get Jasperreport objects
JasperReport jasperReportReport1 = JasperCompileManager.compileReport(jasperDesignReport1);
JasperReport jasperReportReport2 = JasperCompileManager.compileReport(jasperDesignReport2);
JasperReport jasperReportReport3 = JasperCompileManager.compileReport(jasperDesignReport3);

JRPdfExporter exporter = new JRPdfExporter();
//Create new FileOutputStream or you can use Http Servlet Response.getOutputStream() to get Servlet output stream
// Or if you want bytes create ByteArrayOutputStream
ByteArrayOutputStream out = new ByteArrayOutputStream();
exporter.setParameter(JRExporterParameter.JASPER_PRINT_LIST, jasperPrints);
exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, out);
byte[] bytes = out.toByteArray();