如何使用Spring Web应用程序显示PDF文件

时间:2018-07-12 07:39:53

标签: spring-mvc spring-boot thymeleaf

我希望在页面上显示此文件,但是此代码可直接下载

<a th:href="@{/pdf/Manjaro-User-Guide.pdf}">Show Pdf file</a>

我正在使用Spring-Thymeleaf

谢谢!

1 个答案:

答案 0 :(得分:3)

我通过注释下面的行

找到了解决方案
//response.setHeader("Content-Disposition", "attachment; filename=\"demo.pdf\"");

这是代码示例:

@GetMapping(value = "/pdf")
    public void showPDF(HttpServletResponse response) throws IOException {
        response.setContentType("application/pdf");
        //response.setHeader("Content-Disposition", "attachment; filename=\"demo.pdf\"");
        InputStream inputStream = new FileInputStream(new File(rootLocation + "/Manjaro-User-Guide.pdf"));
        int nRead;
        while ((nRead = inputStream.read()) != -1) {
            response.getWriter().write(nRead);
        }
    } 

Source

谢谢!