2014-02-28 23 views
1

的Java/JSF讀取和打開的PDF與JSF

我試着在一個新的瀏覽器窗口中打開PDF,而不是下載它,但在每一個嘗試的文件下載成功和新的瀏覽器窗口它只會在應用程序中打開一個新選項卡,而不是PDF文件。

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

託管豆:generateReport調用downloadFile

FilePath參數下面= /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(); 
} 

我的鉻插件被啓用:

enter image description here

+0

? – Leo

+0

您是否試過'Content-Disposition:inline'而不是? – mabi

+0

嘗試..:內聯,並沒有工作 – Al2x

回答

2

如何primefaces media

showcase

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

你也可以把這個PDF瀏覽器在p:dialoghere

+1

好主意,我用p:media和複合對話框實現。請記住,p:media不適用於@ViewScoped。 – Al2x

+0

很高興它工作:) –

+0

鏈接不起作用 – Utk12

0

如果您希望瀏覽器知道它是PDF,它必須設置爲PDF內容類型(「application/pdf」)。你將它設置爲「application/octet-stream」。

+0

我已經嘗試與應用程序/ pdf沒有成功。 – Al2x

+0

檢查瀏覽器的標題。如果安裝的PDF插件沒有加載它,因爲瀏覽器不知道文件的MIME類型。也。你是否在文件名值上加了一個.PDF擴展名? – BrianC

-4

在該線

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

替換

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

刪除==>附件;那麼Pdf將在新標籤中打開

+0

爲什麼OP應該這樣做?請解釋你的答案。 –

+0

你有/自己嘗試一下嗎? – Sarz