从SpringBoot配置文件XXXX.yml文件中读取配置路径,生成PDF批量添加至zip压缩包下载。
@Value(“${pdf.ceratePath}”)
private String ceratePath;
String zipName = “汇总统计报告”;//压缩包名称
String fileName = ceratePath +”总体报告-单位.pdf”;//文件名称
//
调用createPdfUtil生成pdf文件(具体生成PDF文件,请见另一篇博文)
itext生成pdf文件 设置pdf单元格背景颜色 隔行换色_u010953431-小妖的博客-CSDN博客
springboot itext pdf 生成pdf格式文件,pdf格式文件中添加表格,设置表格列背景颜色
https://blog.csdn.net/u010953431/article/details/125271727
List<File> fileList = new ArrayList<>();//待压缩文件集合
//将已生成文件加入待下载压缩包
FileOutputStream fileOut = new FileOutputStream(new File(ceratePath +zipName));
toZip(fileList, fileOut);//压缩成ZIP
//压缩包下载
File file = new File(ceratePath +zipName);
InputStream fis = new BufferedInputStream(new FileInputStream(ceratePath +zipName));
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
response.reset();
response.addHeader(“Content-Disposition”, “attachment;filename=” + URLEncoder.encode(zipName, “UTF-8”));
response.addHeader(“Content-Length”,”” + file.length());
OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
response.setContentType(“application/octet-stream”);
toClient.write(buffer);
toClient.flush();
toClient.close();
//删除生成的pdf文件
for(File delFile:fileList){
if(!delFile.isDirectory()){
delFile.delete();
}
}
/**
* 压缩成ZIP
* @param fileList 需要压缩的文件列表
* @param out 压缩文件输出流
* @throws RuntimeException 压缩失败会抛出运行时异常
*/
public static void toZip(List<File> fileList, OutputStream out) throws RuntimeException {
long start = System.currentTimeMillis();
ZipOutputStream zos = null;
try {
zos = new ZipOutputStream(out);
for (File srcFile : fileList) {
byte[] buf = new byte[2 * 1024];
zos.putNextEntry(new ZipEntry(srcFile.getName()));
int len;
FileInputStream in = new FileInputStream(srcFile);
while ((len = in.read(buf)) != -1) {
zos.write(buf, 0, len);
}
zos.closeEntry();
in.close();
}
long end = System.currentTimeMillis();
System.out.println(“压缩完成,耗时:” + (end – start) + ” ms”);
} catch (Exception e) {
throw new RuntimeException(“zip error from ZipUtils”, e);
} finally {
if (zos != null) {
try {
zos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}