aspose file tools*
The moose likes Servlets and the fly likes Unable to open PDF file from servlet. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Servlets
Bookmark "Unable to open PDF file from servlet." Watch "Unable to open PDF file from servlet." New topic
Author

Unable to open PDF file from servlet.

kartik reddy
Greenhorn

Joined: Dec 11, 2008
Posts: 9
When I am trying to open a PDF through a Servlet it is popping with an acrobat error with the message
"The file is damaged and could not be repaired"


I am using the following code to display the pdf file from the serlvet,

File pdfFile = new File(filePath);
OutputStream responseOutputStream = resp.getOutputStream();
resp.setContentType("application/pdf");
resp.setHeader("Content-disposition", "attachment;filename=\"" + file + "\"");
resp.setContentLength((int)filePath.length());
FileInputStream fileInputStream = new FileInputStream(pdfFile);
int size = fileInputStream.available();
byte[] content = new byte[size];
fileInputStream.read(content);
responseOutputStream.write(content);
responseOutputStream.flush();
fileInputStream.close();
responseOutputStream.close();


The same code works fine when the pdf contains only text content.
But it doesn't work when PDF contains text content with images.

Could anyone help me to solve this issue..
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19720
    
  20

kartik reddy wrote:fileInputStream.read(content);
responseOutputStream.write(content);

That's not the proper way to copy a file. InputStream.read(byte[]) can read fewer bytes than you intend. If that is the case the remainder of the byte[] will contain 0 bytes. This may very well be the cause of the corruption.
The solution is of course to use a loop:


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
kartik reddy
Greenhorn

Joined: Dec 11, 2008
Posts: 9
I have used while loop, but still I could able to get this issue "The file is damaged and could not be repaired" when I am trying to open a PDF through a Servlet.

If you find any alternative solution to fix this issue please let me know.

Thanks in advance..
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19720
    
  20

What happens if you don't close responseOutputStream, but only flush it after writing the file?
 
jQuery in Action, 2nd edition
 
subject: Unable to open PDF file from servlet.