I need to return a HttpServletResponse to download a ZIP file with PDFs inside using iText. This is my code:
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();
When I download the ZIP file, this come with all the PDFs corrupts and without size... I don't know what I'm doing wrong, but seems that the documents are not being instantiated.
Replace the following line:
PdfWriter.getInstance(document, baos);
with these two lines:
PdfWriter writer = PdfWriter.getInstance(document, zos);
writer.setCloseStream(false);
Don't forget to tell the writer
instance not to close the underlying stream, otherwise closing the document
instance will also close the ZipOutputStream
, and you won't be able to add new entries.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.