阅读PDF文件并使用iText下载

时间:2012-07-11 13:00:39

标签: java pdf itext

如何阅读本地PDF文件,并在带有iText的浏览器中下载? 这是我尝试过的,但文件总是说:

Adob​​e 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

1 个答案:

答案 0 :(得分: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();