Reputation: 1325
I am trying to create a pdf file with a simple table. I have computed all the table data ahead into a Map<String, List<String>>
where the keys are the table columns and the corresponding list is the values that will populated each column cells. I have followed this example but I seem to not be able to correctly initialize the JRDataSource required to print the report since I can't understand what it expects to receive. It seems that are several classes that implement the interface like JRMapArrayDataSource
or JRMapCollectionDataSource
but those expect an array or a collection. I have already tried to convert my map to one of these but that won't work because then it can't know what goes to each column. Follows my code. Any clue on how to structure this would be very appreciated.
public void buildReport(Map<String, List<String>> tableData) throws Exception {
drb = new DynamicReportBuilder();
List<AbstractColumn> columns = new ArrayList<>();
tableData.keySet().forEach(key-> {
AbstractColumn column = ColumnBuilder.getNew()
.setColumnProperty(key, String.class.getName()).setTitle(key.toUpperCase()).setWidth(85).build();
columns.add(column);
});
columns.forEach(column -> drb.addColumn(column));
DynamicReport dynamicReport = drb.build();
JasperReport jasperReport = DynamicJasperHelper.generateJasperReport(dynamicReport,
new ClassicLayoutManager(),
params);
//JRDataSource dataSource = new JRBeanCollectionDataSource(SortUtils.sortCollection(Arrays.asList(tableData.values()), dynamicReport.getColumns()));
JRDataSource dataSource = new JRMapArrayDataSource(tableData); // this is wrong since it expects java.lang.Object
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, params, dataSource);
exportReport(jasperPrint, System.getProperty("user.dir")+ urlJasper + "reports/medical-report.pdf");
}
Upvotes: 0
Views: 2601
Reputation: 1325
I fixed the issue for this case by restructuring the data into a collection of rows. So instead of having a Map<String, List<String>>
I had to convert it to a List<Map<String, String>>
where each map in the list concerns a line in the table and the map has the column name as key and the column value for the row as value. I then used
JRDataSource dataSource = new JRBeanCollectionDataSource(tableData);
to create the JRDataSource.
Upvotes: 1