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

Primefaces InputStream generating corrupted PDF in fileDownload

我需要您的帮助来解决从 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() 吗?如果您将文件保存到硬盘驱动器而不是将其发送到浏览器,文件是否也已损坏?