0

如何阅读本地 PDF 文件并将其作为 iText 在浏览器中的下载提供?这是我尝试过的,但文件总是说:

Adobe Reader 无法打开“xxx.pdf”,因为它不是受支持的文件类型或文件已损坏(例如,它作为电子邮件附件发送并且未正确解码)。

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

如果 iText 将文件识别为 PDF,我什至进行了测试,这是输出:

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
4

1 回答 1

1

内容类型应为“application/pdf”

  response.setContentType("application/pdf");

编辑:你不必使用PdfReader因为你没有修改 pdf,你想做这样的事情:

             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();
于 2012-07-11T13:06:17.600 回答