WordToPdfUtil.java 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  1. package com.ruoyi.common.utils.ahrs;
  2. import com.alibaba.fastjson.JSONObject;
  3. import com.aspose.words.*;
  4. import com.aspose.words.Document;
  5. import com.ruoyi.common.config.Global;
  6. import com.ruoyi.common.enums.FlowTypeEnums;
  7. import com.ruoyi.common.enums.UserEnums;
  8. import com.ruoyi.common.utils.DateUtils;
  9. import com.ruoyi.common.utils.StringUtils;
  10. import com.ruoyi.common.utils.file.FileUploadUtils;
  11. import com.ruoyi.common.utils.file.FileUtils;
  12. import org.apache.pdfbox.multipdf.PDFMergerUtility;
  13. import org.apache.poi.xwpf.usermodel.*;
  14. import org.springframework.scheduling.annotation.Async;
  15. import java.io.*;
  16. import java.util.*;
  17. import java.util.List;
  18. /**
  19. * Description:
  20. *
  21. * @author flh
  22. * @date Created on 2021/1/18
  23. */
  24. public class WordToPdfUtil {
  25. public boolean getLicense() {
  26. boolean result = false;
  27. try {
  28. InputStream is =this.getClass().getClassLoader().getResourceAsStream("license.xml");
  29. License aposeLic = new License();
  30. aposeLic.setLicense(is);
  31. result = true;
  32. } catch (Exception e) {
  33. e.printStackTrace();
  34. }
  35. return result;
  36. }
  37. public static void main(String[] args) throws Exception {
  38. // WordToPdfUtil bean = new WordToPdfUtil();
  39. // //windows下
  40. // bean.word2Pdf2("D:\\20210831103542.docx","D:\\20210831103542.pdf");
  41. // bean.word2Pdf2("D:\\安徽省安徽警官职业学院人员聘任确认函.docx","D:\\安徽省安徽警官职业学院人员聘任确认函.pdf");
  42. // //linux下
  43. // bean.word2Pdf2("//opt//uploadPath//安徽省演示事业单位二来文承办签.docx","//opt//uploadPath//安徽省演示事业单位二来文承办签.pdf");
  44. // bean.word2Pdf2("//opt//uploadPath//安徽省演示事业单位二人员聘任确认函.docx","//opt//uploadPath//安徽省演示事业单位二人员聘任确认函.pdf");
  45. //确认函盖章
  46. // try {
  47. // ElectronicSeal.sealAutoPdfZF("D:\\\\安徽省省教育厅人员聘任确认函(合并).pdf");
  48. // } catch (Exception e) {
  49. // e.printStackTrace();
  50. // }
  51. }
  52. /**
  53. * inpath: 输入word的路径,例如: C:\\TEST.doc
  54. * outpath: 输出pdf的路径,例如: C:\\TEST.pdf
  55. */
  56. public void word2Pdf2(String inpath,String outpath) throws Exception {
  57. if (!getLicense()) { // 验证License 若不验证则转化出的pdf文档会有水印产生
  58. System.out.println("非法------------");
  59. return;
  60. }
  61. long old = System.currentTimeMillis();
  62. File file = new File(outpath);
  63. FileOutputStream os = new FileOutputStream(file);
  64. //解决乱码
  65. //如果是windows执行,不需要加这个
  66. //TODO 如果是linux执行,需要添加这个*****
  67. String sy = System.getProperty("os.name");
  68. if(!sy.toLowerCase().startsWith("win")){
  69. FontSettings.setFontsFolder("/usr/share/fonts",true);
  70. }
  71. Document doc = new Document(inpath); //Address是将要被转化的word文档
  72. doc.save(os, SaveFormat.PDF);//全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF, EPUB, XPS, SWF 相互转换
  73. long now = System.currentTimeMillis();
  74. System.out.println("共耗时:" + ((now - old) / 1000.0) + "秒");
  75. os.flush();
  76. os.close();
  77. }
  78. public String word2Pdf2(String inpath) throws Exception {
  79. if (!getLicense()) { // 验证License 若不验证则转化出的pdf文档会有水印产生
  80. System.out.println("非法------------");
  81. return "";
  82. }
  83. String outpath = StringUtils.substringBeforeLast(inpath,".")+".pdf";
  84. long old = System.currentTimeMillis();
  85. File file = new File(Global.getProfile() + outpath.substring(8));
  86. FileOutputStream os = new FileOutputStream(file);
  87. //解决乱码
  88. //如果是windows执行,不需要加这个
  89. //TODO 如果是linux执行,需要添加这个*****
  90. String sy = System.getProperty("os.name");
  91. if(!sy.toLowerCase().startsWith("win")){
  92. FontSettings.setFontsFolder("/usr/share/fonts",true);
  93. }
  94. Document doc = new Document(Global.getProfile() + inpath.substring(8)); //Address是将要被转化的word文档
  95. PdfSaveOptions options = new PdfSaveOptions();
  96. options.setExportDocumentStructure(true);
  97. // Document document = new Document();//新建一个空白pdf文档
  98. // document.removeAllChildren();
  99. // document.appendDocument(doc, ImportFormatMode.USE_DESTINATION_STYLES);//保留样式
  100. doc.save(os, SaveFormat.PDF);//全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF, EPUB, XPS, SWF 相互转换
  101. long now = System.currentTimeMillis();
  102. System.out.println("共耗时:" + ((now - old) / 1000.0) + "秒");
  103. os.flush();
  104. os.close();
  105. return outpath;
  106. }
  107. /**
  108. * @param path pdf输出路径
  109. * @param wordInput word输入流
  110. * @param wordName word文档的名称
  111. */
  112. public void word2pdf(String path, InputStream wordInput, String wordName) throws FileNotFoundException {
  113. if (!getLicense()) { // 验证License 若不验证则转化出的pdf文档会有水印产生
  114. System.out.println("非法");
  115. return;
  116. }
  117. long old = System.currentTimeMillis();
  118. File file = new File(path + wordName + ".pdf"); //新建一个空白pdf文档
  119. FileOutputStream os = new FileOutputStream(file);
  120. Document doc = null; //Address是将要被转化的word文档
  121. try {
  122. doc = new Document(wordInput);
  123. } catch (Exception e) {
  124. e.printStackTrace();
  125. }
  126. try {
  127. doc.save(os, SaveFormat.PDF);//全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF, EPUB, XPS, SWF 相互转换
  128. } catch (Exception e) {
  129. e.printStackTrace();
  130. }
  131. long now = System.currentTimeMillis();
  132. System.out.println("共耗时:" + ((now - old) / 1000.0) + "秒"); //转化用时
  133. }
  134. /**
  135. * 设置确认函日期,并转换为PDF
  136. *
  137. * @param attachmentMap
  138. * @return
  139. */
  140. @Async("threadPoolTaskExecutor")
  141. public void setParameterToFile(Map<String, String> attachmentMap) throws Exception {
  142. String path = Global.getProfile() + attachmentMap.get(FlowTypeEnums.FileName.BDQRH.getStatus()).substring(8);
  143. //获取模板文件流
  144. InputStream templateFileStream = new FileInputStream(path);
  145. //转为临时模板文件对象
  146. String tempTemplateFilePath = Global.getProfile() + "/" + "tempParameter.docx";
  147. File fileTemp = new File(tempTemplateFilePath);
  148. if (!fileTemp.exists()) {
  149. fileTemp.createNewFile();
  150. }
  151. PathUtil.inputstreamtofile(templateFileStream, fileTemp);
  152. //动态生成word
  153. WordUtils.process(new HashMap() {{
  154. put("date", DateUtils.datePath2());
  155. }}, tempTemplateFilePath, new File(path));
  156. //删除临时模板文件
  157. FileUtils.deleteFile(tempTemplateFilePath);
  158. word2Pdf2(attachmentMap.get(FlowTypeEnums.FileName.BDQRH.getStatus()));
  159. // //确认函盖章
  160. // try {
  161. // ElectronicSeal.sealAutoPdfZF(Global.getProfile() + attachmentMap.get(FlowTypeEnums.FileName.PDFQRH.getStatus()).substring(8));
  162. // } catch (Exception e) {
  163. // e.printStackTrace();
  164. // }
  165. }
  166. /**
  167. * 承办签word插入意见,并转为pdf,此处是初审领导或终审领导审批通过,所以无需更新attachment
  168. *
  169. * @param comment 意见
  170. * @param attachmentMap 申报附件Map
  171. * @throws IOException
  172. */
  173. @Async("threadPoolTaskExecutor")
  174. public void editword(String roleId, String userName, String comment, Map<String, String> attachmentMap) throws Exception {
  175. String path = attachmentMap.get(FlowTypeEnums.FileName.CBQ.getStatus());
  176. FileInputStream fileInputStream = new FileInputStream(Global.getProfile() + path.substring(8));
  177. XWPFDocument document = new XWPFDocument(fileInputStream);
  178. List<XWPFTable> tables = document.getTables();
  179. XWPFTable table = tables.get(0);
  180. XWPFTableRow row = table.getRow(3);
  181. XWPFTableCell headCell1 = row.getCell(1);
  182. if (UserEnums.roleType.zhglbmcsld.getId().equals(roleId)) {
  183. List<XWPFParagraph> cellParList = headCell1.getParagraphs();
  184. for (int k = 0; cellParList != null && k < cellParList.size(); ) { //每个格子循环
  185. headCell1.removeParagraph(k);
  186. }
  187. }
  188. XWPFParagraph p = headCell1.addParagraph();
  189. XWPFRun headRun0 = p.createRun();
  190. headRun0.setFontFamily("仿宋_GB2312");
  191. headRun0.setFontSize(15);
  192. headRun0.setText(userName + ":" + comment);
  193. fileInputStream.close();
  194. OutputStream output = new FileOutputStream(Global.getProfile() + path.substring(8));
  195. document.write(output);
  196. output.close();
  197. word2Pdf2(attachmentMap.get(FlowTypeEnums.FileName.CBQ.getStatus()));
  198. }
  199. @Async("threadPoolTaskExecutor")
  200. public void mergeUrl(List<List<String>> rowValue,String dataPath,String deptName,String declarationUrl,List<Map<String,Object>> personnelList) throws Exception {
  201. WordToPdfUtil word = new WordToPdfUtil();
  202. Map map = new HashMap();
  203. map.put("tb:1", rowValue);
  204. map.put("deptName",deptName);
  205. map.put("date",DateUtils.dateTime(new Date()));
  206. //文件地址
  207. String rosterPath = "activiti" + dataPath + "/" + "安徽省" + deptName + "拟聘人员名单.docx";
  208. //模板地址
  209. String tempPath = "static/temp/word/拟聘人员名单.docx";
  210. //生成文件
  211. WordUtils.generateFileToServer(rosterPath, tempPath, map);
  212. String pdfUrl = word.word2Pdf2("/profile/" + rosterPath);
  213. Map<String, String> declarationMap = JSONObject.parseObject(declarationUrl, Map.class);
  214. String pdfnpyrymd = pdfUrl;
  215. String bpqs = declarationMap.get(FlowTypeEnums.FileName.BPQS.getStatus());
  216. String gwpx = declarationMap.get(FlowTypeEnums.FileName.GWPX.getStatus());
  217. String gscl = declarationMap.get(FlowTypeEnums.FileName.GSCL.getStatus());
  218. String tjfj = declarationMap.get(FlowTypeEnums.FileName.TJFJ.getStatus());
  219. String sccl = declarationMap.get(FlowTypeEnums.FileName.SCCL.getStatus());
  220. PDFMergerUtility mergePdf = new PDFMergerUtility();
  221. String fileName = "/合并.pdf";
  222. String path = bpqs;
  223. mergePdf.addSource(Global.getUploadPath()+bpqs.substring(path.indexOf("upload") + 6));
  224. mergePdf.addSource(Global.getProfile()+pdfnpyrymd.substring(8));
  225. mergePdf.addSource(Global.getUploadPath()+gwpx.substring(path.indexOf("upload") + 6));
  226. mergePdf.addSource(Global.getUploadPath()+gscl.substring(path.indexOf("upload") + 6));
  227. mergePdf.addSource(Global.getUploadPath()+tjfj.substring(path.indexOf("upload") + 6));
  228. mergePdf.addSource(Global.getUploadPath()+sccl.substring(path.indexOf("upload") + 6));
  229. for (Map<String, Object> map1 : personnelList) {
  230. //文件地址
  231. String personnelPath = "activiti" + dataPath + "/" + map1.get("name").toString()+"个人报批表.docx";
  232. //模板地址
  233. String personnelTempPath = "static/temp/word/安徽省省直事业单位公开招聘人员报批表.docx";
  234. //生成文件
  235. WordUtils.generateFileToServer(personnelPath, personnelTempPath, map1);
  236. //生成PDF文件
  237. mergePdf.addSource(Global.getProfile()+word.word2Pdf2("/profile/" +personnelPath).substring(8));
  238. }
  239. mergePdf.setDestinationFileName(Global.getProfile() + "/activiti" + dataPath + "/" + fileName);
  240. //合并pdf
  241. try {
  242. try {
  243. mergePdf.mergeDocuments();
  244. } catch (IOException e) {
  245. e.printStackTrace();
  246. }
  247. } catch (Exception e) {
  248. e.printStackTrace();
  249. }
  250. }
  251. @Async("threadPoolTaskExecutor")
  252. public void postPlanMerge(String fileName,String dataPath,String path,Map<String,String> map) throws Exception {
  253. PDFMergerUtility mergePdf = new PDFMergerUtility();
  254. mergePdf.addSource(Global.getUploadPath()+map.get("postSetting").substring(path.indexOf("upload") + 6));
  255. mergePdf.addSource(Global.getUploadPath()+map.get("adjustmentFile").substring(path.indexOf("upload") + 6));
  256. if(StringUtils.isNotEmpty(map.get("scanningCopy")) && !"undefined".equals(map.get("scanningCopy")))
  257. mergePdf.addSource(Global.getUploadPath()+map.get("scanningCopy").substring(path.indexOf("upload") + 6));
  258. mergePdf.addSource(Global.getUploadPath()+word2Pdf2(map.get("quasiProse")).substring(path.indexOf("upload") + 6));
  259. mergePdf.addSource(Global.getUploadPath()+word2Pdf2(map.get("postDescription")).substring(path.indexOf("upload") + 6));
  260. if(StringUtils.isNotEmpty(map.get("informationSheet")) && !"undefined".equals(map.get("informationSheet")))
  261. mergePdf.addSource(Global.getUploadPath()+word2Pdf2(map.get("informationSheet")).substring(path.indexOf("upload") + 6));
  262. FileUploadUtils.getAbsoluteFile(Global.getProfile(), "activiti" + dataPath + "/" + fileName);
  263. mergePdf.setDestinationFileName(Global.getProfile() + "/activiti" + dataPath + "/" + fileName);
  264. //合并pdf
  265. try {
  266. try {
  267. mergePdf.mergeDocuments();
  268. } catch (IOException e) {
  269. e.printStackTrace();
  270. }
  271. } catch (Exception e) {
  272. e.printStackTrace();
  273. }
  274. }
  275. }