有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

如何下载多个。java中的PDF文件

单击JSP页面上的按钮后,我尝试使用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文件正在下载,有人帮我吗


共 (1) 个答案

  1. # 1 楼答案

    你可以准备一个页面,向服务器发送多个请求,每个请求下载一份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提供更好的下载体验(进度条?)