How to get PDF content (from Spring MVC controller method) in a new window

I am new to Spring MVC, but I am impressed with its capabilities.

I am using 3.1.0-RELEASE, and I have to show the PDF in response to the form: form submission.

Here is the (small) code I wrote in the controller:

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

This code sends the PDF [] byte back to the original window.

How can I get the PDF file in a separate window so that I can still have the original browser window to display other content? The best way would be to show the PDF using the client's PDF file viewer (Adobe Reader, FoxIt, etc.), but I would be fine if the PDF appears in a separate browser window.

EDIT: I decided to set Content-Disposition so that the browser opens a save / open window where the user can open Adobe (with the loss of the main page of the browser).

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

Thanks everyone!

+6
source share
3 answers

Specify target="_blank" in the form:form tag that will submit your form.

+5
source

Use @RequestMapping to determine the type of response.

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

You would do this on the client side using some javascript, for example:

 <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> 

(replace with pretty jQuery-ness if you want). If you want something else to happen in the main window, just don’t return false from the onClick event, and let the regular click do whatever you want in the main window

It is not up to you if PDF files are opened in a browser window or in Adobe, this configuration is on the user's computer.

-

Also, like Spring, @ResponseBody in the void method makes no sense. @ResponseBody tells Spring to use the return type of the method as an answer. That is, you will return the byte[] method from the method and let Spring deal with turning it into a servlet response. Instead of writing the answer directly inside the method

0
source

Source: https://habr.com/ru/post/909122/


All Articles