阅读PDF文件并使用iText下载 [英] Read PDF file and offer it as download with iText

查看:183
本文介绍了阅读PDF文件并使用iText下载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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:

Adob​​e Reader无法打开xxx.pdf,因为它不是受支持的文件类型或者因为文件已被损坏(例如,它是作为电子邮件附件发送的,并且未经过相关解码)。

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

我甚至做过测试,如果iText将文件识别为PDF,这就是输出:

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


推荐答案

内容类型应为application / pdf

The content type should be "application/pdf"

  response.setContentType("application/pdf");

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

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

这篇关于阅读PDF文件并使用iText下载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆