首页 > 解决方案 > 如何使用 Spring Web 应用程序显示 PDF 文件

问题描述

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

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

我正在使用 Spring-Thymeleaf

谢谢!

标签: spring-mvcspring-bootthymeleaf

解决方案


我通过评论下面的行找到了解决方案

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

资源

谢谢!


推荐阅读