Java Spring MVC display PDF in browser

2020-07-17 14:42发布

问题:

How do I force the browser to display the pdf instead of downloading ? Here is the controller

 @RequestMapping(value = "/preview.pdf", method = RequestMethod.GET)
protected String preivewSection(      
    HttpServletRequest request,
        HttpSession httpSession,
    HttpServletResponse response) {
    try {
        byte[] documentInBytes = getDocument();         
        response.setHeader("Content-Disposition", "inline; filename=\"report.pdf\"");
        response.setDateHeader("Expires", -1);
        response.setContentType("application/pdf");
        response.setContentLength(documentInBytes.length);
        response.getOutputStream().write(documentInBytes);
    } catch (Exception ioe) {
    } finally {
    }
    return null;
}

回答1:

If you remove this line, the pdf will open in the browser itself.

response.setHeader("Content-Disposition", "inline; filename=\"report.pdf\"");


回答2:

It looks like the above mentioned controller is all we need from the server side, the problem is the browser doesn't support viewing PDF files.



回答3:

Use this google chrome browser not support preview It.

response.setHeader("Content-Disposition", "attachment; filename=" + file.getName());

But I changed this header as :

response.setHeader("Content-Disposition", "inline; filename=" + file.getName());

preview ok !

Because inline (default value, indicating it can be displayed inside the Web page, or as the Web page)

https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition