File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Servlets and the fly likes Send PDF file to browser for display Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Servlets
Bookmark "Send PDF file to browser for display" Watch "Send PDF file to browser for display" New topic
Author

Send PDF file to browser for display

Meng Tan
Ranch Hand

Joined: Jan 20, 2001
Posts: 115
Hi,
Does anyone know how to send a PDF file in byte[] to the browser?
In doGet() :
res.setContentType("application/pdf");
OutputStream out = res.getOutputStream();
byte[] pdf; //PDF file obtained somewhere
byte[] buf = new byte[4 * 1024];
int i = 0;
while (i < pdf.length) {
int j = 0;
for (j = 0; (j < 4 * 1024) && (i < pdf.length); j++) {
buf[j] = b[i];
i++;
}
out.write(buf, 0, j);
}
The browser does not seem to displat the PDF.
What's wrong.
Please advise.
Tim Holloway
Saloon Keeper

Joined: Jun 25, 2001
Posts: 16305
    
  21

If the browser is Netscape, there's a well-known problem about PDF's not displaying unless you send a Content-length header with the exact size of the PDF in bytes.
Without the Content-length header a blank document will display, but if you save it as a file, then open the file from the local drive, you will be able to read it.


Customer surveys are for companies who didn't pay proper attention to begin with.
Meng Tan
Ranch Hand

Joined: Jan 20, 2001
Posts: 115
Hi,
I m using IE6.
Is it OK when I didnt send the Content-length header at all?
Actually the browser only display the PDF only when I do a reload again.
So everytime I have to enter the URL, press enter and when it displays a blank page, I have to hit F5 again to get the PDF shown.
I believe this should be a common problem faced because the PDF byte[] stream is dynamically generated after processing by the Servlet.
Please advise.
Thanks!
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Send PDF file to browser for display