2017-06-12 98 views
0

我需要返回一個HttpServletResponse使用iText下載帶有PDF的ZIP文件。這是我的代碼:使用PDF生成ZIP內

  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(); 

當我下載ZIP文件,這與所有的PDF文件和腐敗沒有大小......我不知道我做錯了什麼,但似乎文件沒有被實例化。

+0

嘗試使用任何文件的你的郵政編碼,然後用你的PDF,也是你的意見是錯誤的'應用程序/ zip'並不表示它是PDF :) –

回答

4

替換以下行:

PdfWriter.getInstance(document, baos); 

與這兩條線:

PdfWriter writer = PdfWriter.getInstance(document, zos); 
writer.setCloseStream(false); 

不要忘了告訴writer實例不關閉底層流,否則關閉document實例將也關閉ZipOutputStream,您將無法添加新條目。

+0

我試過了: 'java.io.IOException:Stream關閉 javax.faces.el.E​​valuationException:java.io.IOException:流關閉' 我試着刪除'zos.finish(); zos.close();'並給我同樣的錯誤。 – Jota

+0

我會更新我的答案。 –

+0

你救了我的一天。其作品。我嘗試刪除'zos.closeEntry();'並且沒有'writer.setCloseStream(false);'也工作。 感謝你。 – Jota