Reputation: 5732
How can I read a local PDF file and offer it as a download in the browser with iText? This is what I tried, but the file always says:
Adobe Reader could not open "xxx.pdf" because it is either not a supported file type or because the file has been damaged (for example, it was sent as an email attachement and wasn't correclty decoded).
PdfReader reader = new PdfReader(filename);
byte[] streamBytes = reader.getPageContent(1);
response.setContentType("application/force-download");
response.setCharacterEncoding("UTF-8");
response.addHeader("Content-Disposition", "attachment; filename=" + filename);
BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());
bos.write(reader.getPageContent(1));
bos.write(streamBytes);
bos.flush();
bos.close();
I even made a test if iText recognizes the file as PDF, and this is the output:
System.out.println("PDF Version: " + reader.getPdfVersion());
System.out.println("Number of pages: " + reader.getNumberOfPages());
System.out.println("File length: " + reader.getFileLength());
System.out.println("Encrypted? " + reader.isEncrypted());
System.out.println("Rebuilt? " + reader.isRebuilt());
14:52:42,121 INFO [STDOUT] PDF Version: 4
14:52:42,121 INFO [STDOUT] Number of pages: 2
14:52:42,121 INFO [STDOUT] File length: 186637
14:52:42,121 INFO [STDOUT] Encrypted? false
14:52:42,121 INFO [STDOUT] Rebuilt? false
Upvotes: 0
Views: 8174
Reputation: 6479
The content type should be "application/pdf"
response.setContentType("application/pdf");
EDIT: you don't have to use PdfReader because you are not modifying the pdf, you want to do something like this:
FileInputStream baos = new FileInputStream("c:\\temp\\test.pdf");
response.setHeader("Expires", "0");
response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
response.setHeader("Pragma", "public");
response.setContentType("application/pdf");
response.addHeader("Content-Disposition", "attachment; filename=test.pdf");
OutputStream os = response.getOutputStream();
byte buffer[] = new byte[8192];
int bytesRead;
while ((bytesRead = baos.read(buffer)) != -1) {
os.write(buffer, 0, bytesRead);
}
os.flush();
os.close();
Upvotes: 1