繁体   English   中英

如何在Java中下载多个.PDF文件

[英]how to download mulitple .PDF files in java

在JSP页面上的按钮的onClick上,我试图使用Java代码一个一个地下载一个以上的pdf文件,但无法做到这一点,并且对同一代码使用以下代码段代码

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

它不起作用,仅下载一个.PDF文件,有人帮我吗?

可以准备一个页面,该页面向服务器发出多个请求,每个页面都下载PDF。 这不是很好的用户体验。

我将使用包含所有PDF的zip文件:

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

刚刚阅读,您不能使用ZIP下载。

也许您可以使用HTML5提供更好的下载体验(进度条?)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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