简体   繁体   中英

PDF file not opening in browser using servlet and jsp

I am trying to open a pdf file in my browser window using servlet and jsp. With a button click on jsp i am calling a servlet and then via that servlet trying to display the pdf file on the browser.

Here's the code with what i am trying:

The jsp file:

<form action="DisplayPDF" method="post" class="register">




        <p><button type="submit" class="button">Click To Add &raquo;</button></p>


   </form>

The servlet section in doPost method:

response.setContentType("application/pdf");

    PrintWriter out = response.getWriter(); 
    response.setHeader("Content-Disposition", "inline; filename=bill.pdf");
    FileOutputStream fileOut = new FileOutputStream("D:\\Invoice\\Invoice_1094.pdf");  
    fileOut.close();
    out.close();

Kindly let me know where exactly i am doing wrong here. Thanks in advance.

What you are doing is opening an OutputStream on the file "D:\\\\Invoice\\\\Invoice_1094.pdf" and obtaining a reference to the servlet reaponse's writer, but actually never writing anything to neither of them.

I assume you want to serve the file "D:\\\\Invoice\\\\Invoice_1094.pdf" that resides on your server. For this, you have to read its contents and write them to your servlet's output stream. Please note I'm using the servlet's OutputStream and not its Writer.

response.setContentType("application/pdf");
response.setHeader("Content-Disposition", "inline; filename=bill.pdf");
OutputStream out = response.getOutputStream(); 
try (FileInputStream in = new FileInputStream("D:\\Invoice\\Invoice_1094.pdf")) {
    int content;
    while ((content = in.read()) != -1) {
        out.write(content);
    }
} catch (IOException e) {
    e.printStackTrace();
}
out.close();

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