2013-09-25 64 views
4

我在做一個JSP站點,我需要顯示PDF文件。 我有web服務的PDF文件的字節數組,我需要在HTML中顯示該字節數組作爲PDF文件。我的問題是如何將該字節數組轉換爲PDF並在新選項卡中顯示該PDF。將字節數組轉換爲PDF並在JSP頁面中顯示

回答

1

不幸的是,你不會告訴我們你使用的是什麼技術。

使用Spring MVC,使用@ResponseBody爲您的控制器方法的註釋,並簡單地返回字節像這樣:

@ResponseBody 
@RequestMapping(value = "/pdf/shopping-list.pdf", produces = "application/pdf", method=RequestMethod.POST) 
public byte[] downloadShoppingListPdf() { 
    return new byte[0]; 
} 

打開一個新標籤是具有在HTML中處理不相關的事情。

+0

IAM使用Hibernate和jsp,怎麼能我在jsp – abhi

3

使用輸出流將這些字節保存在磁盤上。

FileOutputStream fos = new FileOutputStream(new File(latest.pdf)); 

//create an object of BufferedOutputStream 
bos = new BufferedOutputStream(fos); 

byte[] pdfContent = //your bytes[] 

bos.write(pdfContent); 

然後發送它的鏈接到客戶端從那裏打開。 像http://myexamply.com/files/latest.pdf

3

更好的方法是使用一個servlet這一點,因爲你不希望呈現一些HTML,但要傳輸的字節[]:

public class PdfStreamingServlet extends HttpServlet { 
    private static final long serialVersionUID = 1L; 

    @Override 
    protected void doGet(final HttpServletRequest request, 
     final HttpServletResponse response) throws ServletException, 
     IOException { 
     processRequest(request, response); 
    } 

    public void processRequest(final HttpServletRequest request, 
     final HttpServletResponse response) throws ServletException, 
     IOException { 

     // fetch pdf 
     byte[] pdf = new byte[] {}; // Load PDF byte[] into here 
     if (pdf != null) { 
      String contentType = "application/pdf"; 
      byte[] ba1 = new byte[1024]; 
      String fileName = "pdffile.pdf"; 
      // set pdf content 
      response.setContentType("application/pdf"); 
      // if you want to download instead of opening inline 
      // response.addHeader("Content-Disposition", "attachment; filename=" + fileName); 
      // write the content to the output stream 
      BufferedOutputStream fos1 = new BufferedOutputStream(
       response.getOutputStream()); 
      fos1.write(ba1); 
      fos1.flush(); 
      fos1.close(); 
     } 
    } 
} 
+0

中執行那個動作URL url1 = new URL(url);爲什麼這樣設置 - byte [] ba1 = new byte [1024]; – abhi

+0

你不需要URL,這是我用於別的東西的一些代碼,我忘了刪除它。至於byte [],這是BufferedOutputStream的Buffer。 –

相關問題