工具类:
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import com.wlit.base.common.utils.DateUtil;
import com.wlit.base.common.utils.HttpUtils;
import com.wuwenze.poi.annotation.ExcelField;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* @author: lx
* @create: 2024-02-21 15:01
* @Description: pdf工具类
*/
public class PDFUtil {
public static <T> void generatePdf(HttpServletRequest request, HttpServletResponse response,
String folderName, String fileName, String titleName, List<T> dataList, Class dataClass) {
try {
//页面大小
Rectangle rect = new Rectangle(PageSize.A4);
//创建文档对象
Document document = new Document(rect, 60, 60, 30, 30);
File folderFile = new File(folderName);
if (!folderFile.exists()) {
folderFile.mkdirs();// 如果不存在,创建目录
}
String totalPath = folderName + File.separator + DateUtil.format(new Date(), "yyyyMMddHHmmss") + ".pdf";
//设置输出流
PdfWriter.getInstance(document, Files.newOutputStream(Paths.get(totalPath)));
document.open();
// 本地调试用这个字体
BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
Font fontTitle = new Font(bfChinese, 18, Font.BOLD, BaseColor.BLACK);
Font fontContent = new Font(bfChinese, 10, Font.NORMAL, BaseColor.BLACK);
Paragraph title = new Paragraph(titleName, fontTitle);
//居中
title.setAlignment(1);
document.add(title);
// 空一行
Paragraph emptyRow = new Paragraph(10f, " ", fontContent);
document.add(emptyRow);
// 不一定要用@ExcelField注解,自定义就行,需要规定一个参数作为表头
List<Field> fieldList = Arrays.stream(dataClass.getDeclaredFields())
.filter(field -> field.isAnnotationPresent(ExcelField.class))
.collect(Collectors.toList());
int columnNum = fieldList.size();
PdfPTable headerTable = new PdfPTable(columnNum);
headerTable.setWidthPercentage(100);
int[] headerwidths = new int[columnNum];
for (int i = 0; i < columnNum; i++) {
headerwidths[i] = 3;
}
headerTable.setWidths(headerwidths);
// 构建表格头 (根据需求修改,也可作为入参传进来)
List<String> headList = new ArrayList<>();
fieldList.forEach(field -> headList.add(field.getAnnotation(ExcelField.class).value()));
for (int i = 0; i < headList.size(); i++) {
createTableCell(headList.get(i), fontContent, headerTable);
}
// 外层循环构建行,内层循环构建列
for (int i = 0; i < dataList.size(); i++) {
for (Field field : fieldList) {
field.setAccessible(true);
String fieldData;
Object data = field.get(dataList.get(i));
if (data == null) {
fieldData = "";
} else if (field.getType() == Date.class) {
Date time = (Date) data;
fieldData = DateUtil.format(time, "yyyy-MM-dd HH:mm:ss");
} else {
fieldData = data.toString();
}
createTableCell(fieldData, fontContent, headerTable);
field.setAccessible(false);
}
}
document.add(headerTable);
document.close();
HttpUtils.download(request, fileName, totalPath, response);
} catch (DocumentException | IOException | IllegalAccessException e) {
e.printStackTrace();
throw new RuntimeException("导出PDF失败");
}
}
/**
* 创建表格单元格
*
* @param content 内容
* @param fontContent 字体
* @param headerTable 表格对象
*/
private static void createTableCell(String content, Font fontContent, PdfPTable headerTable) {
Phrase phrase = new Phrase(content, fontContent);
PdfPCell pdfCell = new PdfPCell(phrase);
pdfCell.setMinimumHeight(30);
//设置单元格样式
pdfCell.setHorizontalAlignment(Element.ALIGN_CENTER);
pdfCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
pdfCell.setBackgroundColor(new BaseColor(0xdd7e6b));
pdfCell.setBorder(0);
pdfCell.setBorderWidthTop(0.1f);
pdfCell.setBorderWidthBottom(0.1f);
pdfCell.setBorderWidthLeft(0.1f);
pdfCell.setBorderWidthRight(0.1f);
pdfCell.setBorderColorBottom(new BaseColor(220, 220, 220));
pdfCell.setBorderColorLeft(new BaseColor(220, 220, 220));
pdfCell.setBorderColorRight(new BaseColor(220, 220, 220));
pdfCell.setBorderColorTop(new BaseColor(220, 220, 220));
pdfCell.setNoWrap(false);
headerTable.addCell(pdfCell);
}
}
HttpUtils.download():
public static void download(HttpServletRequest request, String zhName, String path, HttpServletResponse response) {
try {
// path是指欲下载的文件的路径。
File file = new File(path);
// 取得文件名。
String filename = file.getName();
if(zhName != null) {
filename = zhName;
}
String encodeName = URLEncoder.encode(filename, "UTF-8");
// 以流的形式下载文件。
InputStream fis = new BufferedInputStream(new FileInputStream(path));
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
// 清空response
response.reset();
// 设置response的Header
OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
response.setContentType("application/vnd.ms-excel;charset=gb2312");
response.addHeader("Content-Disposition", "attachment;filename=" + encodeName);
response.addHeader("Content-Length", "" + file.length());
String ORIGIN = request.getHeader(HttpHeaders.ORIGIN);
response.setHeader("Access-Control-Allow-Origin", ORIGIN);
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, content-type, Accept");
toClient.write(buffer);
toClient.flush();
toClient.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}