TemplateUtil.java 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530
  1. package com.kingdee.eas.custom.compensation.utils;
  2. import com.google.common.collect.Maps;
  3. import com.kingdee.bos.Context;
  4. import com.kingdee.shr.base.syssetting.exception.SHRWebException;
  5. import com.kingdee.shr.compensation.util.columnModel.CmpColumnModels;
  6. import com.kingdee.shr.compensation.web.handler.integrate.entry.BaseSubmitBillEntryGenerator;
  7. import com.spire.doc.Document;
  8. import com.spire.doc.FileFormat;
  9. import org.apache.commons.lang3.StringUtils;
  10. import org.apache.poi.xwpf.usermodel.*;
  11. import org.apache.xmlbeans.XmlCursor;
  12. import org.apache.xmlbeans.XmlObject;
  13. import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTDrawing;
  14. import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTR;
  15. import java.io.*;
  16. import java.util.*;
  17. import java.util.regex.Matcher;
  18. import java.util.regex.Pattern;
  19. /**
  20. * @Description 模板工具类
  21. * @Date 2025/9/16 18:08
  22. * @Created by 59279
  23. */
  24. public class TemplateUtil {
  25. /**
  26. * 从Word文档中提取所有${xxx}格式的变量
  27. *
  28. * @param filePath Word文档路径
  29. * @return 包含所有变量的集合
  30. * @throws IOException 如果读取文件失败
  31. */
  32. public static Set<String> extractVariablesFromWord(String filePath) throws IOException {
  33. Set<String> variables = new HashSet<String>();
  34. FileInputStream fis = null;
  35. XWPFDocument document = null;
  36. try {
  37. fis = new FileInputStream(filePath);
  38. document = new XWPFDocument(fis);
  39. // 处理表格中的变量
  40. for (XWPFTable table : document.getTables()) {
  41. for (XWPFTableRow row : table.getRows()) {
  42. for (XWPFTableCell cell : row.getTableCells()) {
  43. for (XWPFParagraph paragraph : cell.getParagraphs()) {
  44. extractVariablesFromText(paragraph.getText(), variables);
  45. }
  46. }
  47. }
  48. }
  49. // 处理段落中的变量
  50. for (XWPFParagraph paragraph : document.getParagraphs()) {
  51. extractVariablesFromText(paragraph.getText(), variables);
  52. }
  53. } finally {
  54. if (fis != null) {
  55. fis.close();
  56. }
  57. if (document != null) {
  58. document.close();
  59. }
  60. }
  61. return variables;
  62. }
  63. /**
  64. * 从Word文档中提取所有${xxx}格式的变量
  65. *
  66. * @param file Word文档字节数组
  67. * @return 包含所有变量的集合
  68. * @throws IOException 如果读取文件失败
  69. */
  70. public static Set<String> extractVariablesFromWord(byte[] file) throws IOException {
  71. Set<String> variables = new LinkedHashSet<String>();
  72. ByteArrayInputStream bis = null;
  73. XWPFDocument document = null;
  74. try {
  75. bis = new ByteArrayInputStream(file);
  76. document = new XWPFDocument(bis);
  77. // 处理表格中的变量
  78. for (XWPFTable table : document.getTables()) {
  79. for (XWPFTableRow row : table.getRows()) {
  80. for (XWPFTableCell cell : row.getTableCells()) {
  81. for (XWPFParagraph paragraph : cell.getParagraphs()) {
  82. extractVariablesFromText(paragraph.getText(), variables);
  83. }
  84. }
  85. }
  86. }
  87. // 处理段落中的变量
  88. for (XWPFParagraph paragraph : document.getParagraphs()) {
  89. extractVariablesFromText(paragraph.getText(), variables);
  90. }
  91. } finally {
  92. if (bis != null) {
  93. bis.close();
  94. }
  95. if (document != null) {
  96. document.close();
  97. }
  98. }
  99. return variables;
  100. }
  101. /**
  102. * 从文本中提取变量并添加到集合中
  103. *
  104. * @param text 要搜索的文本
  105. * @param variables 变量集合
  106. */
  107. private static void extractVariablesFromText(String text, Set<String> variables) {
  108. // 匹配${xxx}格式的正则表达式
  109. Pattern pattern = Pattern.compile("\\$\\{([^}]+)\\}");
  110. Matcher matcher = pattern.matcher(text);
  111. while (matcher.find()) {
  112. // 获取匹配的变量名(去掉${和})
  113. String variable = matcher.group(1);
  114. variables.add(variable);
  115. }
  116. }
  117. /**
  118. * 处理Word模板,替换文本框变量并添加表格行
  119. *
  120. * @param file
  121. * @param variables 文本框变量映射
  122. * @param tableData 表格数据
  123. * @param approveList 审批信息
  124. * @throws IOException 如果读写文件失败
  125. */
  126. public static byte[] processWordTemplate(
  127. byte[] file,
  128. Map<String, String> variables,
  129. List<Map<String, String>> tableData,
  130. List<Map<String, String>> approveList
  131. ) throws IOException {
  132. ByteArrayInputStream bis = null;
  133. XWPFDocument document = null;
  134. try {
  135. bis = new ByteArrayInputStream(file);
  136. document = new XWPFDocument(bis);
  137. // 1. 处理文本框中的变量替换
  138. processTextboxes(document, variables);
  139. // 2. 处理段落中的变量替换
  140. processParagraphs(document, variables);
  141. // 3. 处理页眉页脚中的变量替换
  142. processHeadersAndFooters(document, variables);
  143. List<XWPFTable> tables = document.getTables();
  144. if (!tables.isEmpty()) {
  145. if (tables.size() > 0) {
  146. // 4. 处理表格 - 查找并添加行
  147. processTables(tables.get(0), tableData);
  148. }
  149. if (tables.size() > 1) {
  150. // 5. 处理审批表格表格 - 查找并添加行
  151. processApproveTables(tables.get(1), approveList);
  152. }
  153. }
  154. // 保存文档
  155. ByteArrayOutputStream bos = null;
  156. ByteArrayOutputStream pdfBos = null;
  157. ByteArrayInputStream byteArrayInputStream = null;
  158. try {
  159. bos = new ByteArrayOutputStream();
  160. document.write(bos);
  161. byteArrayInputStream = new ByteArrayInputStream(bos.toByteArray());
  162. pdfBos = new ByteArrayOutputStream();
  163. //实例化Document类的对象
  164. com.spire.doc.Document doc = new com.spire.doc.Document();
  165. doc.loadFromStream(byteArrayInputStream, FileFormat.Doc);
  166. //保存为PDF格式
  167. doc.saveToStream(pdfBos, FileFormat.PDF);
  168. return pdfBos.toByteArray();
  169. } finally {
  170. if (bos != null) {
  171. bos.close();
  172. }
  173. if (byteArrayInputStream != null) {
  174. byteArrayInputStream.close();
  175. }
  176. if (pdfBos != null) {
  177. pdfBos.close();
  178. }
  179. }
  180. } finally {
  181. if (bis != null) {
  182. bis.close();
  183. }
  184. if (document != null) {
  185. document.close();
  186. }
  187. }
  188. }
  189. /**
  190. * 处理文档中的所有文本框,替换变量
  191. *
  192. * @param document Word文档对象
  193. * @param variables 变量映射
  194. */
  195. private static void processTextboxes(XWPFDocument document, Map<String, String> variables) {
  196. // 获取文档中的所有绘图对象(包括文本框)
  197. //List<XWPFDrawing> drawings = new ArrayList<>();
  198. // 从段落中获取绘图对象
  199. for (XWPFParagraph paragraph : document.getParagraphs()) {
  200. for (XWPFRun run : paragraph.getRuns()) {
  201. if (run.getEmbeddedPictures().size() > 0 || run.getCTR().getDrawingList().size() > 0) {
  202. // 这里可以处理包含绘图的运行
  203. }
  204. }
  205. }
  206. // 从页眉获取绘图对象
  207. List<XWPFHeader> headers = document.getHeaderList();
  208. for (XWPFHeader header : headers) {
  209. for (XWPFParagraph paragraph : header.getParagraphs()) {
  210. for (XWPFRun run : paragraph.getRuns()) {
  211. if (run.getCTR().getDrawingList().size() > 0) {
  212. // 处理页眉中的绘图
  213. }
  214. }
  215. }
  216. }
  217. // 从页脚获取绘图对象
  218. List<XWPFFooter> footers = document.getFooterList();
  219. for (XWPFFooter footer : footers) {
  220. for (XWPFParagraph paragraph : footer.getParagraphs()) {
  221. for (XWPFRun run : paragraph.getRuns()) {
  222. if (run.getCTR().getDrawingList().size() > 0) {
  223. // 处理页脚中的绘图
  224. }
  225. }
  226. }
  227. }
  228. // 由于POI对文本框的直接支持有限,这里使用XML遍历方式处理文本框
  229. try {
  230. // 获取文档的底层XML对象
  231. XmlCursor cursor = document.getDocument().newCursor();
  232. // 移动到文档开始
  233. cursor.toStartDoc();
  234. // 遍历所有文本框
  235. while (cursor.hasNextToken()) {
  236. XmlCursor.TokenType token = cursor.toNextToken();
  237. if (token.isStart()) {
  238. XmlObject obj = cursor.getObject();
  239. if (obj instanceof CTR) {
  240. CTR ctr = (CTR) obj;
  241. if (ctr.getDrawingList().size() > 0) {
  242. // 处理绘图对象
  243. for (CTDrawing drawing : ctr.getDrawingList()) {
  244. // 查找文本框
  245. XmlCursor drawingCursor = drawing.newCursor();
  246. if (drawingCursor.toChild("http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing", "anchor") ||
  247. drawingCursor.toChild("http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing", "inline")) {
  248. // 查找文本框内容
  249. if (drawingCursor.toChild("http://schemas.openxmlformats.org/drawingml/2006/main", "txBox")) {
  250. // 获取文本框中的文本
  251. if (drawingCursor.toChild("http://schemas.openxmlformats.org/drawingml/2006/main", "txBody")) {
  252. if (drawingCursor.toChild("http://schemas.openxmlformats.org/drawingml/2006/main", "p")) {
  253. String text = drawingCursor.getTextValue();
  254. // 替换变量
  255. String replacedText = replaceVariables(text, variables);
  256. // 设置回文本框
  257. if (!text.equals(replacedText)) {
  258. drawingCursor.setTextValue(replacedText);
  259. }
  260. }
  261. }
  262. }
  263. }
  264. drawingCursor.dispose();
  265. }
  266. }
  267. }
  268. }
  269. }
  270. cursor.dispose();
  271. } catch (Exception e) {
  272. System.err.println("处理文本框时出错: " + e.getMessage());
  273. e.printStackTrace();
  274. }
  275. }
  276. /**
  277. * 处理文档中的所有段落,替换变量
  278. *
  279. * @param document Word文档对象
  280. * @param variables 变量映射
  281. */
  282. private static void processParagraphs(XWPFDocument document, Map<String, String> variables) {
  283. for (XWPFParagraph paragraph : document.getParagraphs()) {
  284. String text = paragraph.getText();
  285. String replacedText = replaceVariables(text, variables);
  286. if (!text.equals(replacedText)) {
  287. // 清除原有内容
  288. for (int i = paragraph.getRuns().size() - 1; i >= 0; i--) {
  289. paragraph.removeRun(i);
  290. }
  291. // 添加新内容
  292. XWPFRun run = paragraph.createRun();
  293. run.setText(replacedText);
  294. }
  295. }
  296. }
  297. /**
  298. * 处理文档中的页眉和页脚,替换变量
  299. *
  300. * @param document Word文档对象
  301. * @param variables 变量映射
  302. */
  303. private static void processHeadersAndFooters(XWPFDocument document, Map<String, String> variables) {
  304. // 处理页眉
  305. List<XWPFHeader> headers = document.getHeaderList();
  306. for (XWPFHeader header : headers) {
  307. for (XWPFParagraph paragraph : header.getParagraphs()) {
  308. String text = paragraph.getText();
  309. String replacedText = replaceVariables(text, variables);
  310. if (!text.equals(replacedText)) {
  311. // 清除原有内容
  312. for (int i = paragraph.getRuns().size() - 1; i >= 0; i--) {
  313. paragraph.removeRun(i);
  314. }
  315. // 添加新内容
  316. XWPFRun run = paragraph.createRun();
  317. run.setText(replacedText);
  318. }
  319. }
  320. }
  321. // 处理页脚
  322. List<XWPFFooter> footers = document.getFooterList();
  323. for (XWPFFooter footer : footers) {
  324. for (XWPFParagraph paragraph : footer.getParagraphs()) {
  325. String text = paragraph.getText();
  326. String replacedText = replaceVariables(text, variables);
  327. if (!text.equals(replacedText)) {
  328. // 清除原有内容
  329. for (int i = paragraph.getRuns().size() - 1; i >= 0; i--) {
  330. paragraph.removeRun(i);
  331. }
  332. // 添加新内容
  333. XWPFRun run = paragraph.createRun();
  334. run.setText(replacedText);
  335. }
  336. }
  337. }
  338. }
  339. /**
  340. * 处理文档中的所有表格,添加行并替换变量
  341. *
  342. * @param table Word文档对象
  343. * @param tableData 表格数据
  344. */
  345. private static void processTables(XWPFTable table, List<Map<String, String>> tableData) {
  346. //for (XWPFTable table : document.getTables()) {
  347. // 查找模板行(通常第一行是表头,第二行是模板行)
  348. if (table.getNumberOfRows() >= 2) {
  349. XWPFTableRow templateRow = table.getRow(1);
  350. int num = 2;
  351. // 为每条数据添加新行
  352. for (Map<String, String> rowData : tableData) {
  353. // 复制模板行
  354. XWPFTableRow newRow = table.insertNewTableRow(2);
  355. // 复制每个单元格
  356. for (int i = 0; i < templateRow.getTableCells().size(); i++) {
  357. XWPFTableCell templateCell = templateRow.getCell(i);
  358. XWPFTableCell newCell = newRow.addNewTableCell();
  359. //清除自带的段落
  360. for (int j = newCell.getParagraphs().size() - 1; j >= 0; j--) {
  361. newCell.removeParagraph(j);
  362. }
  363. // 复制单元格样式
  364. newCell.getCTTc().setTcPr(templateCell.getCTTc().getTcPr());
  365. // 复制段落并替换变量
  366. for (XWPFParagraph paragraph : templateCell.getParagraphs()) {
  367. XWPFParagraph newParagraph = newCell.addParagraph();
  368. newParagraph.getCTP().setPPr(paragraph.getCTP().getPPr());
  369. //变量名称
  370. String text = paragraph.getText();
  371. String replacedText = replaceVariables(text, rowData);
  372. XWPFRun newRun = newParagraph.createRun();
  373. newRun.setText(replacedText);
  374. // 复制运行样式
  375. if (paragraph.getRuns().size() > 0) {
  376. XWPFRun templateRun = paragraph.getRuns().get(0);
  377. newRun.setBold(templateRun.isBold());
  378. newRun.setItalic(templateRun.isItalic());
  379. String fontFamily = templateRun.getFontFamily();
  380. if (StringUtils.isNotBlank(fontFamily)) {
  381. newRun.setFontFamily(fontFamily);
  382. }
  383. int fontSize = templateRun.getFontSize();
  384. if (fontSize > 0) {
  385. newRun.setFontSize(fontSize);
  386. }
  387. newRun.setColor(templateRun.getColor());
  388. }
  389. }
  390. }
  391. num++;
  392. }
  393. // 删除模板行
  394. table.removeRow(1);
  395. }
  396. //}
  397. }
  398. /**
  399. * 处理审批表格表格,添加行并替换变量
  400. *
  401. * @param table Word文档对象
  402. * @param tableData 表格数据
  403. */
  404. private static void processApproveTables(XWPFTable table, List<Map<String, String>> tableData) {
  405. // 查找模板行(通常第一行是表头,第二行是模板行)
  406. if (table.getNumberOfRows() >= 2) {
  407. XWPFTableRow templateRow = table.getRow(1);
  408. int num = 2;
  409. // 为每条数据添加新行
  410. for (Map<String, String> rowData : tableData) {
  411. // 复制模板行
  412. XWPFTableRow newRow = table.insertNewTableRow(2);
  413. // 复制每个单元格
  414. for (int i = 0; i < templateRow.getTableCells().size(); i++) {
  415. XWPFTableCell templateCell = templateRow.getCell(i);
  416. XWPFTableCell newCell = newRow.addNewTableCell();
  417. //清除自带的段落
  418. for (int j = newCell.getParagraphs().size() - 1; j >= 0; j--) {
  419. newCell.removeParagraph(j);
  420. }
  421. // 复制单元格样式
  422. newCell.getCTTc().setTcPr(templateCell.getCTTc().getTcPr());
  423. // 复制段落并替换变量
  424. for (XWPFParagraph paragraph : templateCell.getParagraphs()) {
  425. XWPFParagraph newParagraph = newCell.addParagraph();
  426. newParagraph.getCTP().setPPr(paragraph.getCTP().getPPr());
  427. //变量名称
  428. String text = paragraph.getText();
  429. String replacedText = replaceVariables(text, rowData);
  430. XWPFRun newRun = newParagraph.createRun();
  431. newRun.setText(replacedText);
  432. // 复制运行样式
  433. if (paragraph.getRuns().size() > 0) {
  434. XWPFRun templateRun = paragraph.getRuns().get(0);
  435. newRun.setBold(templateRun.isBold());
  436. newRun.setItalic(templateRun.isItalic());
  437. String fontFamily = templateRun.getFontFamily();
  438. if (StringUtils.isNotBlank(fontFamily)) {
  439. newRun.setFontFamily(fontFamily);
  440. }
  441. int fontSize = templateRun.getFontSize();
  442. if (fontSize > 0) {
  443. newRun.setFontSize(fontSize);
  444. }
  445. newRun.setColor(templateRun.getColor());
  446. }
  447. }
  448. }
  449. num++;
  450. }
  451. // 删除模板行
  452. table.removeRow(1);
  453. }
  454. }
  455. /**
  456. * 替换文本中的变量
  457. *
  458. * @param text 原始文本
  459. * @param variables 变量映射
  460. * @return 替换后的文本
  461. */
  462. private static String replaceVariables(String text, Map<String, String> variables) {
  463. if (text == null || variables == null) {
  464. return text;
  465. }
  466. String result = text;
  467. for (Map.Entry<String, String> entry : variables.entrySet()) {
  468. String pattern = "\\$\\{" + entry.getKey() + "\\}";
  469. String value = entry.getValue() == null ? "" : entry.getValue();
  470. result = result.replaceAll(pattern, value);
  471. }
  472. return result;
  473. }
  474. /**
  475. * 获取提报方案字段
  476. *
  477. * @param ctx 上下文对象
  478. * @param submitSchemeId 提报方案ID
  479. * @return 提报方案字段列表
  480. * @throws IOException
  481. * @throws SHRWebException
  482. */
  483. public static CmpColumnModels getSubmitSchemeFields(Context ctx, String submitSchemeId) throws SHRWebException {
  484. //获取提报方案字段
  485. boolean dynamicColmunRequired = true;
  486. Map<String, Object> params = Maps.newHashMap();
  487. params.put("datasource", 2);
  488. params.put("costTypeId", "");
  489. params.put("dynamicColmunRequired", dynamicColmunRequired);
  490. params.put("hrOrgUnitId", "");
  491. BaseSubmitBillEntryGenerator baseSubmitBillEntryGenerator = new BaseSubmitBillEntryGenerator();
  492. return baseSubmitBillEntryGenerator.getEntryColumnModels(ctx, submitSchemeId, params);
  493. }
  494. }