jasperreports has the concept of Datasources, where you can assemble the data source of your report from various formats and send it to your reports.
You need to execute a code that returns some interface implementation Jrdatasource
There are some implementations of this class depending on how you want to pass your data, following examples:
- Jrresultsetdatasource If you want to work with a Resultset
- Jrbeancollectiondatasource If you want to pass any Collection as List, Set, etc
- Jrxlsdatasource If you want to use an Excel file as a data source.
Basically, instead of mounting the query in the report and having it run the query you pass the data source to the fillReport method, follow example:
InputStream isDesignRelatorio = this.getClass().getResourceAsStream("path/to/report.jasper");
JRDataSource dataSource = new JRResultSetDataSource(this.getResultSet());
JasperPrint print = JasperFillManager.fillReport(isDesignRelatorio,this.getParametros(), dataSource);
ByteArrayOutputStream pdfStream = new ByteArrayOutputStream();
JRPdfExporter exporter = new JRPdfExporter();
exporter.setExporterInput(SimpleExporterInput.getInstance(Arrays.asList(print)));
exporter.setExporterOutput(new SimpleOutputStreamExporterOutput(pdfStream));
SimplePdfExporterConfiguration configuration = new SimplePdfExporterConfiguration() ;
configuration.setCreatingBatchModeBookmarks(true);
exporter.setConfiguration(configuration);
exporter.exportReport();
Some comments on this code snippet:
This example assumes that you have a jrxml file already compiled in format. Jasper, I compile the report by the design tool so that the code does not "waste time" doing this, however you can also choose to compile at runtime.
In this case add a line compiling the report, for example:
JasperReport report = JasperCompileManager.compileReport(isDesignRelatorio);
The method this.getResultSet()
is to represent your data source that in this case would be a Resultset, but as I explained earlier may even be a Collection of a DTO assembled by you or even a bank entity.
In this case change the implmentation of the source date of new JRResultSetDataSource(this.getResultSet());
for something like new JRBeanCollectionDataSource(this.getCollection());
This example writes the export output on a ByteArrayOutputStream
, if you are working with a web system you can write directly to outputstream.
There is also the possibility to generate the output in a physical file, just explore the export forms.
How do you make your reports today regarding the data source ? You put the queries within each report ?
– hebertrfreitas
@hebertrfreitas yes, just like that. Consultation within the
jrxml
– Jefferson Quesado