Reputation: 55
I'm trying to send a static pdf (which is on the system) to a outputStream in order to display a save-as-dialog. But when the Pdf is opened only an empty page is displayed:
here's the code which should display the dialog:
//get the pdf:
String pathToPdf = servletContext.getRealPath("/pdfFiles/dealer.pdf");
File pdfFile = new File (pathToPdf);
response.setContentType("application/pdf");
response.addHeader("Content-Disposition", "attachment; filename=dealer.pdf");
response.setContentLength((int) pdfFile.length());
FileInputStream fileInputStream = new FileInputStream(pdfFile);
OutputStream responseOutputStream = response.getOutputStream();
int bytes;
while ((bytes = fileInputStream.read()) != -1) {
responseOutputStream.write(bytes);
}
responseOutputStream.flush();
responseOutputStream.close();
The Stacktrace says the following:
WARNING: Invalid HTML; bare lessthan sign found at line 4. Surroundings: '<
/Creator (Apache FOP Version'.
WARNING: Invalid HTML; bare lessthan sign found at line 5. Surroundings: '/Creator (Apache FOP Version 1'.
WARNING: Invalid HTML; bare lessthan sign found at line 11. Surroundings: '<
/N 3
/Length 11 0 R
/F'.
WARNING: Invalid HTML; bare lessthan sign found at line 12. Surroundings: '/N 3
/Length 11 0 R
/Filte'.
WARNING: Invalid HTML; bare lessthan sign found at line 18. Surroundings: '?s??e???'?9???`??2?&c?tI?'.
WARNING: Invalid tag found: unexpected input while looking for attr name or '/>' at line 25. Surroundings: '?+?U?Zp'pWp?????????e?F|'.
WARNING: Invalid HTML; bare lessthan sign found at line 68. Surroundings: '<
/Name /Im1
/Type /XObjec'.
WARNING: Invalid HTML; bare lessthan sign found at line 69. Surroundings: '/Name /Im1
/Type /XObject
'.
WARNING: Invalid tag found: unexpected input while looking for attr name or '/>' at line 85. Surroundings: '??r??"?F?t??$??n{?q??O~??{?'.
Can anyone say what I'm missing or doing wrong? Thanks!!
Upvotes: 1
Views: 565
Reputation: 55
I had to add the following:
context.responseComplete();
So the complete code looks like this now:
response.setContentType("application/pdf");
response.setHeader("Content-Disposition", "attachment; filename=\"PdfName.pdf\"");
response.setContentLength(outStream.size());
OutputStream responseOutputStream = response.getOutputStream();
outStream.writeTo(responseOutputStream);
responseOutputStream.flush();
responseOutputStream.close();
context.responseComplete();
Upvotes: 0
Reputation: 862
You should try to call
response.reset();
before setting the content type. Maybe a library has set the headers already and the different headers would collide.
Upvotes: 1