Java 生成包含PDF的ZIP文件
我需要返回一个HttpServletResponse,以便使用iText下载一个包含PDF的ZIP文件。这是我的代码:Java 生成包含PDF的ZIP文件,java,itext,Java,Itext,我需要返回一个HttpServletResponse,以便使用iText下载一个包含PDF的ZIP文件。这是我的代码: String fileName = "Acreditaciones.zip"; ByteArrayOutputStream baos = new ByteArrayOutputStream(); ZipOutputStream zos = new ZipOutputStream(baos);
String fileName = "Acreditaciones.zip";
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ZipOutputStream zos = new ZipOutputStream(baos);
for(int i = 0; i < numAcre; i++){
zos.putNextEntry(new ZipEntry("Acreditaciones" + String.valueOf(i+1) + ".pdf"));
Document document = new Document();
PdfWriter.getInstance(document, baos);
//Abrimos el documento para insertarle contenido
document.open();
//TODO: Coger la URL de los parametros de la BD y cifrar el id del perceptor o la columna que lo identifique
//Creamos imagen con codigo QR
BarcodeQRCode barcodeQRCode2 = new BarcodeQRCode(URL + UtilsSeguridad.cifrar("80004244D"), 1000, 1000, null);
Image codeQrImage2 = barcodeQRCode2.getImage();
codeQrImage2.setAlignment(Image.RIGHT);
codeQrImage2.scaleAbsolute(70, 70);
document.add(codeQrImage2);
document.close();
zos.closeEntry();
}
zos.finish();
zos.close();
response.setHeader("Content-Disposition", "attachment; filename=\""+ fileName + "\";");
// Indicamos que es un PDF
response.setContentType("application/zip");
// El tamaño del contenido es igual al del ByteArrayOutputStream
response.setContentLength(baos.size());
// Inyectamos el ByteArrayOutputStream al ServletOutputStream
ServletOutputStream os = response.getOutputStream();
baos.writeTo(os);
os.flush();
os.close();
FacesContext.getCurrentInstance().responseComplete();
String fileName=“Acreditaciones.zip”;
ByteArrayOutputStream bas=新的ByteArrayOutputStream();
ZipOutputStream zos=新ZipOutputStream(BAS);
对于(int i=0;i
当我下载ZIP文件时,所有PDF文件都会损坏,而且没有大小。。。我不知道我做错了什么,但似乎没有实例化文档。替换以下行:
PdfWriter.getInstance(document, baos);
用这两条线:
PdfWriter writer = PdfWriter.getInstance(document, zos);
writer.setCloseStream(false);
不要忘记告诉
编写器
实例不要关闭底层流,否则关闭文档
实例也会关闭ZipOutputStream
,您将无法添加新条目。替换以下行:
PdfWriter.getInstance(document, baos);
用这两条线:
PdfWriter writer = PdfWriter.getInstance(document, zos);
writer.setCloseStream(false);
不要忘了告诉
编写器
实例不要关闭底层流,否则关闭文档
实例也会关闭ZipOutputStream
,您将无法添加新条目。尝试使用任何文件的邮政编码,然后使用PDF,另外,您的评论是错误的应用程序/zip
并不表示它是PDF:)请尝试使用任何文件的邮政编码,然后使用PDF,另外,您的评论是错误的application/zip
并不表示它是PDF:)我尝试过:java.io.IOException:Stream closed javax.faces.el.EvaluationException:java.io.IOException:Stream closed
我尝试过删除zos.finish();zos.close()代码>并给我同样的错误。你救了我一天。这很有效。我尝试删除zos.closeEntry()代码>并且在没有writer.setCloseStream的情况下也工作(false)代码>。谢谢。我正在使用本文建议的代码。我可以让一切正常工作,除了zip中的最后一个文件大小为0。无论要压缩的文件列表是2还是10,都会发生这种情况。我尝试过:java.io.IOException:Stream closed javax.faces.el.EvaluationException:java.io.IOException:Stream closed
我尝试过删除zos.finish();zos.close()代码>并给我同样的错误。你救了我一天。这很有效。我尝试删除zos.closeEntry()代码>并且在没有writer.setCloseStream的情况下也工作(false)代码>。谢谢。我正在使用本文建议的代码。我可以让一切正常工作,除了zip中的最后一个文件大小为0。无论要压缩的文件列表是2还是10,都会发生这种情况。