java - Primefaces InputStream 在文件下载中生成损坏的 PDF

标签 java jsf pdf primefaces inputstream

我需要您的帮助来解决从 fileDownload 组件中使用的 InputStream 生成损坏的 PDF 文件的问题。我有一个使用 iText 生成的 PDF,然后将其转换为 inputStream,因此我可以将其用作 fileDownload 组件中的输入。点击下载commandButton后,我将下载文件并打开它,它会显示一条消息:

The Adobe Reader can not open the file "sample.pdf" because it is either not supported file type or it is damaged

bean 代码是:

private StreamedContent file;

public void createPdf() {
    try {
        Document doc = Document(PageSize.A4, 50, 50, 50, 50);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ByteArrayInputStream in ;
        PdfWriter writer;
        writer = PdfWriter.getInstance(doc, out);
        doc.open();
        doc.add(new Paragraph("Hello World!"));
        in = new ByteArrayInputStream(out.toByteArray());
        file = new DefaultStreamedContent(in, "application/pdf", "sample.pdf");
    } catch (Exception e) {
        e.printStackTrace();
    }
}

jsf代码是:

<p:commandButton value="Download" ajax="false"
        onclick="PrimeFaces.monitorDownload(start, stop);"
        icon="ui-icon-arrowthick-1-s" actionListener="#{pdf.createPdf}">
    <p:fileDownload value="#{pdf.file}"/>
</p:commandButton>

那么如何解决这个问题

最佳答案

在开始从 out 复制字节之前,不应该有 doc.close() 吗?如果将文件保存到硬盘而不是发送到浏览器,文件是否也会损坏?

关于java - Primefaces InputStream 在文件下载中生成损坏的 PDF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31455958/

相关文章:

java - try catch 扫描仪

java - 使用 spring 的 pom.xml 中的 Maven 错误

java - Netbeans JSF 应用程序中从未到达 javascript 文件中的断点?

jsf - p :radioButton with render rule is never rendered

java - 将参数从一种方法传递到另一种方法

java - 使用 Java 将多个 pdf 压缩为单个 zip 文件

c# - 如何在 C# 中使用与 HTML 代码相同的布局即时生成 PDF

node.js - Node 中的日期格式生成pdf

java - 使用 Spring Boot 2.4.1 启动 Eureka Client 时出错

java - 登录页面并将数据写入 CSV 文件