当前位置:网站首页>pdf导出工具类
pdf导出工具类
2022-08-08 16:24:00 【一个搬砖的农民工】
(目前只更新导出pdf表格)
导出pdf表格
1、依赖:
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.13</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext-asian</artifactId>
<version>5.2.0</version>
</dependency>
2、工具类:
import com.crunii.micro.common.exception.BusinessException;
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 javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
/** * @Filename: PdfUtils * @Author: sheng.wanping * <li>Date: 2022/8/1 15:40</li> * <li>Version: 1.0</li> * <li>Content: create</li> */
public class PdfUtils {
// 定义全局的字体静态变量
private static Font titlefont;
private static Font textfont;
static {
try {
BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
titlefont = new Font(bfChinese, 8, Font.BOLD);
textfont = new Font(bfChinese, 8, Font.NORMAL);
} catch (Exception e) {
e.printStackTrace();
}
}
/** * 用于返回 简单列表ftp表格 * @param response * @param tableName 表名 * @param list 数据列表 * @param map 中英文map(key为标题,value为字段英文名;注意:map是有顺序的,可用LinkedHashMap) * @param <T> */
public static <T> void pdfSingleTable(HttpServletResponse response, String tableName, List<T> list, Map<String, String> map) {
// 1、从map中获取字段中文名和英文名
List<String> valueList = new ArrayList<>(); // 存表格所有数据
List<String> fieldEnList = new ArrayList<>(); // 字段英文名
for (Map.Entry<String, String> entry : map.entrySet()) {
valueList.add(entry.getKey());
fieldEnList.add(entry.getValue());
}
// 2、用反射根据字段名获取值
for (int i = 0; i < list.size(); i++) {
for (int j = 0; j < fieldEnList.size(); j++) {
Field field = null;
String strValue = "";
try {
field = list.get(i).getClass().getDeclaredField(fieldEnList.get(j));
field.setAccessible(true);
Object value = field.get(list.get(i));
if (value != null) {
if (value instanceof Date) {
strValue = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(value);
} else {
strValue = String.valueOf(value);
}
} else {
strValue = "";
}
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} finally {
valueList.add(strValue);// 字段值
}
}
}
// 3、返回pdf
try {
// 3-1.新建document对象
Document document = new Document(PageSize.A4);
// 3-2.建立一个书写器
response.setHeader("Content-Type", "application/pdf");
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(tableName + ".pdf", "UTF-8"));
ServletOutputStream out = response.getOutputStream();
PdfWriter.getInstance(document, out);
// 3-3.打开文档
document.open();
// 3-4、查询数据库数据,并存入list中
// 3-5、设置单元格宽度
List<Integer> mergeCellList = new ArrayList<>();
int idx = 0;
while (idx < (list.size() + 1) * fieldEnList.size()) {
idx++;
mergeCellList.add(1);
}
// 3-6.创建表格
PdfPTable table = new PdfPTable(fieldEnList.size());
for (int i = 0; i < mergeCellList.size(); i++) {
PdfPCell cell = new PdfPCell(); // 创建行
cell.setColspan(mergeCellList.get(i)); // 合并单元格
// 如果有合并行可以这样写 cell.setRowspan(2)
cell.setPhrase(new Phrase(valueList.get(i), textfont));
cell.setHorizontalAlignment(Element.ALIGN_CENTER);//水平居中
cell.setVerticalAlignment(Element.ALIGN_MIDDLE); //垂直居中
table.addCell(cell); // 添加单元格内容
}
// 3-7、向文档中添加内容
document.add(table);
// 3-8、关闭文档
document.close();
out.close();
}catch (Exception e){
e.printStackTrace();
throw new BusinessException("导出pdf失败");
}
}
}
3、测试代码
private static final Map<String, String> BUDGE_MAP = new LinkedHashMap<>();
static {
BUDGE_MAP.put("主设备", "mainEquipmentExpense");
BUDGE_MAP.put("天线", "aerialExpense");
BUDGE_MAP.put("电源", "powerExpense");
}
public void testPdf(HttpServletResponse response) {
List<Object> list = testDao.getData;// 查询数据列表
PdfUtils.pdfSingleTable(response, "表名", list, BUDGE_MAP);// 导出pdf表格
}
边栏推荐
- C#/VB.NET 将PDF转为PDF/X-1a:2001
- 我分析30w条数据后发现,西安新房公摊最低的竟是这里?
- Kubernetes资源编排系列之四: CRD+Operator篇
- 论文解读(soft-mask GNN)《Soft-mask: Adaptive Substructure Extractions for Graph Neural Networks》
- 有了这个开源工具后,我五点就下班了!
- 成员变量和局部变量的区别?
- 使用FastApi服务解决程序反复调试导致速度过慢的问题(以tsfresh为例)
- 急了,Mysql索引中最不容易记的三个知识点通透了
- The realization of the salary slip issuing function of WeChat public account + web background
- groovy基础学习
猜你喜欢
NFT质押挖矿分红系统开发逻辑功能介绍
Redis哨兵的配置和原理
全网首发!消息中间件神仙笔记,涵盖阿里十年技术精髓
api的封装
DASCTF部分复现
[Unity entry plan] Use the double blood bar method to control the blood loss speed of the damage area
谈谈怎么可以得到显著性图 特征图 featuremap
ImportError: numpy.core.multiarray failed to import [cv2, matplotlib, PyTorch, pyinstaller ]
2022年中国全民健身发展白皮书
promise学习笔记
随机推荐
The situation of the solution of the equation system and the correlation transformation of the vector group
在通达信开户安全不呢
GHOST工具访问数据库
redis切片集群的理解
用于视觉语言导航的自监督三维语义表示学习
Go 语言 Strconv 库常用方法
Grafana配置LDAP认证
华为云分布式缓存服务Redis开通及使用规划教程【华为云至简致远】
【软件工程之美 - 专栏笔记】40 | 最佳实践:小团队如何应用软件工程?
10分钟快速入门RDS【华为云至简致远】
方程组解的情况与向量组相关性转化【线代碎碎念】
【有奖征文 第13期】至简致远,“云”响世界,大胆秀出你的华为云技术主张,高额激励等你拿
【入门PCB】立创eda的学习
基于华为云ModelArts的水表读数识别开发实践【华为云至简致远】
leetcode 31. 下一个排列(实现next_permutation 函数)
redis设计与实现 笔记(一)
力扣207,课程表
groovy基础学习
使用 FasterTransformer 和 Triton 推理服务器加速大型 Transformer 模型的推理
成员变量和局部变量的区别?