Search code examples
jsf-2jasper-reportsoutputstreamzipoutputstream

How to put two jasperReports in one zip file to download?


public String generateReport()    {
 try

            {

                final FacesContext facesContext = FacesContext.getCurrentInstance();
                final HttpServletResponse response = (HttpServletResponse) facesContext.getExternalContext().getResponse();
                response.reset();
                response.setHeader("Content-Disposition", "attachment; filename=\"" + "myReport.zip\";");
                final BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());
                final ZipOutputStream zos = new ZipOutputStream(bos);

                for (final PeriodScale periodScale : Scale.getPeriodScales(this.startDate, this.endDate))
                {
                    final JasperPrint jasperPrint = JasperFillManager.fillReport(
                        this.reportsPath() + File.separator + "periodicScale.jasper",
                        this.parameters(this.reportsPath(), periodScale.getScale(),
                            periodScale.getStartDate(), periodScale.getEndDate()),
                        new JREmptyDataSource());

                    final byte[] bytes = JasperExportManager.exportReportToPdf(jasperPrint);
                    response.setContentLength(bytes.length);

                    final ZipEntry ze = new ZipEntry("periodicScale"+ periodScale.getStartDate() + ".pdf"); // periodicScale13032015.pdf for example
                    zos.putNextEntry(ze);
                    zos.write(bytes, 0, bytes.length);
                    zos.closeEntry();
                }
                zos.close();
                facesContext.responseComplete();
            }
            catch (final Exception e)
            {
                e.printStackTrace();
            }

            return "";
}

This is my action method in the managedBean which is called by the user to print a JasperReport, but when I try to put more than one report inside the zip file it's not working.

getPeriodScales are returning two objects and JasperFillManager.fillReport is running correctly as the reports print when I just generate data for one report, when I try to stream two reports though and open in WinRar only one appears and I get an "unexpedted end of archive", in 7zip both appear but the second is corrupted.

What am I doing wrong or is there a way to stream multiple reports without zipping it?


Solution

  • I figured out what was, I was setting the contentLenght of the response with bytes.length size, but it should be bytes.length * Scale.getPeriodScales(this.startDate, this.endDate).size()