• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Unable to open PDF file from servlet.

 
kartik reddy
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 20611
63
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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:
 
kartik reddy
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 20611
63
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What happens if you don't close responseOutputStream, but only flush it after writing the file?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic