Read PDF file and offer it as download with iText

久未见 提交于 2020-01-06 19:56:46

问题


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

回答1:


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();


来源:https://stackoverflow.com/questions/11433228/read-pdf-file-and-offer-it-as-download-with-itext

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!