How to display PDF in JSF, with content from ServletResponse

726 views Asked by At

In my application, I use jsf & richfaces, I want to display a generated pdf in web browser , I have generated this PDF in serverside and it is available in ServletResponse, but I am unable to display it in my web page.

I have tried this question but, it did not solve my problem.

Is there any libraries or special ways to do this?

What I have tried to do is given below.

    <h:commandLink rendered="#{ fileImportOptionsViewBean.isFileExist(status.myPdf) }" action="#
    {fileImportOptionsViewBean.downloadFile(satus.myPdf)}" target="_blank">


<h:graphicImage url="../../resources/xyz/icons/pdf.png" /></h:commandLink>

downloadFile method

public void downloadFile(String filePath){
    try {           
        File file=new File(filePath);
        if(file.exists()){
            FacesContext fc=FacesContext.getCurrentInstance();
            ExternalContext ec=fc.getExternalContext();
            ec.responseReset();
            ec.setResponseContentType("application/pdf");
            ec.setResponseHeader("Content-Disposition", "inline; filename=\"" + file.getName() + "\""); 
            ec.setResponseBufferSize(8192);
            OutputStream output = ec.getResponseOutputStream();                       
            URL url = file.toURL();
                            try(
                                BufferedInputStream bis = new BufferedInputStream(url.openStream());
                                BufferedOutputStream bos = new BufferedOutputStream(output);             
                             ){
                                byte[] buff = new byte[8192];
                                int bytesRead;
                                while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                                bos.write(buff, 0, bytesRead);              
                                 }                      
                            }
            fc.responseComplete(); 
        }


    } catch (Exception e) {

    }

}

Any help is appreciated,Thanks.

1

There are 1 answers

0
Joyal Augustine On BEST ANSWER

I don't see anything wrong with your current setup.Most probably the problem lies in your XHTML page and something is causing your h:commandLink not to fire the event.Please refer this post for further details,surely this will be of some help to you.