5

I am working with JSF and I want to open a PDF file in a new tab when I click on a button.

XHTML

<p:commandButton onclick="this.form.target = '_blank'"
                 actionListener="#{managedBean.openFile(file)}"
                 ajax="false" />

Managed bean

public void openFile( File file ) {
FacesContext facesContext = FacesContext.getCurrentInstance();
        ExternalContext externalContext = facesContext.getExternalContext();
        HttpServletResponse response = (HttpServletResponse) externalContext.getResponse();
        BufferedInputStream input = null;
        BufferedOutputStream output = null;

        try {
            // Open file.
            input = new BufferedInputStream(new FileInputStream(file), 10240);

            // Init servlet response.
            response.reset();
            // lire un fichier pdf
            response.setHeader("Content-type", "application/pdf"); 
            response.setContentLength((int)file.length());

            response.setHeader("Content-disposition", "attachment; filename=" + node.getNomRepertoire());
            response.setHeader("pragma", "public");
            output = new BufferedOutputStream(response.getOutputStream(), 10240);

            // Write file contents to response.
            byte[] buffer = new byte[10240];
            int length;
            while ((length = input.read(buffer)) > 0) {
                output.write(buffer, 0, length);
            }

            // Finalize task.
            output.flush();
        } finally {
            // Gently close streams.

                output.close();
                input.close();
        }
}

The problem is when I use this method it only downloads the file. For your information, I'm following this post: http://balusc.omnifaces.org/2006/05/pdf-handling.html

Jasper de Vries
  • 19,370
  • 6
  • 64
  • 102

1 Answers1

7

You should change

response.setHeader("Content-disposition", "attachment; filename=" + node.getNomRepertoire());

into

response.setHeader("Content-disposition", "inline; filename=" + node.getNomRepertoire());

So, use inline instead of attachment.

See also:

Community
  • 1
  • 1
Jasper de Vries
  • 19,370
  • 6
  • 64
  • 102
  • just to know it is possible to `onclick="this.form.target = '_blank'"` from the managedBean ?!? –  Sep 22 '16 at 08:21
  • You could create some JavaScript in your bean and pass it to the front end, but that would be over complicating things. Not sure though if `this` will be working since PF wraps the `onclick`. If so, try `document.getElementById('yourFormId').target = '_blank'`. – Jasper de Vries Sep 22 '16 at 08:27