TableImageGenerator.java 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628
  1. package com.malk.mankalong.util;
  2. import com.alibaba.fastjson.JSON;
  3. import com.alibaba.fastjson.JSONArray;
  4. import com.alibaba.fastjson.JSONObject;
  5. import com.malk.mankalong.config.ImageConfig;
  6. import com.malk.mankalong.entity.dto.FieldDefinitionDTO;
  7. import java.awt.*;
  8. import java.awt.image.BufferedImage;
  9. import java.text.SimpleDateFormat;
  10. import java.util.*;
  11. import java.util.List;
  12. /**
  13. * 表格图片生成器
  14. *
  15. * <p>使用 Java AWT Graphics2D 将宜搭子表数据渲染为表格图片。</p>
  16. * <p>支持:中文字体自适应、列宽自适应、长文本自动换行、表头样式、隔行变色。</p>
  17. *
  18. * <p>JDK 1.8 兼容,无外部图片库依赖。</p>
  19. */
  20. public class TableImageGenerator {
  21. // ===== 颜色常量 =====
  22. private static final Color HEADER_BG = Color.WHITE;
  23. private static final Color HEADER_FG = Color.BLACK;
  24. private static final Color ROW_BG_EVEN = Color.WHITE;
  25. private static final Color ROW_BG_ODD = Color.WHITE;
  26. private static final Color GRID_COLOR = new Color(220, 223, 230);
  27. private static final Color TEXT_COLOR = new Color(48, 49, 51);
  28. private static final Color TITLE_COLOR = new Color(48, 49, 51);
  29. // ===== 字体候选列表(按优先级,覆盖 Windows / Linux 常见中文字体) =====
  30. private static final String[] FONT_CANDIDATES = {
  31. "Microsoft YaHei", // Windows 微软雅黑
  32. "SimHei", // Windows 黑体
  33. "SimSun", // Windows 宋体
  34. "Noto Sans CJK SC", // Linux 思源黑体
  35. "WenQuanYi Micro Hei", // Linux 文泉驿微米黑
  36. "SansSerif" // 通用回退
  37. };
  38. private final ImageConfig config;
  39. private final Font titleFont;
  40. private final Font headerFont;
  41. private final Font cellFont;
  42. public TableImageGenerator(ImageConfig config) {
  43. this.config = config;
  44. String fontName = resolveChineseFont();
  45. this.titleFont = new Font(fontName, Font.BOLD, config.getTitleFontSize());
  46. this.headerFont = new Font(fontName, Font.BOLD, config.getHeaderFontSize());
  47. this.cellFont = new Font(fontName, Font.PLAIN, config.getCellFontSize());
  48. }
  49. /**
  50. * 解析可用的中文字体
  51. */
  52. private String resolveChineseFont() {
  53. // 中文字符测试
  54. char testChar = '\u4e2d'; // "中"
  55. for (String name : FONT_CANDIDATES) {
  56. Font f = new Font(name, Font.PLAIN, 12);
  57. if (f.canDisplay(testChar)) {
  58. return name;
  59. }
  60. }
  61. return Font.SANS_SERIF;
  62. }
  63. /**
  64. * 生成表格图片
  65. *
  66. * @param title 表格标题(可为 null,如子表名称)
  67. * @param fieldDefs 字段定义列表(决定列顺序和列标题)
  68. * @param dataRows 子表原始数据(每行一个 Map)
  69. * @return 生成的 BufferedImage
  70. */
  71. public BufferedImage generate(String title,
  72. List<FieldDefinitionDTO> fieldDefs,
  73. List<Map<String, Object>> dataRows) {
  74. // 1. 准备表格数据:列标题 + 字符串化的行数据
  75. List<String> headers = new ArrayList<>();
  76. List<String> fieldIds = new ArrayList<>();
  77. for (FieldDefinitionDTO fd : fieldDefs) {
  78. headers.add(fd.getLabel());
  79. fieldIds.add(fd.getFieldId());
  80. }
  81. List<List<String>> stringRows = new ArrayList<>();
  82. for (Map<String, Object> row : dataRows) {
  83. List<String> stringRow = new ArrayList<>();
  84. for (int i = 0; i < fieldIds.size(); i++) {
  85. String fieldId = fieldIds.get(i);
  86. FieldDefinitionDTO fd = fieldDefs.get(i);
  87. Object value = row.get(fieldId);
  88. stringRow.add(formatCellValue(value, fd));
  89. }
  90. stringRows.add(stringRow);
  91. }
  92. // 2. 计算列宽
  93. int[] colWidths = calculateColumnWidths(headers, stringRows);
  94. // 3. 计算行高(考虑文本换行)
  95. int titleHeight = (title != null && !title.isEmpty()) ? config.getTitleFontSize() + 24 : 0;
  96. int[] rowHeights = calculateRowHeights(headers, stringRows, colWidths);
  97. int headerHeight = config.getRowHeight();
  98. // 4. 计算图片总尺寸
  99. int totalWidth = config.getCellPadding() * 2; // 左右边距
  100. for (int w : colWidths) {
  101. totalWidth += w;
  102. }
  103. int totalHeight = titleHeight + headerHeight;
  104. for (int h : rowHeights) {
  105. totalHeight += h;
  106. }
  107. // 确保最小尺寸
  108. totalWidth = Math.max(totalWidth, 200);
  109. totalHeight = Math.max(totalHeight, 100);
  110. // 5. 创建图片
  111. BufferedImage image = new BufferedImage(totalWidth, totalHeight, BufferedImage.TYPE_INT_RGB);
  112. Graphics2D g2d = image.createGraphics();
  113. // 抗锯齿
  114. g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
  115. g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
  116. g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
  117. // 6. 绘制背景
  118. Color bgColor = parseColor(config.getBackground(), Color.WHITE);
  119. g2d.setColor(bgColor);
  120. g2d.fillRect(0, 0, totalWidth, totalHeight);
  121. int y = 0;
  122. // 7. 绘制标题
  123. if (titleHeight > 0) {
  124. g2d.setColor(TITLE_COLOR);
  125. g2d.setFont(titleFont);
  126. FontMetrics titleFm = g2d.getFontMetrics();
  127. int titleX = config.getCellPadding();
  128. int titleY = y + (titleHeight - titleFm.getHeight()) / 2 + titleFm.getAscent();
  129. g2d.drawString(title, titleX, titleY);
  130. y += titleHeight;
  131. // 标题下方的分割线
  132. g2d.setColor(GRID_COLOR);
  133. g2d.drawLine(0, y - 1, totalWidth, y - 1);
  134. }
  135. // 8. 绘制表头
  136. g2d.setColor(HEADER_BG);
  137. g2d.fillRect(0, y, totalWidth, headerHeight);
  138. g2d.setColor(HEADER_FG);
  139. g2d.setFont(headerFont);
  140. FontMetrics headerFm = g2d.getFontMetrics();
  141. int x = config.getCellPadding();
  142. for (int i = 0; i < headers.size(); i++) {
  143. String headerText = headers.get(i);
  144. int textWidth = headerFm.stringWidth(headerText);
  145. int availWidth = colWidths[i] - config.getCellPadding() * 2;
  146. // 表头不换行,超长则截断
  147. if (textWidth > availWidth) {
  148. headerText = truncateText(headerText, availWidth, headerFm);
  149. }
  150. int textY = y + (headerHeight - headerFm.getHeight()) / 2 + headerFm.getAscent();
  151. g2d.drawString(headerText, x + config.getCellPadding(), textY);
  152. x += colWidths[i];
  153. }
  154. y += headerHeight;
  155. // 9. 绘制数据行
  156. g2d.setFont(cellFont);
  157. FontMetrics cellFm = g2d.getFontMetrics();
  158. for (int rowIdx = 0; rowIdx < stringRows.size(); rowIdx++) {
  159. List<String> rowData = stringRows.get(rowIdx);
  160. int rowHeight = rowHeights[rowIdx];
  161. // 隔行变色
  162. Color rowBg = (rowIdx % 2 == 0) ? ROW_BG_EVEN : ROW_BG_ODD;
  163. g2d.setColor(rowBg);
  164. g2d.fillRect(0, y, totalWidth, rowHeight);
  165. // 绘制每个单元格
  166. int cellX = config.getCellPadding();
  167. for (int colIdx = 0; colIdx < rowData.size(); colIdx++) {
  168. String cellText = rowData.get(colIdx);
  169. int availWidth = colWidths[colIdx] - config.getCellPadding() * 2;
  170. // 文本换行处理
  171. List<String> lines = wrapText(cellText, availWidth, cellFm);
  172. g2d.setColor(TEXT_COLOR);
  173. int lineY = y + config.getCellPadding() + cellFm.getAscent();
  174. int maxLines = Math.max(1, (rowHeight - config.getCellPadding() * 2) / cellFm.getHeight());
  175. for (int lineIdx = 0; lineIdx < Math.min(lines.size(), maxLines); lineIdx++) {
  176. String line = lines.get(lineIdx);
  177. // 最后一行如果截断了,加省略号
  178. if (lineIdx == maxLines - 1 && lines.size() > maxLines && !line.endsWith("...")) {
  179. line = truncateText(line, availWidth, cellFm);
  180. }
  181. g2d.drawString(line, cellX + config.getCellPadding(), lineY);
  182. lineY += cellFm.getHeight();
  183. }
  184. cellX += colWidths[colIdx];
  185. }
  186. y += rowHeight;
  187. }
  188. // 10. 绘制网格线
  189. drawGridLines(g2d, totalWidth, titleHeight, headerHeight, rowHeights, colWidths);
  190. g2d.dispose();
  191. return image;
  192. }
  193. // ===== 私有方法 =====
  194. /**
  195. * 计算各列宽度(基于表头和内容,限制在 min ~ max 范围内)
  196. */
  197. private int[] calculateColumnWidths(List<String> headers, List<List<String>> rows) {
  198. int[] widths = new int[headers.size()];
  199. // 使用临时 BufferedImage 获取 FontMetrics
  200. BufferedImage temp = new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB);
  201. Graphics2D g = temp.createGraphics();
  202. g.setFont(cellFont);
  203. FontMetrics cellFm = g.getFontMetrics();
  204. g.setFont(headerFont);
  205. FontMetrics headerFm = g.getFontMetrics();
  206. int padding = config.getCellPadding() * 2;
  207. for (int i = 0; i < headers.size(); i++) {
  208. int maxContent = headerFm.stringWidth(headers.get(i)) + padding;
  209. for (List<String> row : rows) {
  210. if (i < row.size()) {
  211. String cellText = row.get(i);
  212. // 对于多行文本,取第一行宽度作为估算
  213. int textWidth = cellFm.stringWidth(cellText);
  214. // 如果超长,按最大列宽估算
  215. if (textWidth > config.getMaxColWidth() - padding) {
  216. textWidth = config.getMaxColWidth() - padding;
  217. }
  218. int cellWidth = textWidth + padding;
  219. if (cellWidth > maxContent) {
  220. maxContent = cellWidth;
  221. }
  222. }
  223. }
  224. widths[i] = Math.max(config.getMinColWidth(), Math.min(maxContent, config.getMaxColWidth()));
  225. }
  226. g.dispose();
  227. return widths;
  228. }
  229. /**
  230. * 计算各行高度(考虑文本换行)
  231. */
  232. private int[] calculateRowHeights(List<String> headers, List<List<String>> rows, int[] colWidths) {
  233. BufferedImage temp = new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB);
  234. Graphics2D g = temp.createGraphics();
  235. g.setFont(cellFont);
  236. FontMetrics cellFm = g.getFontMetrics();
  237. int[] heights = new int[rows.size()];
  238. int defaultHeight = config.getRowHeight();
  239. int padding = config.getCellPadding() * 2;
  240. int lineHeight = cellFm.getHeight();
  241. for (int rowIdx = 0; rowIdx < rows.size(); rowIdx++) {
  242. List<String> row = rows.get(rowIdx);
  243. int maxLines = 1;
  244. for (int colIdx = 0; colIdx < row.size() && colIdx < colWidths.length; colIdx++) {
  245. String cellText = row.get(colIdx);
  246. int availWidth = colWidths[colIdx] - padding;
  247. List<String> lines = wrapText(cellText, availWidth, cellFm);
  248. if (lines.size() > maxLines) {
  249. maxLines = lines.size();
  250. }
  251. }
  252. int calculatedHeight = padding + maxLines * lineHeight;
  253. heights[rowIdx] = Math.max(defaultHeight, calculatedHeight);
  254. }
  255. g.dispose();
  256. return heights;
  257. }
  258. /**
  259. * 文本换行:将文本按可用宽度拆分为多行
  260. */
  261. private List<String> wrapText(String text, int availWidth, FontMetrics fm) {
  262. List<String> lines = new ArrayList<>();
  263. if (text == null || text.isEmpty()) {
  264. lines.add("");
  265. return lines;
  266. }
  267. if (availWidth <= 0) {
  268. lines.add(text);
  269. return lines;
  270. }
  271. // 按已有换行符分割
  272. String[] paragraphs = text.split("\n");
  273. for (String para : paragraphs) {
  274. if (para.isEmpty()) {
  275. lines.add("");
  276. continue;
  277. }
  278. if (fm.stringWidth(para) <= availWidth) {
  279. lines.add(para);
  280. continue;
  281. }
  282. // 逐字符拆分(兼容中英文混合)
  283. StringBuilder current = new StringBuilder();
  284. for (int i = 0; i < para.length(); i++) {
  285. char c = para.charAt(i);
  286. String candidate = current.toString() + c;
  287. if (fm.stringWidth(candidate) > availWidth) {
  288. if (current.length() > 0) {
  289. lines.add(current.toString());
  290. current = new StringBuilder();
  291. }
  292. // 即使单个字符也超宽,也强制加入
  293. current.append(c);
  294. } else {
  295. current.append(c);
  296. }
  297. }
  298. if (current.length() > 0) {
  299. lines.add(current.toString());
  300. }
  301. }
  302. return lines;
  303. }
  304. /**
  305. * 截断文本并添加省略号
  306. */
  307. private String truncateText(String text, int availWidth, FontMetrics fm) {
  308. if (text == null || text.isEmpty()) {
  309. return "";
  310. }
  311. String ellipsis = "...";
  312. int ellipsisWidth = fm.stringWidth(ellipsis);
  313. if (availWidth <= ellipsisWidth) {
  314. return ellipsis;
  315. }
  316. StringBuilder sb = new StringBuilder();
  317. for (int i = 0; i < text.length(); i++) {
  318. String candidate = sb.toString() + text.charAt(i);
  319. if (fm.stringWidth(candidate) + ellipsisWidth > availWidth) {
  320. break;
  321. }
  322. sb.append(text.charAt(i));
  323. }
  324. return sb.toString() + ellipsis;
  325. }
  326. /**
  327. * 绘制网格线
  328. */
  329. private void drawGridLines(Graphics2D g2d, int totalWidth, int titleHeight,
  330. int headerHeight, int[] rowHeights, int[] colWidths) {
  331. g2d.setColor(GRID_COLOR);
  332. g2d.setStroke(new BasicStroke(1f));
  333. int startY = titleHeight;
  334. // 水平线:表头底部 + 每行底部
  335. int y = startY + headerHeight;
  336. g2d.drawLine(0, y, totalWidth, y);
  337. for (int h : rowHeights) {
  338. y += h;
  339. g2d.drawLine(0, y, totalWidth, y);
  340. }
  341. // 表头与数据之间的分隔线(稍粗)
  342. g2d.setColor(new Color(200, 203, 210));
  343. g2d.setStroke(new BasicStroke(1.5f));
  344. g2d.drawLine(0, startY + headerHeight, totalWidth, startY + headerHeight);
  345. g2d.setStroke(new BasicStroke(1f));
  346. g2d.setColor(GRID_COLOR);
  347. // 垂直线
  348. int x = config.getCellPadding();
  349. for (int i = 0; i < colWidths.length; i++) {
  350. x += colWidths[i];
  351. if (i < colWidths.length - 1) {
  352. g2d.drawLine(x, startY, x, y);
  353. }
  354. }
  355. // 外边框
  356. g2d.drawRect(1, startY - 1, totalWidth - 3, y - startY);
  357. }
  358. /**
  359. * 格式化单元格值
  360. * <p>根据字段类型将原始值转换为显示文本</p>
  361. */
  362. @SuppressWarnings("unchecked")
  363. private String formatCellValue(Object value, FieldDefinitionDTO fieldDef) {
  364. if (value == null) {
  365. return "";
  366. }
  367. String type = fieldDef.getType();
  368. if (type == null) {
  369. type = "";
  370. }
  371. try {
  372. switch (type) {
  373. case "NumberField":
  374. case "MoneyField":
  375. return formatNumber(value, type);
  376. case "DateField":
  377. case "DateTimeField":
  378. case "TimeField":
  379. return formatDate(value);
  380. case "EmployeeField":
  381. return formatEmployee(value);
  382. case "DepartmentField":
  383. return formatDepartment(value);
  384. case "AttachmentField":
  385. case "ImageUploadField":
  386. return formatAttachment(value);
  387. case "CheckboxField":
  388. case "MultiSelectField":
  389. return formatMultiValue(value);
  390. case "AddressField":
  391. return formatAddress(value);
  392. default:
  393. // 默认:如果是字符串直接返回,否则尝试 JSON 解析取 name/title
  394. if (value instanceof String) {
  395. return (String) value;
  396. }
  397. if (value instanceof Number) {
  398. return String.valueOf(value);
  399. }
  400. if (value instanceof Boolean) {
  401. return (Boolean) value ? "是" : "否";
  402. }
  403. // 尝试解析为 JSON 对象,提取常见的显示字段
  404. return extractDisplayName(value);
  405. }
  406. } catch (Exception e) {
  407. // 格式化失败,返回原始 toString
  408. return String.valueOf(value);
  409. }
  410. }
  411. private String formatNumber(Object value, String type) {
  412. if (value instanceof Number) {
  413. double d = ((Number) value).doubleValue();
  414. if (d == Math.floor(d)) {
  415. return String.valueOf((long) d);
  416. }
  417. if ("MoneyField".equals(type)) {
  418. return String.format("%.2f", d);
  419. }
  420. return String.valueOf(d);
  421. }
  422. return String.valueOf(value);
  423. }
  424. private String formatDate(Object value) {
  425. if (value instanceof Number) {
  426. long ts = ((Number) value).longValue();
  427. // 宜搭日期通常是毫秒时间戳
  428. return new SimpleDateFormat("yyyy-MM-dd").format(new Date(ts));
  429. }
  430. return String.valueOf(value);
  431. }
  432. private String formatEmployee(Object value) {
  433. // 宜搭 EmployeeField 返回值可能是 JSON 数组: [{"value":"xxx","label":"张三"}]
  434. if (value instanceof String) {
  435. String str = (String) value;
  436. try {
  437. if (str.startsWith("[")) {
  438. JSONArray arr = JSON.parseArray(str);
  439. StringBuilder sb = new StringBuilder();
  440. for (int i = 0; i < arr.size(); i++) {
  441. JSONObject obj = arr.getJSONObject(i);
  442. if (sb.length() > 0) sb.append(", ");
  443. sb.append(obj.getString("label"));
  444. }
  445. return sb.toString();
  446. }
  447. } catch (Exception ignored) {
  448. }
  449. return str;
  450. }
  451. return extractDisplayName(value);
  452. }
  453. private String formatDepartment(Object value) {
  454. return formatEmployee(value); // 结构类似
  455. }
  456. private String formatAttachment(Object value) {
  457. if (value instanceof String) {
  458. String str = (String) value;
  459. try {
  460. if (str.startsWith("[")) {
  461. JSONArray arr = JSON.parseArray(str);
  462. return arr.size() + " 个文件";
  463. }
  464. } catch (Exception ignored) {
  465. }
  466. }
  467. return String.valueOf(value);
  468. }
  469. private String formatMultiValue(Object value) {
  470. if (value instanceof String) {
  471. String str = (String) value;
  472. try {
  473. if (str.startsWith("[")) {
  474. JSONArray arr = JSON.parseArray(str);
  475. StringBuilder sb = new StringBuilder();
  476. for (int i = 0; i < arr.size(); i++) {
  477. if (sb.length() > 0) sb.append(", ");
  478. Object item = arr.get(i);
  479. if (item instanceof JSONObject) {
  480. sb.append(((JSONObject) item).getString("label"));
  481. } else {
  482. sb.append(String.valueOf(item));
  483. }
  484. }
  485. return sb.toString();
  486. }
  487. } catch (Exception ignored) {
  488. }
  489. return str;
  490. }
  491. if (value instanceof List) {
  492. return String.join(", ", (List<String>) value);
  493. }
  494. return String.valueOf(value);
  495. }
  496. private String formatAddress(Object value) {
  497. if (value instanceof String) {
  498. String str = (String) value;
  499. try {
  500. JSONObject obj = JSON.parseObject(str);
  501. // 宜搭地址格式: {"province":"xxx","city":"xxx","district":"xxx","address":"xxx"}
  502. StringBuilder sb = new StringBuilder();
  503. String[] keys = {"province", "city", "district", "address"};
  504. for (String key : keys) {
  505. String v = obj.getString(key);
  506. if (v != null && !v.isEmpty()) {
  507. sb.append(v);
  508. }
  509. }
  510. return sb.toString();
  511. } catch (Exception ignored) {
  512. }
  513. return str;
  514. }
  515. return String.valueOf(value);
  516. }
  517. /**
  518. * 从复杂对象中提取显示名称
  519. */
  520. private String extractDisplayName(Object value) {
  521. if (value instanceof Map) {
  522. Map<String, Object> map = (Map<String, Object>) value;
  523. // 尝试常见的字段名
  524. for (String key : new String[]{"label", "name", "title", "text", "value"}) {
  525. Object v = map.get(key);
  526. if (v != null) {
  527. return String.valueOf(v);
  528. }
  529. }
  530. }
  531. if (value instanceof List) {
  532. List<?> list = (List<?>) value;
  533. StringBuilder sb = new StringBuilder();
  534. for (Object item : list) {
  535. if (sb.length() > 0) sb.append(", ");
  536. sb.append(extractDisplayName(item));
  537. }
  538. return sb.toString();
  539. }
  540. return String.valueOf(value);
  541. }
  542. /**
  543. * 解析十六进制颜色字符串
  544. */
  545. private Color parseColor(String hex, Color defaultColor) {
  546. if (hex == null || hex.isEmpty()) {
  547. return defaultColor;
  548. }
  549. try {
  550. return Color.decode(hex);
  551. } catch (NumberFormatException e) {
  552. return defaultColor;
  553. }
  554. }
  555. }