Is it possible to create a StreamedContent List?

Viewed 381

I need to create a list of .pdf files and wrapp it all in one zip file using org.primefaces.model.StreamedContent. Is it possible??? This is my general idea:

    private StreamedContent fileDownload;
    private ArrayList<StreamedContent> filesDownload;
     for (Cobranca boleto : cob) {
        this.boletoPDF = null;
        TndFabricaBoletoWrapper wrapper = new TndFabricaBoletoWrapper();
    
        wrapper = this.cobrancaBusiness.processarBoleto(boleto, wrapper);
        wrapper.setDownload(true);
    
        JBoleto jBoleto = TndFabricaJBoleto.getJBoleto(wrapper);
        jBoleto.addBoleto();
    
        this.boletoPDF = jBoleto.closeBoleto();
    
        File anexo = File.createTempFile("Boleto", ".pdf");
        Arquivo.salvarArquivo(anexo, this.boletoPDF);
    
        byte[] arq = Arquivo.zipByte(anexo, 9);
    
        this.fileDownload = new DefaultStreamedContent(new ByteArrayInputStream(arq), "application/zip", "Boleto");
        this.filesDownload.add(this.fileDownload);
}
((DefaultStreamedContent) this.filesDownload).setName("Boleto" + ".zip"); //this is where the download action usually happens... But the (DefaultStreamdContent) cannot be cast to an ArrayList...
1 Answers

What you need to do is get a byte-array of every PDF-Content, add this to a zip-File and then produce a StreamedContent of this Zip-File.
Supposing you have a List<byte[]> with all your PDF-Contents, it could be something like this:

public StreamedContent getZipDownload(List<byte[]> contentList){
    StreamedContent result = null;
    
    try {

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ZipOutputStream zipOut = new ZipOutputStream(baos);
        for (int i = 0; i < contentList.size(); i++) {
            String name = "" + i + ".pdf";

            zipOut.putNextEntry(new ZipEntry(name));
            zipOut.write(contentList.get(i));
            zipOut.closeEntry();

        }

        zipOut.finish();
        zipOut.close();
        result = DefaultStreamedContent.builder()
                    .name("pdfFiles.zip")
                    .contentType("application/octet-stream")
                    .stream(() -> new ByteArrayInputStream(baos.toByteArray())).build();
    } catch (IOException e) {
        LOGGER.log(Level.WARNING, "Download failed, error in Zip Creation", e);
    }

    return result;
}
Related