简体   繁体   中英

Display Pdf file in browser using Servlet

I am using intellij Idea and I have saved my pdf file in resources folder. I want to display that pdf file in browser.

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>

I am using Jsp servlet and I am calling "/documentation". And my file is getting rendered but it's blank. Am I doing anything wrong?

inline Content-Disposition should be used to display the document. Replace "attachment" with "inline" :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM