2016-11-21 71 views
0

我想在我的應用程序的瀏覽器中打開一個空白的PDF。我正在使用Spring Web模型 - 視圖 - 控制器(MVC)框架。Spring MVC - 在瀏覽器中打開一個空白PDF

下面的代碼

@Override 
     public ModelAndView handleRequest(HttpServletRequest request, 
       HttpServletResponse response) throws Exception { 
    byte[] data = "No file attached".getBytes(); 
    String fileName = "NofileFound.pdf"; 
      response.setHeader("Content-Disposition","attachment; filename="+fileName); 
      response.setContentType("application/pdf");   
      OutputStream out = response.getOutputStream();  

Document document = new Document();   
      PdfWriter writer = PdfWriter.getInstance(new Document(), new FileOutputStream("NofileFound.pdf")); 
      document.open(); 
      document.add(new Paragraph("test")); 
      document.close(); 
      writer.close(); 

      ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); 
      PdfWriter.getInstance(document, byteArrayOutputStream);   
      data = byteArrayOutputStream.toByteArray(); 

      out.write(data); 
      out.flush(); 
      out.close();   
      return null; 
    } 

但是當我打開我得到這個錯誤的文件:

not a supported file type 
+1

你不能讓空白的PDF這樣。你必須使用iText,PDFBox等第三種庫。 –

+0

刪除行response.setHeader(「Content-Disposition」,「attachment; filename =」+ fileName); –

+0

@YWWin - 你確定你的解決方案可行嗎?我懷疑! –

回答

0
@Override 
     public ModelAndView handleRequest(HttpServletRequest request, 
       HttpServletResponse response) throws Exception { 

    response.setContentType("application/pdf"); 
    Document document = new Document(); 
    PdfWriter.getInstance(document, response.getOutputStream()); 
    document.open(); 
    document.add(new Paragraph("empty pdf")); 
    document.close(); 

    return null 
}