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文件正在下载,有人帮帮我吗?
答案 0 :(得分:0)
可以准备一个页面,它向服务器发出多个请求,每个下载一个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提供更好的下载体验(进度条?)。