1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
| /**
* PDF操作工具类
*/
public class PDFUtil {
private static Logger logger = LoggerFactory.getLogger(PDFUtil.class);
public static final String PDF_FILE_SUFFIX = ".pdf";
public static Font headFont;
public static Font keyFont;
// 标题
public static Font titleFont;
// 设置字体大小
public static Font textFont;
public static final int MAX_WIDTH = 520;
static {
//中文格式
BaseFont bfChinese;
try {
// 设置中文显示
bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
headFont = new Font(bfChinese, 10, java.awt.Font.BOLD);
keyFont = new Font(bfChinese, 8, java.awt.Font.BOLD);
textFont = new Font(bfChinese, 8, Font.NORMAL);
titleFont = new Font(bfChinese, 16, Font.NORMAL);
} catch (Exception e) {
logger.error("创建pdf格式失败,异常={}", e);
throw new RuntimeException(e);
}
}
/**
* 为表格添加一个内容
*
* @param value 值
* @param font 字体
* @param align 对齐方式
* @return 添加的文本框
*/
public static PdfPCell createCell(String value, Font font, int align) {
PdfPCell cell = new PdfPCell();
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setHorizontalAlignment(align);
font.setColor(BaseColor.WHITE);
cell.setPhrase(new Phrase(value, font));
cell.setBackgroundColor(BaseColor.GRAY);
return cell;
}
/**
* 为表格添加一个内容
*
* @param value 值
* @param font 字体
* @return 添加的文本框
*/
public static PdfPCell createCell(String value, Font font) {
PdfPCell cell = new PdfPCell();
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.setPhrase(new Phrase(value, font));
return cell;
}
/**
* 为表格添加一个内容
*
* @param value 值
* @param font 字体
* @param align 对齐方式
* @param colspan 占多少列
* @return 添加的文本框
*/
public static PdfPCell createCell(String value, Font font, int align, int colspan) {
PdfPCell cell = new PdfPCell();
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setHorizontalAlignment(align);
cell.setColspan(colspan);
cell.setPhrase(new Phrase(value, font));
return cell;
}
/**
* 为表格添加一个内容
*
* @param value 值
* @param font 字体
* @param align 对齐方式
* @param colspan 占多少列
* @param boderFlag 是否有有边框
* @return 添加的文本框
*/
public static PdfPCell createCell(String value, Font font, int align, int colspan,
boolean boderFlag) {
PdfPCell cell = new PdfPCell();
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setHorizontalAlignment(align);
cell.setColspan(colspan);
cell.setPhrase(new Phrase(value, font));
cell.setPadding(3.0f);
if (!boderFlag) {
cell.setBorder(0);
cell.setPaddingTop(4.0f);
cell.setPaddingBottom(8.0f);
}
return cell;
}
/**
* 创建一个表格对象
*
* @param colNumber 表格的列数
* @return 生成的表格对象
*/
public static PdfPTable createTable(int colNumber) {
PdfPTable table = new PdfPTable(colNumber);
table.setTotalWidth(MAX_WIDTH);
table.setLockedWidth(true);
table.setHorizontalAlignment(Element.ALIGN_CENTER);
table.getDefaultCell().setBorder(1);
return table;
}
public PdfPTable createTable(float[] widths) {
PdfPTable table = new PdfPTable(widths);
try {
table.setTotalWidth(MAX_WIDTH);
table.setLockedWidth(true);
table.setHorizontalAlignment(Element.ALIGN_CENTER);
table.getDefaultCell().setBorder(1);
} catch (Exception e) {
e.printStackTrace();
}
return table;
}
public static PdfPTable createBlankTable() {
PdfPTable table = new PdfPTable(1);
table.getDefaultCell().setBorder(0);
table.addCell(createCell("", keyFont));
table.setSpacingAfter(20.0f);
table.setSpacingBefore(20.0f);
return table;
}
/**
* 提供外界调用的接口,生成以head为表头,list为数据的pdf
*
* @param fileName 文件名
* @param titleName 表单名
* @param headName 数据表头
* @param headField 对应类的属性名
* @param list 数据
*/
public static <T> File generatePDFs(String fileName, String titleName, String[] headName, String[] headField,
List<T> list) {
// 建立一个Document对象
Document document = new Document();
// 设置页面大小
document.setPageSize(PageSize.A4);
File tempFile = null;
try {
tempFile = File.createTempFile(fileName, PDF_FILE_SUFFIX);
PdfWriter.getInstance(document, new FileOutputStream(tempFile));
document.open();
} catch (Exception e) {
e.printStackTrace();
}
Class classType = list.get(0).getClass();
int colNum = headName.length;
PdfPTable table = createTable(colNum);
// 添加标题
table.addCell(createCell(titleName, titleFont, Element.ALIGN_CENTER, colNum, false));
//设置表头
for (int i = 0; i < colNum; i++) {
table.addCell(createCell(headName[i], keyFont, Element.ALIGN_CENTER));
}
for (int i = 0; i < list.size(); i++) {
T t = list.get(i);
for (int j = 0; j < colNum; j++) {
//获得get方法,getName,getAge等
String getMethodName = "get" + headField[j].substring(0, 1).toUpperCase() + headField[j].substring(1);
try {
//通过反射获得相应的get方法,用于获得相应的属性值
Method method = classType.getMethod(getMethodName, new Class[]{});
logger.debug(getMethodName + ":" + method.invoke(t, new Class[]{}) + ",");
//添加数据
table.addCell(createCell(method.invoke(t, new Class[]{}).toString(), textFont));
} catch (Exception e) {
logger.error("属性设值错误:入参={},异常={}", JSON.toJSONString(t), e);
throw new RuntimeException(e);
}
}
}
try {
//将表格添加到文档中
document.add(table);
} catch (Exception e) {
logger.error("");
throw new RuntimeException(e);
}
//关闭流
document.close();
return tempFile;
}
/**
* 构建行程单PDF文件
* @param date 构建日期
* @param phone 手机号
* @param baseTripInfos 行程信息
* @param outputStream 输出流
*/
public static void createPDFFile(Date date, String phone, List<BaseTripInfo> baseTripInfos, OutputStream outputStream) {
String[] header = new String[]{"序号", "出站时间", "入站站点", "出站站点", "金额(元)"};
int[] width = new int[]{20, 45, 35, 35, 35};
Document document = null;
try {
// 建立一个Document对象
document = new Document();
// 设置页面大小
document.setPageSize(PageSize.A4);
PdfWriter.getInstance(document, outputStream);
document.open();
// 设置列以及列宽度
PdfPTable table = PDFUtil.createTable(header.length);
table.setWidths(width);
// 添加标题以及空行
table.addCell(PDFUtil.createCell("广州地铁—行程单", PDFUtil.titleFont, Element.ALIGN_CENTER, header.length, false));
table.addCell(PDFUtil.createCell(" ", PDFUtil.titleFont, Element.ALIGN_CENTER, header.length, false));
// 设置申请日期以及行程起止日期
table.addCell(PDFUtil.createCell("申请时间:" + cn.hutool.core.date.DateUtil.format(date, "yyyy-MM-dd"), PDFUtil.textFont, Element.ALIGN_LEFT, 2, false));
table.addCell(PDFUtil.createCell("行程人手机号:" + phone, PDFUtil.textFont, Element.ALIGN_LEFT, 2, false));
// 计算该行程单总金额
double totalAmount = 0;
for (BaseTripInfo baseTripInfo : baseTripInfos) {
totalAmount += Double.parseDouble(baseTripInfo.getPrice());
}
table.addCell(PDFUtil.createCell("共" + baseTripInfos.size() + "笔行程, 合计 " + NumberUtil.round(totalAmount, 2).toString() + "元",
PDFUtil.textFont, Element.ALIGN_LEFT, header.length, false));
// 设置表头
for (String headName : header) {
table.addCell(PDFUtil.createCell(headName, PDFUtil.keyFont, Element.ALIGN_CENTER));
}
for (int i = 0; i < baseTripInfos.size(); i++) {
// 序号
table.addCell(createTextCell(String.valueOf(i + 1)));
// 出站时间
table.addCell(createTextCell(baseTripInfos.get(i).getExitDate() == null ? "" :
baseTripInfos.get(i).getExitDate()));
// 进站站点
table.addCell(createTextCell(baseTripInfos.get(i).getEnterStation() == null ? "" :
baseTripInfos.get(i).getEnterStation()));
// 出站站点
table.addCell(createTextCell(baseTripInfos.get(i).getExitStation() == null ? "" :
baseTripInfos.get(i).getExitStation()));
// 扣费金额
double price = Double.parseDouble(baseTripInfos.get(i).getPrice());
table.addCell(createTextCell(NumberUtil.round(price, 2).toString()));
}
//将表格添加到文档中
document.add(table);
} catch (DocumentException e) {
logger.error("Document添加PdfWriter实例失败", e);
} finally {
//关闭流
if (document != null) {
document.close();
}
}
}
private static PdfPCell createTextCell(String value) {
return PDFUtil.createCell(value, PDFUtil.textFont);
}
}
|