简体   繁体   中英

how to download mulitple .PDF files in java

OnClick of button on JSP Page, I am trying to download more than one pdf one by one using java code but not able to done it and Using Following snippet code for the same

     Document document[]=  new Document[20];
             httpServletResponse.setHeader("Content-Disposition",
                "attachment;filename=welcome.pdf");
                httpServletResponse.setContentType("application/pdf");
                try{
                    for(int i=0;i<3;i++)
                    {
                    System.out.println(i);
                    document[i]=new Document();
                    PdfWriter.getInstance(document[i], httpServletResponse.getOutputStream());
                    document[i].open();
                    document[i].add(new Paragraph("Hello Prakash"));
                    document[i].add(new Paragraph(new Date().toString()));
                    document[i].close();
                    } 
                     }catch(Exception e){
                    e.printStackTrace();
                }

It is not working and alaways only one .PDF file is downloading, anyone help me out?

One could prepare a page, that does multiple requests to the server, every one which of downloads a PDF. This is not so nice a user experience.

I would use a zip file containing all PDFs:

response.setContentType("application/zip"); // application/octet-stream
response.setHeader("Content-Disposition", "inline; filename=\"all.zip\"");
try (ZipOutputStream zos = new ZipOutputStream(response.getOutputStream())) {
     for (int i = 0; i < 3; i++) {
         ZipEntry ze = new ZipEntry("document-" + i + ".pdf");
         zos.putNextEntry(ze);

         // It would be nice to write the PDF immediately to zos.
         // However then you must take care to not close the PDF (and zos),
         // but just flush (= write all buffered).
         //PdfWriter pw = PdfWriter.getInstance(document[i], zos);
         //...
         //pw.flush(); // Not closing pw/zos

         // Or write the PDF to memory:
         ByteArrayOutputStream baos = new ...
         PdfWriter pw = PdfWriter.getInstance(document[i], baos);
         ...
         pw.close();
         byte[] bytes = baos.toByteArray();
         zos.write(baos, 0, baos.length);

         zos.closeEntry();
     }
}

Just read, you cannot use ZIP download.

Maybe you might use HTML5 offering a nicer download experience (progress bars?).

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM