Search code examples
javajasper-reportsexport-to-pdf

Download option for pdf generated by Jasper reports in browsers not working


Im trying to generate a pdf using jasper reports. Its generating fine and its storing in the specified path directly. But what I needed is, it has to show the open or save option before downloading directly. Im using struts 1.x

Here is my code which I hve written in the method

String reportsPath = "D:/JasperReports/";
String reportName = "StatisticsReport";
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put("statisticsData", map);

// Load JRXML

 JasperDesign mainReportDesign = JRXmlLoader.load(reportsPath + reportName + ".jrxml");
// Compile to generate .Jasper file
   JasperCompileManager.compileReportToFile(mainReportDesign, reportsPath + reportName + ".jasper");

   System.out.println(reportsPath + reportName);
                 // Generate Jasper print
   JasperPrint jasperPrint = JasperFillManager.fillReport(reportsPath + reportName + ".jasper", parameters,
                             new JREmptyDataSource());

   String pdfFileName = "D:/JasperReports/StatisticsrReport.pdf";
                 // Export PDF file
   response.addHeader("Content-disposition", "attachment; filename=StatisticsrReport1.pdf");
                 JasperExportManager.exportReportToPdfFile(jasperPrint,pdfFileName);

Solution

  • Browser will prompt to save or open file when response content type is application/x-download. For example:

    //String pdfFileName = "D:/JasperReports/StatisticsrReport.pdf";
    response.setContentType("application/x-download");
    response.addHeader("Content-disposition", "attachment; filename=StatisticsrReport1.pdf");
    OutputStream out = response.getOutputStream();
    JasperExportManager.exportReportToPdfStream(jasperPrint,out);//export PDF directly
    //return null ActionForward, no extra data is appended to output stream