Reputation: 13
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 »</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.
Upvotes: 0
Views: 1800
Reputation: 1982
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();
Upvotes: 1