我需要您的帮助来解决从 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/