2012-02-22 59 views
6

我是Spring MVC的新手,但對這些功能印象頗深。如何從新窗口中獲得PDF內容(由Spring MVC控制器方法提供)

我使用的是3.1.0-RELEASE,我必須顯示一個PDF以迴應表單:表單提交。

這裏是(小)代碼我在控制器中寫道:

@RequestMapping(value = "new_product", method = RequestMethod.POST, params = "print") 
@ResponseBody 
public void saveAndShowPDF(ModelMap map, ShippingRequestInfo requestInfo, HttpServletRequest request, HttpServletResponse httpServletResponse) throws IOException { 
    saveProductChanges(map, requestInfo, request, httpServletResponse); 
    httpServletResponse.setContentType("application/pdf"); 
    byte[] pdfImage = productService.getPDFImage(requestInfo.getRequestId()); 
    httpServletResponse.getOutputStream().write(pdfImage); 
} 

此代碼發送PDF字節[]回到原來的窗口。

如何將PDF顯示在單獨的窗口中,以便我仍然可以使原始瀏覽器窗口顯示其他內容?最好的辦法是使用客戶端PDF查看程序(Adobe Reader,FoxIt等)顯示PDF,但是如果PDF顯示在單獨的瀏覽器窗口中,我會很好。

編輯 我決定將內容處置,以使瀏覽器彈出一個保存/打開對話框,用戶可以在打開的Adobe(與丟失主瀏覽器頁面)

httpServletResponse.setHeader("Content-Disposition","attachment;filename=cool.pdf"); 

謝謝大家!

回答

5

在提交表單的form:form標記中指定target="_blank"

+0

target =「_ blank」將(希望)在單獨的窗口中顯示PDF。如果我讓控制器方法返回一個字符串,我可以讓原始窗口呈現一個新頁面(以及新窗口中的PDF)? – 2012-02-22 19:37:48

+1

Darn ...我不能使用target =「__ blank」,因爲表單有多個type =「submit」按鈕,我只有這個按鈕需要在單獨的窗口中進行響應(PDF)。 我決定設置Content-Disposition來帶一個保存/打開框,用戶可以打開Adobe(丟失主瀏覽器頁面) httpServletResponse.setHeader(「Content-Disposition」,「attachment; filename = product.pdf 「); – 2012-02-22 20:07:19

0

你會做在客戶端與一些JavaScript例如,:

<a href="http://www.myWebApp.com/somePdf.pdf" onclick="window.open('http://www.myWebApp.com/somePdf.pdf'); return false;" target="_blank">My Super Awesome Docment</a> 

(以代替根據需要漂亮的jQuery岬)如果你想要別的東西在主窗口發生只是不在onClick事件中返回false,並讓常規點擊做你希望在主窗口中發生的任何事情

如果PDF在瀏覽器窗口或Adobe中打開,這不是由你自己決定的,用戶的電腦。

-

而且,就像春天的事情,@ResponseBodyvoid方法沒有任何意義。 @ResponseBody告訴spring使用方法的返回類型作爲響應。也就是說,您將返回方法中的byte[],並讓Spring將其轉換爲servlet響應。而不是直接在方法中寫回應

1

使用@RequestMapping產生來定義響應類型。

@RequestMapping(value = doc/{docId}, method = RequestMethod.GET, produces = "application/pdf") 
@ResponseBody 
public byte[] getDocument(@PathVariable("docId") String docId) throws Exception 
{ 
    return service.getDocument(docId); 
} 
相關問題