TemplateUtil.java 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531
  1. package com.kingdee.eas.custom.compensation.utils;
  2. import com.google.common.collect.Maps;
  3. import com.kingdee.bos.BOSException;
  4. import com.kingdee.bos.Context;
  5. import com.kingdee.shr.base.syssetting.exception.SHRWebException;
  6. import com.kingdee.shr.compensation.util.columnModel.CmpColumnModels;
  7. import com.kingdee.shr.compensation.web.handler.integrate.entry.BaseSubmitBillEntryGenerator;
  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, BOSException {
  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. //去除水印
  169. byte[] bytes = PDFUtil.removeWatermark(pdfBos.toByteArray(),"Evaluation Warning: The document was created with Spire.Doc for JAVA.");
  170. return bytes;
  171. } finally {
  172. if (bos != null) {
  173. bos.close();
  174. }
  175. if (byteArrayInputStream != null) {
  176. byteArrayInputStream.close();
  177. }
  178. if (pdfBos != null) {
  179. pdfBos.close();
  180. }
  181. }
  182. } finally {
  183. if (bis != null) {
  184. bis.close();
  185. }
  186. if (document != null) {
  187. document.close();
  188. }
  189. }
  190. }
  191. /**
  192. * 处理文档中的所有文本框,替换变量
  193. *
  194. * @param document Word文档对象
  195. * @param variables 变量映射
  196. */
  197. private static void processTextboxes(XWPFDocument document, Map<String, String> variables) {
  198. // 获取文档中的所有绘图对象(包括文本框)
  199. //List<XWPFDrawing> drawings = new ArrayList<>();
  200. // 从段落中获取绘图对象
  201. for (XWPFParagraph paragraph : document.getParagraphs()) {
  202. for (XWPFRun run : paragraph.getRuns()) {
  203. if (run.getEmbeddedPictures().size() > 0 || run.getCTR().getDrawingList().size() > 0) {
  204. // 这里可以处理包含绘图的运行
  205. }
  206. }
  207. }
  208. // 从页眉获取绘图对象
  209. List<XWPFHeader> headers = document.getHeaderList();
  210. for (XWPFHeader header : headers) {
  211. for (XWPFParagraph paragraph : header.getParagraphs()) {
  212. for (XWPFRun run : paragraph.getRuns()) {
  213. if (run.getCTR().getDrawingList().size() > 0) {
  214. // 处理页眉中的绘图
  215. }
  216. }
  217. }
  218. }
  219. // 从页脚获取绘图对象
  220. List<XWPFFooter> footers = document.getFooterList();
  221. for (XWPFFooter footer : footers) {
  222. for (XWPFParagraph paragraph : footer.getParagraphs()) {
  223. for (XWPFRun run : paragraph.getRuns()) {
  224. if (run.getCTR().getDrawingList().size() > 0) {
  225. // 处理页脚中的绘图
  226. }
  227. }
  228. }
  229. }
  230. // 由于POI对文本框的直接支持有限,这里使用XML遍历方式处理文本框
  231. try {
  232. // 获取文档的底层XML对象
  233. XmlCursor cursor = document.getDocument().newCursor();
  234. // 移动到文档开始
  235. cursor.toStartDoc();
  236. // 遍历所有文本框
  237. while (cursor.hasNextToken()) {
  238. XmlCursor.TokenType token = cursor.toNextToken();
  239. if (token.isStart()) {
  240. XmlObject obj = cursor.getObject();
  241. if (obj instanceof CTR) {
  242. CTR ctr = (CTR) obj;
  243. if (ctr.getDrawingList().size() > 0) {
  244. // 处理绘图对象
  245. for (CTDrawing drawing : ctr.getDrawingList()) {
  246. // 查找文本框
  247. XmlCursor drawingCursor = drawing.newCursor();
  248. if (drawingCursor.toChild("http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing", "anchor") ||
  249. drawingCursor.toChild("http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing", "inline")) {
  250. // 查找文本框内容
  251. if (drawingCursor.toChild("http://schemas.openxmlformats.org/drawingml/2006/main", "txBox")) {
  252. // 获取文本框中的文本
  253. if (drawingCursor.toChild("http://schemas.openxmlformats.org/drawingml/2006/main", "txBody")) {
  254. if (drawingCursor.toChild("http://schemas.openxmlformats.org/drawingml/2006/main", "p")) {
  255. String text = drawingCursor.getTextValue();
  256. // 替换变量
  257. String replacedText = replaceVariables(text, variables);
  258. // 设置回文本框
  259. if (!text.equals(replacedText)) {
  260. drawingCursor.setTextValue(replacedText);
  261. }
  262. }
  263. }
  264. }
  265. }
  266. drawingCursor.dispose();
  267. }
  268. }
  269. }
  270. }
  271. }
  272. cursor.dispose();
  273. } catch (Exception e) {
  274. System.err.println("处理文本框时出错: " + e.getMessage());
  275. e.printStackTrace();
  276. }
  277. }
  278. /**
  279. * 处理文档中的所有段落,替换变量
  280. *
  281. * @param document Word文档对象
  282. * @param variables 变量映射
  283. */
  284. private static void processParagraphs(XWPFDocument document, Map<String, String> variables) {
  285. for (XWPFParagraph paragraph : document.getParagraphs()) {
  286. String text = paragraph.getText();
  287. String replacedText = replaceVariables(text, variables);
  288. if (!text.equals(replacedText)) {
  289. // 清除原有内容
  290. for (int i = paragraph.getRuns().size() - 1; i >= 0; i--) {
  291. paragraph.removeRun(i);
  292. }
  293. // 添加新内容
  294. XWPFRun run = paragraph.createRun();
  295. run.setText(replacedText);
  296. }
  297. }
  298. }
  299. /**
  300. * 处理文档中的页眉和页脚,替换变量
  301. *
  302. * @param document Word文档对象
  303. * @param variables 变量映射
  304. */
  305. private static void processHeadersAndFooters(XWPFDocument document, Map<String, String> variables) {
  306. // 处理页眉
  307. List<XWPFHeader> headers = document.getHeaderList();
  308. for (XWPFHeader header : headers) {
  309. for (XWPFParagraph paragraph : header.getParagraphs()) {
  310. String text = paragraph.getText();
  311. String replacedText = replaceVariables(text, variables);
  312. if (!text.equals(replacedText)) {
  313. // 清除原有内容
  314. for (int i = paragraph.getRuns().size() - 1; i >= 0; i--) {
  315. paragraph.removeRun(i);
  316. }
  317. // 添加新内容
  318. XWPFRun run = paragraph.createRun();
  319. run.setText(replacedText);
  320. }
  321. }
  322. }
  323. // 处理页脚
  324. List<XWPFFooter> footers = document.getFooterList();
  325. for (XWPFFooter footer : footers) {
  326. for (XWPFParagraph paragraph : footer.getParagraphs()) {
  327. String text = paragraph.getText();
  328. String replacedText = replaceVariables(text, variables);
  329. if (!text.equals(replacedText)) {
  330. // 清除原有内容
  331. for (int i = paragraph.getRuns().size() - 1; i >= 0; i--) {
  332. paragraph.removeRun(i);
  333. }
  334. // 添加新内容
  335. XWPFRun run = paragraph.createRun();
  336. run.setText(replacedText);
  337. }
  338. }
  339. }
  340. }
  341. /**
  342. * 处理文档中的所有表格,添加行并替换变量
  343. *
  344. * @param table Word文档对象
  345. * @param tableData 表格数据
  346. */
  347. private static void processTables(XWPFTable table, List<Map<String, String>> tableData) {
  348. //for (XWPFTable table : document.getTables()) {
  349. // 查找模板行(通常第一行是表头,第二行是模板行)
  350. if (table.getNumberOfRows() >= 2) {
  351. XWPFTableRow templateRow = table.getRow(1);
  352. int num = 2;
  353. // 为每条数据添加新行
  354. for (Map<String, String> rowData : tableData) {
  355. // 复制模板行
  356. XWPFTableRow newRow = table.insertNewTableRow(2);
  357. // 复制每个单元格
  358. for (int i = 0; i < templateRow.getTableCells().size(); i++) {
  359. XWPFTableCell templateCell = templateRow.getCell(i);
  360. XWPFTableCell newCell = newRow.addNewTableCell();
  361. //清除自带的段落
  362. for (int j = newCell.getParagraphs().size() - 1; j >= 0; j--) {
  363. newCell.removeParagraph(j);
  364. }
  365. // 复制单元格样式
  366. newCell.getCTTc().setTcPr(templateCell.getCTTc().getTcPr());
  367. // 复制段落并替换变量
  368. for (XWPFParagraph paragraph : templateCell.getParagraphs()) {
  369. XWPFParagraph newParagraph = newCell.addParagraph();
  370. newParagraph.getCTP().setPPr(paragraph.getCTP().getPPr());
  371. //变量名称
  372. String text = paragraph.getText();
  373. String replacedText = replaceVariables(text, rowData);
  374. XWPFRun newRun = newParagraph.createRun();
  375. newRun.setText(replacedText);
  376. // 复制运行样式
  377. if (paragraph.getRuns().size() > 0) {
  378. XWPFRun templateRun = paragraph.getRuns().get(0);
  379. newRun.setBold(templateRun.isBold());
  380. newRun.setItalic(templateRun.isItalic());
  381. String fontFamily = templateRun.getFontFamily();
  382. if (StringUtils.isNotBlank(fontFamily)) {
  383. newRun.setFontFamily(fontFamily);
  384. }
  385. int fontSize = templateRun.getFontSize();
  386. if (fontSize > 0) {
  387. newRun.setFontSize(fontSize);
  388. }
  389. newRun.setColor(templateRun.getColor());
  390. }
  391. }
  392. }
  393. num++;
  394. }
  395. // 删除模板行
  396. table.removeRow(1);
  397. }
  398. //}
  399. }
  400. /**
  401. * 处理审批表格表格,添加行并替换变量
  402. *
  403. * @param table Word文档对象
  404. * @param tableData 表格数据
  405. */
  406. private static void processApproveTables(XWPFTable table, List<Map<String, String>> tableData) {
  407. // 查找模板行(通常第一行是表头,第二行是模板行)
  408. if (table.getNumberOfRows() >= 2) {
  409. XWPFTableRow templateRow = table.getRow(1);
  410. int num = 2;
  411. // 为每条数据添加新行
  412. for (Map<String, String> rowData : tableData) {
  413. // 复制模板行
  414. XWPFTableRow newRow = table.insertNewTableRow(2);
  415. // 复制每个单元格
  416. for (int i = 0; i < templateRow.getTableCells().size(); i++) {
  417. XWPFTableCell templateCell = templateRow.getCell(i);
  418. XWPFTableCell newCell = newRow.addNewTableCell();
  419. //清除自带的段落
  420. for (int j = newCell.getParagraphs().size() - 1; j >= 0; j--) {
  421. newCell.removeParagraph(j);
  422. }
  423. // 复制单元格样式
  424. newCell.getCTTc().setTcPr(templateCell.getCTTc().getTcPr());
  425. // 复制段落并替换变量
  426. for (XWPFParagraph paragraph : templateCell.getParagraphs()) {
  427. XWPFParagraph newParagraph = newCell.addParagraph();
  428. newParagraph.getCTP().setPPr(paragraph.getCTP().getPPr());
  429. //变量名称
  430. String text = paragraph.getText();
  431. String replacedText = replaceVariables(text, rowData);
  432. XWPFRun newRun = newParagraph.createRun();
  433. newRun.setText(replacedText);
  434. // 复制运行样式
  435. if (paragraph.getRuns().size() > 0) {
  436. XWPFRun templateRun = paragraph.getRuns().get(0);
  437. newRun.setBold(templateRun.isBold());
  438. newRun.setItalic(templateRun.isItalic());
  439. String fontFamily = templateRun.getFontFamily();
  440. if (StringUtils.isNotBlank(fontFamily)) {
  441. newRun.setFontFamily(fontFamily);
  442. }
  443. int fontSize = templateRun.getFontSize();
  444. if (fontSize > 0) {
  445. newRun.setFontSize(fontSize);
  446. }
  447. newRun.setColor(templateRun.getColor());
  448. }
  449. }
  450. }
  451. num++;
  452. }
  453. // 删除模板行
  454. table.removeRow(1);
  455. }
  456. }
  457. /**
  458. * 替换文本中的变量
  459. *
  460. * @param text 原始文本
  461. * @param variables 变量映射
  462. * @return 替换后的文本
  463. */
  464. private static String replaceVariables(String text, Map<String, String> variables) {
  465. if (text == null || variables == null) {
  466. return text;
  467. }
  468. String result = text;
  469. for (Map.Entry<String, String> entry : variables.entrySet()) {
  470. String pattern = "\\$\\{" + entry.getKey() + "\\}";
  471. String value = entry.getValue() == null ? "" : entry.getValue();
  472. result = result.replaceAll(pattern, value);
  473. }
  474. return result;
  475. }
  476. /**
  477. * 获取提报方案字段
  478. *
  479. * @param ctx 上下文对象
  480. * @param submitSchemeId 提报方案ID
  481. * @return 提报方案字段列表
  482. * @throws IOException
  483. * @throws SHRWebException
  484. */
  485. public static CmpColumnModels getSubmitSchemeFields(Context ctx, String submitSchemeId) throws SHRWebException {
  486. //获取提报方案字段
  487. boolean dynamicColmunRequired = true;
  488. Map<String, Object> params = Maps.newHashMap();
  489. params.put("datasource", 2);
  490. params.put("costTypeId", "");
  491. params.put("dynamicColmunRequired", dynamicColmunRequired);
  492. params.put("hrOrgUnitId", "");
  493. BaseSubmitBillEntryGenerator baseSubmitBillEntryGenerator = new BaseSubmitBillEntryGenerator();
  494. return baseSubmitBillEntryGenerator.getEntryColumnModels(ctx, submitSchemeId, params);
  495. }
  496. }