使用Servlet在浏览器中显示Pdf文件

时间:2017-01-13 09:41:59

标签: java pdf servlets

我正在使用intellij Idea,我已将我的pdf文件保存在资源文件夹中。我想在浏览器中显示该pdf文件。

public class GetDocumentation extends HttpServlet {
  private static final Logger log = Logger.getLogger(GetDocumentation.class);
@Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    InputStream pdf_path = this.getClass().getResourceAsStream(ApplicationProperties.getProperty("PDF_PATH"));

    resp.setContentType("application/pdf");
    resp.addHeader("Content-Disposition", "attachment; filename=Documentation.pdf");
    OutputStream responseOutputStream = resp.getOutputStream();

    byte[] buf = new byte[4096];
    int len = -1;

    while ((len = pdf_path.read(buf)) != -1) {
      responseOutputStream.write(buf, 0, len);
    }
    responseOutputStream.flush();
    responseOutputStream.close();
  }
}


<a href="/documentation">Documentation</a>

我正在使用Jsp servlet,我正在调用“/ documentation”。我的文件正在渲染,但它是空白的。我做错了吗?

1 个答案:

答案 0 :(得分:0)

inline Content-Disposition应用于显示文档。将"attachment"替换为"inline"

resp.addHeader("Content-Disposition", "inline; filename=Documentation.pdf");