package com.ruoyi.common.utils.ahrs; import com.alibaba.fastjson.JSONObject; import com.aspose.words.*; import com.aspose.words.Document; import com.ruoyi.common.config.Global; import com.ruoyi.common.enums.FlowTypeEnums; import com.ruoyi.common.enums.UserEnums; import com.ruoyi.common.utils.DateUtils; import com.ruoyi.common.utils.StringUtils; import com.ruoyi.common.utils.file.FileUploadUtils; import com.ruoyi.common.utils.file.FileUtils; import org.apache.pdfbox.multipdf.PDFMergerUtility; import org.apache.poi.xwpf.usermodel.*; import org.springframework.scheduling.annotation.Async; import java.io.*; import java.util.*; import java.util.List; /** * Description: * * @author flh * @date Created on 2021/1/18 */ public class WordToPdfUtil { public boolean getLicense() { boolean result = false; try { InputStream is =this.getClass().getClassLoader().getResourceAsStream("license.xml"); License aposeLic = new License(); aposeLic.setLicense(is); result = true; } catch (Exception e) { e.printStackTrace(); } return result; } public static void main(String[] args) throws Exception { // WordToPdfUtil bean = new WordToPdfUtil(); // //windows下 // bean.word2Pdf2("D:\\20210831103542.docx","D:\\20210831103542.pdf"); // bean.word2Pdf2("D:\\安徽省安徽警官职业学院人员聘任确认函.docx","D:\\安徽省安徽警官职业学院人员聘任确认函.pdf"); // //linux下 // bean.word2Pdf2("//opt//uploadPath//安徽省演示事业单位二来文承办签.docx","//opt//uploadPath//安徽省演示事业单位二来文承办签.pdf"); // bean.word2Pdf2("//opt//uploadPath//安徽省演示事业单位二人员聘任确认函.docx","//opt//uploadPath//安徽省演示事业单位二人员聘任确认函.pdf"); //确认函盖章 // try { // ElectronicSeal.sealAutoPdfZF("D:\\\\安徽省省教育厅人员聘任确认函(合并).pdf"); // } catch (Exception e) { // e.printStackTrace(); // } } /** * inpath: 输入word的路径,例如: C:\\TEST.doc * outpath: 输出pdf的路径,例如: C:\\TEST.pdf */ public void word2Pdf2(String inpath,String outpath) throws Exception { if (!getLicense()) { // 验证License 若不验证则转化出的pdf文档会有水印产生 System.out.println("非法------------"); return; } long old = System.currentTimeMillis(); File file = new File(outpath); FileOutputStream os = new FileOutputStream(file); //解决乱码 //如果是windows执行,不需要加这个 //TODO 如果是linux执行,需要添加这个***** String sy = System.getProperty("os.name"); if(!sy.toLowerCase().startsWith("win")){ FontSettings.setFontsFolder("/usr/share/fonts",true); } Document doc = new Document(inpath); //Address是将要被转化的word文档 doc.save(os, SaveFormat.PDF);//全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF, EPUB, XPS, SWF 相互转换 long now = System.currentTimeMillis(); System.out.println("共耗时:" + ((now - old) / 1000.0) + "秒"); os.flush(); os.close(); } public String word2Pdf2(String inpath) throws Exception { if (!getLicense()) { // 验证License 若不验证则转化出的pdf文档会有水印产生 System.out.println("非法------------"); return ""; } String outpath = StringUtils.substringBeforeLast(inpath,".")+".pdf"; long old = System.currentTimeMillis(); File file = new File(Global.getProfile() + outpath.substring(8)); FileOutputStream os = new FileOutputStream(file); //解决乱码 //如果是windows执行,不需要加这个 //TODO 如果是linux执行,需要添加这个***** String sy = System.getProperty("os.name"); if(!sy.toLowerCase().startsWith("win")){ FontSettings.setFontsFolder("/usr/share/fonts",true); } Document doc = new Document(Global.getProfile() + inpath.substring(8)); //Address是将要被转化的word文档 PdfSaveOptions options = new PdfSaveOptions(); options.setExportDocumentStructure(true); // Document document = new Document();//新建一个空白pdf文档 // document.removeAllChildren(); // document.appendDocument(doc, ImportFormatMode.USE_DESTINATION_STYLES);//保留样式 doc.save(os, SaveFormat.PDF);//全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF, EPUB, XPS, SWF 相互转换 long now = System.currentTimeMillis(); System.out.println("共耗时:" + ((now - old) / 1000.0) + "秒"); os.flush(); os.close(); return outpath; } /** * @param path pdf输出路径 * @param wordInput word输入流 * @param wordName word文档的名称 */ public void word2pdf(String path, InputStream wordInput, String wordName) throws FileNotFoundException { if (!getLicense()) { // 验证License 若不验证则转化出的pdf文档会有水印产生 System.out.println("非法"); return; } long old = System.currentTimeMillis(); File file = new File(path + wordName + ".pdf"); //新建一个空白pdf文档 FileOutputStream os = new FileOutputStream(file); Document doc = null; //Address是将要被转化的word文档 try { doc = new Document(wordInput); } catch (Exception e) { e.printStackTrace(); } try { doc.save(os, SaveFormat.PDF);//全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF, EPUB, XPS, SWF 相互转换 } catch (Exception e) { e.printStackTrace(); } long now = System.currentTimeMillis(); System.out.println("共耗时:" + ((now - old) / 1000.0) + "秒"); //转化用时 } /** * 设置确认函日期,并转换为PDF * * @param attachmentMap * @return */ @Async("threadPoolTaskExecutor") public void setParameterToFile(Map attachmentMap) throws Exception { String path = Global.getProfile() + attachmentMap.get(FlowTypeEnums.FileName.BDQRH.getStatus()).substring(8); //获取模板文件流 InputStream templateFileStream = new FileInputStream(path); //转为临时模板文件对象 String tempTemplateFilePath = Global.getProfile() + "/" + "tempParameter.docx"; File fileTemp = new File(tempTemplateFilePath); if (!fileTemp.exists()) { fileTemp.createNewFile(); } PathUtil.inputstreamtofile(templateFileStream, fileTemp); //动态生成word WordUtils.process(new HashMap() {{ put("date", DateUtils.datePath2()); }}, tempTemplateFilePath, new File(path)); //删除临时模板文件 FileUtils.deleteFile(tempTemplateFilePath); word2Pdf2(attachmentMap.get(FlowTypeEnums.FileName.BDQRH.getStatus())); // //确认函盖章 // try { // ElectronicSeal.sealAutoPdfZF(Global.getProfile() + attachmentMap.get(FlowTypeEnums.FileName.PDFQRH.getStatus()).substring(8)); // } catch (Exception e) { // e.printStackTrace(); // } } /** * 承办签word插入意见,并转为pdf,此处是初审领导或终审领导审批通过,所以无需更新attachment * * @param comment 意见 * @param attachmentMap 申报附件Map * @throws IOException */ @Async("threadPoolTaskExecutor") public void editword(String roleId, String userName, String comment, Map attachmentMap) throws Exception { String path = attachmentMap.get(FlowTypeEnums.FileName.CBQ.getStatus()); FileInputStream fileInputStream = new FileInputStream(Global.getProfile() + path.substring(8)); XWPFDocument document = new XWPFDocument(fileInputStream); List tables = document.getTables(); XWPFTable table = tables.get(0); XWPFTableRow row = table.getRow(3); XWPFTableCell headCell1 = row.getCell(1); if (UserEnums.roleType.zhglbmcsld.getId().equals(roleId)) { List cellParList = headCell1.getParagraphs(); for (int k = 0; cellParList != null && k < cellParList.size(); ) { //每个格子循环 headCell1.removeParagraph(k); } } XWPFParagraph p = headCell1.addParagraph(); XWPFRun headRun0 = p.createRun(); headRun0.setFontFamily("仿宋_GB2312"); headRun0.setFontSize(15); headRun0.setText(userName + ":" + comment); fileInputStream.close(); OutputStream output = new FileOutputStream(Global.getProfile() + path.substring(8)); document.write(output); output.close(); word2Pdf2(attachmentMap.get(FlowTypeEnums.FileName.CBQ.getStatus())); } @Async("threadPoolTaskExecutor") public void mergeUrl(List> rowValue,String dataPath,String deptName,String declarationUrl,List> personnelList) throws Exception { WordToPdfUtil word = new WordToPdfUtil(); Map map = new HashMap(); map.put("tb:1", rowValue); map.put("deptName",deptName); map.put("date",DateUtils.dateTime(new Date())); //文件地址 String rosterPath = "activiti" + dataPath + "/" + "安徽省" + deptName + "拟聘人员名单.docx"; //模板地址 String tempPath = "static/temp/word/拟聘人员名单.docx"; //生成文件 WordUtils.generateFileToServer(rosterPath, tempPath, map); String pdfUrl = word.word2Pdf2("/profile/" + rosterPath); Map declarationMap = JSONObject.parseObject(declarationUrl, Map.class); String pdfnpyrymd = pdfUrl; String bpqs = declarationMap.get(FlowTypeEnums.FileName.BPQS.getStatus()); String gwpx = declarationMap.get(FlowTypeEnums.FileName.GWPX.getStatus()); String gscl = declarationMap.get(FlowTypeEnums.FileName.GSCL.getStatus()); String tjfj = declarationMap.get(FlowTypeEnums.FileName.TJFJ.getStatus()); String sccl = declarationMap.get(FlowTypeEnums.FileName.SCCL.getStatus()); PDFMergerUtility mergePdf = new PDFMergerUtility(); String fileName = "/合并.pdf"; String path = bpqs; mergePdf.addSource(Global.getUploadPath()+bpqs.substring(path.indexOf("upload") + 6)); mergePdf.addSource(Global.getProfile()+pdfnpyrymd.substring(8)); mergePdf.addSource(Global.getUploadPath()+gwpx.substring(path.indexOf("upload") + 6)); mergePdf.addSource(Global.getUploadPath()+gscl.substring(path.indexOf("upload") + 6)); mergePdf.addSource(Global.getUploadPath()+tjfj.substring(path.indexOf("upload") + 6)); mergePdf.addSource(Global.getUploadPath()+sccl.substring(path.indexOf("upload") + 6)); for (Map map1 : personnelList) { //文件地址 String personnelPath = "activiti" + dataPath + "/" + map1.get("name").toString()+"个人报批表.docx"; //模板地址 String personnelTempPath = "static/temp/word/安徽省省直事业单位公开招聘人员报批表.docx"; //生成文件 WordUtils.generateFileToServer(personnelPath, personnelTempPath, map1); //生成PDF文件 mergePdf.addSource(Global.getProfile()+word.word2Pdf2("/profile/" +personnelPath).substring(8)); } mergePdf.setDestinationFileName(Global.getProfile() + "/activiti" + dataPath + "/" + fileName); //合并pdf try { try { mergePdf.mergeDocuments(); } catch (IOException e) { e.printStackTrace(); } } catch (Exception e) { e.printStackTrace(); } } @Async("threadPoolTaskExecutor") public void postPlanMerge(String fileName,String dataPath,String path,Map map) throws Exception { PDFMergerUtility mergePdf = new PDFMergerUtility(); mergePdf.addSource(Global.getUploadPath()+map.get("postSetting").substring(path.indexOf("upload") + 6)); mergePdf.addSource(Global.getUploadPath()+map.get("adjustmentFile").substring(path.indexOf("upload") + 6)); if(StringUtils.isNotEmpty(map.get("scanningCopy")) && !"undefined".equals(map.get("scanningCopy"))) mergePdf.addSource(Global.getUploadPath()+map.get("scanningCopy").substring(path.indexOf("upload") + 6)); mergePdf.addSource(Global.getUploadPath()+word2Pdf2(map.get("quasiProse")).substring(path.indexOf("upload") + 6)); mergePdf.addSource(Global.getUploadPath()+word2Pdf2(map.get("postDescription")).substring(path.indexOf("upload") + 6)); if(StringUtils.isNotEmpty(map.get("informationSheet")) && !"undefined".equals(map.get("informationSheet"))) mergePdf.addSource(Global.getUploadPath()+word2Pdf2(map.get("informationSheet")).substring(path.indexOf("upload") + 6)); FileUploadUtils.getAbsoluteFile(Global.getProfile(), "activiti" + dataPath + "/" + fileName); mergePdf.setDestinationFileName(Global.getProfile() + "/activiti" + dataPath + "/" + fileName); //合并pdf try { try { mergePdf.mergeDocuments(); } catch (IOException e) { e.printStackTrace(); } } catch (Exception e) { e.printStackTrace(); } } }