2013-10-10 39 views
1

我試圖發送一個靜態pdf(在系統上)到outputStream以顯示另存爲對話框。 但只打開PDF文件時顯示空白頁:通過Servlet銷燬OutputStream pdf

這裏應該顯示的對話框代碼:

//get the pdf: 
    String pathToPdf = servletContext.getRealPath("/pdfFiles/dealer.pdf"); 
    File pdfFile = new File (pathToPdf); 

    response.setContentType("application/pdf"); 
    response.addHeader("Content-Disposition", "attachment; filename=dealer.pdf"); 
    response.setContentLength((int) pdfFile.length()); 

    FileInputStream fileInputStream = new FileInputStream(pdfFile); 
    OutputStream responseOutputStream = response.getOutputStream(); 
    int bytes; 
    while ((bytes = fileInputStream.read()) != -1) { 
     responseOutputStream.write(bytes); 
     } 
    responseOutputStream.flush(); 
    responseOutputStream.close(); 

堆棧跟蹤說以下內容:

WARNING: Invalid HTML; bare lessthan sign found at line 4. Surroundings: '< 
/Creator (Apache FOP Version'. 
WARNING: Invalid HTML; bare lessthan sign found at line 5. Surroundings: '/Creator (Apache FOP Version 1'. 
WARNING: Invalid HTML; bare lessthan sign found at line 11. Surroundings: '< 
    /N 3 
    /Length 11 0 R 
    /F'. 
WARNING: Invalid HTML; bare lessthan sign found at line 12. Surroundings: '/N 3 
    /Length 11 0 R 
    /Filte'. 
WARNING: Invalid HTML; bare lessthan sign found at line 18. Surroundings: '?s??e???'?9???`??2?&c?tI?'. 
WARNING: Invalid tag found: unexpected input while looking for attr name or '/>' at line 25. Surroundings: '?+?U?Zp'pWp?????????e?F|'. 
WARNING: Invalid HTML; bare lessthan sign found at line 68. Surroundings: '< 
    /Name /Im1 
    /Type /XObjec'. 
WARNING: Invalid HTML; bare lessthan sign found at line 69. Surroundings: '/Name /Im1 
    /Type /XObject 
    '. 
WARNING: Invalid tag found: unexpected input while looking for attr name or '/>' at line 85. Surroundings: '??r??"?F?t??$??n{?q??O~??{?'. 

誰能說我失蹤或做錯了什麼? 謝謝!

+0

你齊平,然後關閉的OutputStream? –

+0

是的,我已經編輯了這個問題。 – bethlis

+0

從它的樣子,你試圖解釋PDF爲一個點的HTML在某些時候 –

回答

0

我不得不添加以下內容:

context.responseComplete(); 

所以完整的代碼看起來現在這個樣子:

response.setContentType("application/pdf"); 
      response.setHeader("Content-Disposition", "attachment; filename=\"PdfName.pdf\""); 
      response.setContentLength(outStream.size()); 

      OutputStream responseOutputStream = response.getOutputStream(); 
      outStream.writeTo(responseOutputStream); 

      responseOutputStream.flush(); 
      responseOutputStream.close(); 
      context.responseComplete(); 
1

你應該嘗試設置內容類型之前調用

response.reset(); 

。也許一個圖書館已經設置了標題,並且不同的標題會發生衝突。

+0

這是一個很好的提示,但這並沒有解決它... – bethlis