gpt4 book ai didi

java - 阅读 PDF 文件并使用 iText 提供下载

转载 作者:行者123 更新时间:2023-12-01 15:17:29 29 4
gpt4 key购买 nike

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

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

最佳答案

内容类型应为“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();

关于java - 阅读 PDF 文件并使用 iText 提供下载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11433228/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com