【问题标题】:Primefaces InputStream generating corrupted PDF in fileDownloadPrimefaces InputStream 在 fileDownload 中生成损坏的 PDF
【发布时间】:2015-07-16 13:42:47
【问题描述】:

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

Adobe Reader 无法打开文件“sample.pdf”,因为它是 文件类型不受支持或已损坏

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>

那么如何解决这个问题

【问题讨论】:

    标签: java jsf pdf primefaces inputstream


    【解决方案1】:

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

    【讨论】:

    • 感谢您的帮助。应该关闭 OutputStream 以及文档,
    猜你喜欢
    • 2022-10-05
    • 1970-01-01
    • 2011-09-16
    • 2013-01-10
    • 2016-01-25
    • 1970-01-01
    • 1970-01-01
    • 2014-01-10
    • 2016-03-15
    相关资源
    最近更新 更多