3

I am trying to send a JasperReports generated PDF file to user's browser, I can't find what's wrong in my managed bean method, here's a snippet:

System.out.println("Making pdf...");

        FacesContext fc = FacesContext.getCurrentInstance();
        ExternalContext ec = fc.getExternalContext();
        String tplPath = ec.getRealPath("testTemplate.jrxml");
        JasperReport jasperReport = JasperCompileManager.compileReport(tplPath);
        JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, new HashMap<String,Object>(), ds );

        String pdfName = "/testReport.pdf";
        String pdfPath = ec.getRealPath(pdfName);
        JasperExportManager.exportReportToPdfFile(jasperPrint, pdfPath);

        System.out.println("PDF ready!");

        ec.responseReset(); 
        ec.setResponseContentType(ec.getMimeType(pdfPath)); 
        //ec.setResponseContentLength(contentLength); 
        ec.setResponseHeader("Content-Disposition", "attachment; filename=\"" + pdfName + "\""); 

        InputStream input = new FileInputStream(pdfPath);
        OutputStream output = ec.getResponseOutputStream();
        IOUtils.copy(input, output);

        System.out.println("Sending to browser...");

        fc.responseComplete();  

It's called by a simple user click:

<p:menuitem value="TestPDF" action="#{menuController.getTestPdf()}" />

I feel like it's something easy to find out. Why can't I see it? :)

Fabio B.
  • 9,138
  • 25
  • 105
  • 177
  • do you get any error? is that action triggered by an AJAX request? – Elias Dorneles Dec 18 '12 at 11:33
  • 3
    If you have looked in *Network* tab/section of webbrowser's builtin webdeveloper toolset, then you should surely have noticed that this construct has actually sent an ajax request. In the future questions like that try tracking the HTTP traffic first. – BalusC Dec 18 '12 at 12:20
  • @BalusC i was having same problem with `p:commandButton` i used `ajax="true"`(default). Your answer has solved my problem, but I want to ask question that, I click on `p:commandButton` it opens new tab of browser to view report but when I see in network tab there is no logging of this button. – Mohsin AR Sep 03 '14 at 10:27

1 Answers1

8

The <p:menuitem> uses by default ajax. You can't download files by ajax. JavaScript has due security reasons no facilities to programmatically force a Save As dialogue with arbitrary content in a variable.

Just turn off ajax.

<p:menuitem ... ajax="false" />

See also:

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555