Exporting a report to a PDF

HTML is the best option to render a report in a browser. However, JasperReports and DynamicJasper support many other formats. These formats are available as implementations of the JRExporter interface. One of them is the JRPdfExporter class. The example application includes the LastHourCallReport class, which, in contrast to previous report implementations, is not a Vaadin UI component. Since we want to allow users to download this report, we don't really need a UI component for it. Instead, LastHourCallReport is a helper class that configures the report, exports it as a PDF, and exposes the content of the file through an OutputStream suitable for the FileDownloader class, part of Vaadin Framework.

Omitting the details about the report configuration, which we already covered in previous sections, the following is the implementation of the LastHourCallReport class:

public class AnnualLegalReport {

public static ByteArrayOutputStream getOutputStream() {
try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
DynamicReport report = new FastReportBuilder()
... configure report ...
.build();

List<ClientCountDto> clients = ReportsService.countYearCallsByClient();
JasperPrint print = DynamicJasperHelper.generateJasperPrint(report, new ClassicLayoutManager(), clients);

JRPdfExporter exporter = new JRPdfExporter();
exporter.setExporterOutput(new SimpleOutputStreamExporterOutput(outputStream));
exporter.setExporterInput(new SimpleExporterInput(print));
exporter.exportReport();

outputStream.flush();
return outputStream;

} catch (JRException | IOException e) {
throw new RuntimeException(e);
}
}
}

We need to call the getOutputStream method from a new thread and modify the UI, also from this new thread, to add a button that downloads the PDF file. In order to modify the UI from a separate thread, we need to enable and use Server Push.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset