itext 7批量生成pdf文件并以压缩包形式下载
引入jar
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext7-core</artifactId>
<version>7.0.3</version>
<type>pom</type>
</dependency>
代码实现–生成pdf文件
/**
* 生成pdf文件
* @return java.io.ByteArrayOutputStream
* @date 2023/6/25 16:29
* @author fyh
**/
private ByteArrayOutputStream exportPdf(){
try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
PageSize pageSize = PageSize.A4.rotate();
PdfDocument pdfDoc = new PdfDocument(new PdfWriter(out));
Document doc = new Document(pdfDoc, pageSize);
float[] f = new float[]{0.01f};
Table table = new Table(UnitValue.createPercentArray(f));
table.setWidth(745);
Cell cell = new Cell();
//设置表格边框颜色
cell.setBorder(new SolidBorder(new DeviceRgb(0xFFF, 0xFFF, 0xFFF),3));
PdfFont font = PdfFontFactory.createFont("STSong-Light", "UniGB-UCS2-H",true);
//背景图上写入汉字
Paragraph p = new Paragraph("努尔哈赤")
.setFont(font).setFontSize(13f).setFontColor(DeviceGray.BLACK);
//写入汉字坐标
p.setFirstLineIndent(140f);
p.setFixedLeading(418f);
cell.add(p);
//获取表格背景图
URL resource = this.getClass().getClassLoader().getResource("honour.png");
assert resource != null;
Image img = new Image(ImageDataFactory.create(resource.getPath()));
cell.setNextRenderer(new ImageBackgroundCellRenderer(cell, img));
cell.setHeight(590 * img.getImageHeight() / img.getImageWidth());
table.addCell(cell);
doc.add(table);
doc.close();
out.flush();
return out;
} catch (Exception e) {
log.error(e.getMessage(),e);
}
return new ByteArrayOutputStream();
}
代码实现–生成并下载压缩包
/**
*生成压缩包
* @date 2023/6/25 16:02
* @author fyh
**/
private void downLoadZip(List<Map<String,Object>> fileList, HttpServletResponse httpResponse){
try(ZipOutputStream zipOutputStream = new ZipOutputStream(httpResponse.getOutputStream())) {
//下载压缩包
httpResponse.setContentType("application/zip");
httpResponse.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode("附件.zip", "UTF-8"));
// 创建 ZipEntry 对象
for (Map<String,Object> map:fileList){
ZipEntry zipEntry = new ZipEntry((String) map.get("fileName"));
zipOutputStream.putNextEntry(zipEntry);
zipOutputStream.write((byte[]) map.get("outByte"));
}
} catch (IOException e) {
log.error(e.getMessage(),e);
}
}
controller层 代码实现
/**
* 导出压缩包
* @date 2023/6/25 16:15
* @author fyh
**/
@GetMapping(value = "downLoadZip")
public void downLoadZip2(HttpServletResponse httpServletResponse){
//生成的文件
ByteArrayOutputStream byteArrayOutputStream = exportPdf();
Map<String,Object> excelOut = new HashMap<>();
excelOut.put("fileName","努尔哈赤.pdf");
excelOut.put("outByte",byteArrayOutputStream.toByteArray());
List<Map<String,Object>> fileList = new ArrayList<>();
fileList.add(excelOut);
//文件压缩为zip
downLoadZip(fileList,httpServletResponse);
}
实现效果图