如何将PDF内容(从Spring MVC控制器方法提供)显示在新窗口中

我是Spring MVC的新手,但我对它的function印象深刻。

我正在使用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 byte []发送回原始窗口。

如何让PDF显示在单独的窗口中,以便我仍然可以使用原始浏览器窗口显示其他内容? 最好的方法是使用客户端PDF视图程序(Adobe Reader,FoxIt等)显示PDF,但我可以将PDF显示在单独的浏览器窗口中。

编辑:我决定设置Content-Disposition,以便浏览器显示一个保存/打开框,用户可以打开Adobe(丢失主浏览器页面)。

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

感谢大家!

form:form指定target="_blank" form:form提交表单。

使用@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); } 

您可以在客户端使用一些javascript执行此操作,例如:

 My Super Awesome Docment 

(根据需要替换为漂亮的jQuery-ness)如果你想在主窗口中发生其他事情,只是不要从onClick事件返回false,并让常规点击做你想在主要事件中发生的任何事情窗口

如果PDF在浏览器窗口或Adobe中打开,这取决于您,这是用户计算机上的配置。

另外,就像Spring一样, @ResponseBodyvoid方法没有任何意义。 @ResponseBody告诉spring使用方法的返回类型作为Response。 也就是说,你将从方法返回byte[]并让spring处理将其转换为servlet响应。 而不是直接在方法中编写响应