Although the previous example works as intended, with a few minor
tweaks we can make it perform better. Instead of creating an array of
bytes and passing it to the
write() method of the
class, we can stream the PDF directly to the browser. To accomplish
this, we must first get the compiled resource as a stream by calling the
getResourceAsStream() method in the
This method returns an instance of
we can pass as a parameter to the
method of the
JasperRunManager class. The following example
demonstrates this technique:
The two main changes from the previous example are highlighted in bold. The
method of the
JasperRunManager streams the PDF report to
the browser as it is generated. This way we don't have to store an array
of bytes in memory as in the previous example. When using this
technique, the content length can't be set, therefore the client won't
be able to keep a persistent connection open to the server, but that
usually isn't important with PDFs, because the entire PDF is self
contained and the client won't need to ask for more info.
As can be seen from the examples provided in this article, sending a JasperReports generated PDF report to a browser is not a difficult task. Similar techniques can be used to export HTML, RTF, XLS or any other output format supported by JasperReports.
Thanks to Barry Klawans from JasperSoft for providing valuable feedback.