read and open PDF in a new browser window with JSF

谁说胖子不能爱 提交于 2019-12-06 12:21:30

问题


Java / JSF

Im trying to open PDF in a new browser window instead of download it but in every try the file is downloaded with success and it opens a new tab with the application only and not the pdf file.

<p:commandLink title="report" target="_blank"
    action="#{managedBean.generateReport('P',true)}"
    ajax="false" immediate="false" >
</p:commandLink>

Managed bean : generateReport calls downloadFile

The filePath parameter below = /temp/doc/abc.pdf (chmod 777)

public static void downloadFile(String filePath) throws IOException{
    FacesContext context = FacesContext.getCurrentInstance();  
    HttpServletResponse response = (HttpServletResponse) context  
                         .getExternalContext().getResponse();  
    File file = new File(filePath);  
    if (!file.exists()) {  
      response.sendError(HttpServletResponse.SC_NOT_FOUND);  
      return;  
     }  
    response.reset();  
    response.setBufferSize(DEFAULT_BUFFER_SIZE);  
    response.setContentType("application/octet-stream");  
    response.setHeader("Content-Length", String.valueOf(file.length()));  
    response.setHeader("Content-Disposition", "attachment;filename=\""  
           + file.getName() + "\"");  
    BufferedInputStream input = null;  
    BufferedOutputStream output = null;  

    try 
    {  
        input = new BufferedInputStream(new FileInputStream(file),  
                    DEFAULT_BUFFER_SIZE);  
        output = new BufferedOutputStream(response.getOutputStream(),  
                        DEFAULT_BUFFER_SIZE);  
        byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];  
        int length;  
        while ((length = input.read(buffer)) > 0) {  
            output.write(buffer, 0, length);  
        }  
    } finally 
    {  
        input.close();  
        output.close();  
    }  
    context.responseComplete();
}

My Chromium plugin is enabled :


回答1:


How about primefaces media :

From the showcase :

<p:media value="/resources/other/guide.pdf" width="100%" height="300px"/>  

Also you can put this PDF viewer in a p:dialog here.




回答2:


It has to be set to the PDF content type ("application/pdf") if you want the browser to know it is a PDF. You are setting it to "application/octet-stream".




回答3:


At this line

response.setHeader("Content-Disposition", "attachment;filename=\""  + file.getName() + "\"");

replace with

response.setHeader("Content-Disposition", "filename=\""  + file.getName() + "\""); 

remove ==> attachment; then Pdf will open in new tab



来源:https://stackoverflow.com/questions/22103734/read-and-open-pdf-in-a-new-browser-window-with-jsf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!