This week's book giveaway is in the OO, Patterns, UML and Refactoring forum.
We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line!
See this thread for details.
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

Send PDF file to browser for display

Meng Tan
Ranch Hand

Joined: Jan 20, 2001
Posts: 115
Does anyone know how to send a PDF file in byte[] to the browser?
In doGet() :
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];
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: 17035

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.

An IDE is no substitute for an Intelligent Developer.
Meng Tan
Ranch Hand

Joined: Jan 20, 2001
Posts: 115
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.
I’ve looked at a lot of different solutions, and in my humble opinion Aspose is the way to go. Here’s the link:
subject: Send PDF file to browser for display
It's not a secret anymore!