About Us
Contact us

Facebook profile


Displaying JasperReports PDF Reports on the Browser
Bookmark and Share

Improving Performance

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 ServletOutputStream 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 ServletContext. This method returns an instance of java.io.InputStream that we can pass as a parameter to the runReportToPdfStream() method of the JasperRunManager class. The following example demonstrates this technique:

package net.ensode.jasperreportsbrowserdemo;

//import statements omitted

public class JasperReportsBrowserDemoServlet2 extends HttpServlet

  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException
    ServletOutputStream servletOutputStream = response.getOutputStream();
    InputStream reportStream = getServletConfig().getServletContext()
try { JasperRunManager.runReportToPdfStream(reportStream, servletOutputStream,
new HashMap(), new JREmptyDataSource());
response.setContentType("application/pdf"); servletOutputStream.flush(); servletOutputStream.close(); } catch (JRException e) { //handle the exception } } }

The two main changes from the previous example are highlighted in bold. The runReportToPdfStream() 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.


Java EE 6 Development With NetBeans 7
Java EE 6 Development With NetBeans 7

Java EE 6 with GlassFish 3 Application Server
Java EE 6 with GlassFish 3 Application Server

JasperReports 3.5 For Java Developers
JasperReports 3.5 For Java Developers