如何在新选项卡中打开PDF文件

时间:2016-09-21 19:01:19

标签: jsf pdf primefaces

我正在使用JSF,我想在单击按钮时在新标签页中打开PDF文件。

XHTML

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

托管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();
        }
}

问题是当我使用这种方法时它只下载文件。有关您的信息,请关注此帖:http://balusc.omnifaces.org/2006/05/pdf-handling.html

1 个答案:

答案 0 :(得分:3)

你应该改变

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

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

因此,请使用inline代替attachment

另见: