Fabio B.
Fabio B.

Reputation: 9400

Send a PDF to browser via JSF

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? :)

Upvotes: 3

Views: 6119

Answers (1)

BalusC
BalusC

Reputation: 1108702

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:

Upvotes: 8

Related Questions