diff --git a/casic-metering-api/src/main/java/com/casic/missiles/controller/business/BusinessCertificateReportController.java b/casic-metering-api/src/main/java/com/casic/missiles/controller/business/BusinessCertificateReportController.java index c440253..408b580 100644 --- a/casic-metering-api/src/main/java/com/casic/missiles/controller/business/BusinessCertificateReportController.java +++ b/casic-metering-api/src/main/java/com/casic/missiles/controller/business/BusinessCertificateReportController.java @@ -9,17 +9,13 @@ import com.casic.missiles.dto.business.certificate.CertificateReportApprovalRequest; import com.casic.missiles.dto.business.certificate.CertificateReportResponse; import com.casic.missiles.dto.flowable.ApprovalDeleteRequest; -import com.casic.missiles.dto.meter.TraceSupplierListRequest; import com.casic.missiles.enums.BusinessExceptionEnum; import com.casic.missiles.exception.BusinessException; import com.casic.missiles.model.business.BusinessCertificateReport; import com.casic.missiles.model.exception.enums.CoreExceptionEnum; -import com.casic.missiles.model.meter.MeterTraceSupplier; import com.casic.missiles.service.business.IBusinessCertificateReportService; -import com.casic.missiles.service.meter.IMeterTraceSupplierService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.util.CollectionUtils; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.*; @@ -45,28 +41,7 @@ public class BusinessCertificateReportController extends ExportController { @Resource private IBusinessCertificateReportService certificateReportService; - @Autowired - private IMeterTraceSupplierService traceSupplierService; - @ApiOperation("证书报告列表(分页)") - @PostMapping("/listPage") - @ResponseBody - public ReturnDTO> supplierListPage(@RequestBody @Valid TraceSupplierListRequest request, BindingResult bindingResult) { - if (bindingResult.hasErrors()) { - throw new BusinessException(CoreExceptionEnum.REQUEST_NULL.getCode(), bindingResult.getFieldError().getDefaultMessage()); - } - Page page = PageFactory.defaultPage(); - return ReturnUtil.success(super.packForBT(traceSupplierService.listPage(page, request))); - } - @ApiOperation("证书报告列表") - @PostMapping("/list") - @ResponseBody - public ReturnDTO> supplierList(@RequestBody @Valid TraceSupplierListRequest request, BindingResult bindingResult) { - if (bindingResult.hasErrors()) { - throw new BusinessException(CoreExceptionEnum.REQUEST_NULL.getCode(), bindingResult.getFieldError().getDefaultMessage()); - } - return ReturnUtil.success(traceSupplierService.list(request)); - } @ApiOperation("证书报告记录导出") @PostMapping("/listExport") @@ -113,18 +88,6 @@ return certificateReportService.submitCertificateReport(request); } - @ApiOperation("证书报告更新(审批通过后还能更新??暂时保留。。)") - @PostMapping("/update") - @ResponseBody - public ReturnDTO supplierUpdate(@RequestBody @Valid MeterTraceSupplier traceSupplier, BindingResult bindingResult) { - Assert.isFalse(Objects.isNull(traceSupplier.getId()), () -> { - throw new BusinessException(BusinessExceptionEnum.ID_NULL); - }); - Assert.isFalse(bindingResult.hasErrors(), () -> { - throw new BusinessException(CoreExceptionEnum.REQUEST_NULL.getCode(), bindingResult.getFieldError().getDefaultMessage()); - }); - return traceSupplierService.updateTraceSupplier(traceSupplier); - } @ApiOperation("证书报告批量删除") @PostMapping("/batchDelete") diff --git a/casic-metering-api/src/main/java/com/casic/missiles/controller/business/BusinessCertificateReportController.java b/casic-metering-api/src/main/java/com/casic/missiles/controller/business/BusinessCertificateReportController.java index c440253..408b580 100644 --- a/casic-metering-api/src/main/java/com/casic/missiles/controller/business/BusinessCertificateReportController.java +++ b/casic-metering-api/src/main/java/com/casic/missiles/controller/business/BusinessCertificateReportController.java @@ -9,17 +9,13 @@ import com.casic.missiles.dto.business.certificate.CertificateReportApprovalRequest; import com.casic.missiles.dto.business.certificate.CertificateReportResponse; import com.casic.missiles.dto.flowable.ApprovalDeleteRequest; -import com.casic.missiles.dto.meter.TraceSupplierListRequest; import com.casic.missiles.enums.BusinessExceptionEnum; import com.casic.missiles.exception.BusinessException; import com.casic.missiles.model.business.BusinessCertificateReport; import com.casic.missiles.model.exception.enums.CoreExceptionEnum; -import com.casic.missiles.model.meter.MeterTraceSupplier; import com.casic.missiles.service.business.IBusinessCertificateReportService; -import com.casic.missiles.service.meter.IMeterTraceSupplierService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.util.CollectionUtils; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.*; @@ -45,28 +41,7 @@ public class BusinessCertificateReportController extends ExportController { @Resource private IBusinessCertificateReportService certificateReportService; - @Autowired - private IMeterTraceSupplierService traceSupplierService; - @ApiOperation("证书报告列表(分页)") - @PostMapping("/listPage") - @ResponseBody - public ReturnDTO> supplierListPage(@RequestBody @Valid TraceSupplierListRequest request, BindingResult bindingResult) { - if (bindingResult.hasErrors()) { - throw new BusinessException(CoreExceptionEnum.REQUEST_NULL.getCode(), bindingResult.getFieldError().getDefaultMessage()); - } - Page page = PageFactory.defaultPage(); - return ReturnUtil.success(super.packForBT(traceSupplierService.listPage(page, request))); - } - @ApiOperation("证书报告列表") - @PostMapping("/list") - @ResponseBody - public ReturnDTO> supplierList(@RequestBody @Valid TraceSupplierListRequest request, BindingResult bindingResult) { - if (bindingResult.hasErrors()) { - throw new BusinessException(CoreExceptionEnum.REQUEST_NULL.getCode(), bindingResult.getFieldError().getDefaultMessage()); - } - return ReturnUtil.success(traceSupplierService.list(request)); - } @ApiOperation("证书报告记录导出") @PostMapping("/listExport") @@ -113,18 +88,6 @@ return certificateReportService.submitCertificateReport(request); } - @ApiOperation("证书报告更新(审批通过后还能更新??暂时保留。。)") - @PostMapping("/update") - @ResponseBody - public ReturnDTO supplierUpdate(@RequestBody @Valid MeterTraceSupplier traceSupplier, BindingResult bindingResult) { - Assert.isFalse(Objects.isNull(traceSupplier.getId()), () -> { - throw new BusinessException(BusinessExceptionEnum.ID_NULL); - }); - Assert.isFalse(bindingResult.hasErrors(), () -> { - throw new BusinessException(CoreExceptionEnum.REQUEST_NULL.getCode(), bindingResult.getFieldError().getDefaultMessage()); - }); - return traceSupplierService.updateTraceSupplier(traceSupplier); - } @ApiOperation("证书报告批量删除") @PostMapping("/batchDelete") diff --git a/casic-metering-api/src/main/java/com/casic/missiles/controller/system/PoiController.java b/casic-metering-api/src/main/java/com/casic/missiles/controller/system/PoiController.java index 021eaa8..9848e68 100644 --- a/casic-metering-api/src/main/java/com/casic/missiles/controller/system/PoiController.java +++ b/casic-metering-api/src/main/java/com/casic/missiles/controller/system/PoiController.java @@ -3,12 +3,14 @@ import cn.afterturn.easypoi.entity.ImageEntity; import com.casic.missiles.utils.PdfUtil; +import com.casic.missiles.utils.StampUtils; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.stereotype.Controller; import org.springframework.util.Assert; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpServletResponse; import java.io.*; @@ -23,7 +25,51 @@ private String filepath="C:\\upload"; @ApiOperation("word转pdf") + @PostMapping(value = "/convertWordToPdf1") + @ResponseBody + public void convertWordToPdf1() throws Exception { + File uploadFile = new File(filepath); + String wordDir = ""; + if (!uploadFile.exists()) { + uploadFile.mkdirs(); + } + if (!filepath.endsWith("/")) { + wordDir = filepath + File.separator + "word"; + } + File tf = new File(wordDir + File.separator + "tem.docx"); + File tf_pic = new File(wordDir + File.separator + "logo.jpg"); + String pic_url = tf_pic.getCanonicalPath(); + Calendar now = Calendar.getInstance(); + Map params = new HashMap<>(); + List> dataList=new ArrayList<>(); + for (int i = 0; i < 5; i++) { + Map param = new HashMap<>(); + param.put("name", "彭于晏"+i); + param.put("sex", "男"+i); + param.put("address", "中国"+i); + ImageEntity image = new ImageEntity(); + image.setHeight(100); + image.setWidth(100); + image.setUrl(pic_url); + image.setData(PdfUtil.getImageBase64(pic_url)); + param.put("image", image); + dataList.add(param); + } + + params.put("dataList",dataList); + params.put("y", now.get(Calendar.YEAR)); + params.put("m", (now.get(Calendar.MONTH) + 1)); + params.put("d", now.get(Calendar.DAY_OF_MONTH)); + + String fileName = "wordExport.docx"; + String word = StampUtils.exportWord(tf.getPath(), wordDir, fileName, params); + System.out.println("****新模板"+word); + + } + + @ApiOperation("word转pdf") @PostMapping(value = "/convertWordToPdf") + @ResponseBody public void convertWordToPdf(HttpServletResponse response) throws Exception { File uploadFile = new File(filepath); String wordDir = ""; @@ -117,4 +163,5 @@ } } } + } diff --git a/casic-metering-api/src/main/java/com/casic/missiles/controller/business/BusinessCertificateReportController.java b/casic-metering-api/src/main/java/com/casic/missiles/controller/business/BusinessCertificateReportController.java index c440253..408b580 100644 --- a/casic-metering-api/src/main/java/com/casic/missiles/controller/business/BusinessCertificateReportController.java +++ b/casic-metering-api/src/main/java/com/casic/missiles/controller/business/BusinessCertificateReportController.java @@ -9,17 +9,13 @@ import com.casic.missiles.dto.business.certificate.CertificateReportApprovalRequest; import com.casic.missiles.dto.business.certificate.CertificateReportResponse; import com.casic.missiles.dto.flowable.ApprovalDeleteRequest; -import com.casic.missiles.dto.meter.TraceSupplierListRequest; import com.casic.missiles.enums.BusinessExceptionEnum; import com.casic.missiles.exception.BusinessException; import com.casic.missiles.model.business.BusinessCertificateReport; import com.casic.missiles.model.exception.enums.CoreExceptionEnum; -import com.casic.missiles.model.meter.MeterTraceSupplier; import com.casic.missiles.service.business.IBusinessCertificateReportService; -import com.casic.missiles.service.meter.IMeterTraceSupplierService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.util.CollectionUtils; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.*; @@ -45,28 +41,7 @@ public class BusinessCertificateReportController extends ExportController { @Resource private IBusinessCertificateReportService certificateReportService; - @Autowired - private IMeterTraceSupplierService traceSupplierService; - @ApiOperation("证书报告列表(分页)") - @PostMapping("/listPage") - @ResponseBody - public ReturnDTO> supplierListPage(@RequestBody @Valid TraceSupplierListRequest request, BindingResult bindingResult) { - if (bindingResult.hasErrors()) { - throw new BusinessException(CoreExceptionEnum.REQUEST_NULL.getCode(), bindingResult.getFieldError().getDefaultMessage()); - } - Page page = PageFactory.defaultPage(); - return ReturnUtil.success(super.packForBT(traceSupplierService.listPage(page, request))); - } - @ApiOperation("证书报告列表") - @PostMapping("/list") - @ResponseBody - public ReturnDTO> supplierList(@RequestBody @Valid TraceSupplierListRequest request, BindingResult bindingResult) { - if (bindingResult.hasErrors()) { - throw new BusinessException(CoreExceptionEnum.REQUEST_NULL.getCode(), bindingResult.getFieldError().getDefaultMessage()); - } - return ReturnUtil.success(traceSupplierService.list(request)); - } @ApiOperation("证书报告记录导出") @PostMapping("/listExport") @@ -113,18 +88,6 @@ return certificateReportService.submitCertificateReport(request); } - @ApiOperation("证书报告更新(审批通过后还能更新??暂时保留。。)") - @PostMapping("/update") - @ResponseBody - public ReturnDTO supplierUpdate(@RequestBody @Valid MeterTraceSupplier traceSupplier, BindingResult bindingResult) { - Assert.isFalse(Objects.isNull(traceSupplier.getId()), () -> { - throw new BusinessException(BusinessExceptionEnum.ID_NULL); - }); - Assert.isFalse(bindingResult.hasErrors(), () -> { - throw new BusinessException(CoreExceptionEnum.REQUEST_NULL.getCode(), bindingResult.getFieldError().getDefaultMessage()); - }); - return traceSupplierService.updateTraceSupplier(traceSupplier); - } @ApiOperation("证书报告批量删除") @PostMapping("/batchDelete") diff --git a/casic-metering-api/src/main/java/com/casic/missiles/controller/system/PoiController.java b/casic-metering-api/src/main/java/com/casic/missiles/controller/system/PoiController.java index 021eaa8..9848e68 100644 --- a/casic-metering-api/src/main/java/com/casic/missiles/controller/system/PoiController.java +++ b/casic-metering-api/src/main/java/com/casic/missiles/controller/system/PoiController.java @@ -3,12 +3,14 @@ import cn.afterturn.easypoi.entity.ImageEntity; import com.casic.missiles.utils.PdfUtil; +import com.casic.missiles.utils.StampUtils; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.stereotype.Controller; import org.springframework.util.Assert; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpServletResponse; import java.io.*; @@ -23,7 +25,51 @@ private String filepath="C:\\upload"; @ApiOperation("word转pdf") + @PostMapping(value = "/convertWordToPdf1") + @ResponseBody + public void convertWordToPdf1() throws Exception { + File uploadFile = new File(filepath); + String wordDir = ""; + if (!uploadFile.exists()) { + uploadFile.mkdirs(); + } + if (!filepath.endsWith("/")) { + wordDir = filepath + File.separator + "word"; + } + File tf = new File(wordDir + File.separator + "tem.docx"); + File tf_pic = new File(wordDir + File.separator + "logo.jpg"); + String pic_url = tf_pic.getCanonicalPath(); + Calendar now = Calendar.getInstance(); + Map params = new HashMap<>(); + List> dataList=new ArrayList<>(); + for (int i = 0; i < 5; i++) { + Map param = new HashMap<>(); + param.put("name", "彭于晏"+i); + param.put("sex", "男"+i); + param.put("address", "中国"+i); + ImageEntity image = new ImageEntity(); + image.setHeight(100); + image.setWidth(100); + image.setUrl(pic_url); + image.setData(PdfUtil.getImageBase64(pic_url)); + param.put("image", image); + dataList.add(param); + } + + params.put("dataList",dataList); + params.put("y", now.get(Calendar.YEAR)); + params.put("m", (now.get(Calendar.MONTH) + 1)); + params.put("d", now.get(Calendar.DAY_OF_MONTH)); + + String fileName = "wordExport.docx"; + String word = StampUtils.exportWord(tf.getPath(), wordDir, fileName, params); + System.out.println("****新模板"+word); + + } + + @ApiOperation("word转pdf") @PostMapping(value = "/convertWordToPdf") + @ResponseBody public void convertWordToPdf(HttpServletResponse response) throws Exception { File uploadFile = new File(filepath); String wordDir = ""; @@ -117,4 +163,5 @@ } } } + } diff --git a/casic-metering-common/pom.xml b/casic-metering-common/pom.xml index bb00ab9..e028713 100644 --- a/casic-metering-common/pom.xml +++ b/casic-metering-common/pom.xml @@ -11,6 +11,7 @@ casic-metering-common + @@ -171,6 +172,14 @@ 4.1.2 + + + + e-iceblue + spire.office.free + 5.3.1 + + com.google.zxing diff --git a/casic-metering-api/src/main/java/com/casic/missiles/controller/business/BusinessCertificateReportController.java b/casic-metering-api/src/main/java/com/casic/missiles/controller/business/BusinessCertificateReportController.java index c440253..408b580 100644 --- a/casic-metering-api/src/main/java/com/casic/missiles/controller/business/BusinessCertificateReportController.java +++ b/casic-metering-api/src/main/java/com/casic/missiles/controller/business/BusinessCertificateReportController.java @@ -9,17 +9,13 @@ import com.casic.missiles.dto.business.certificate.CertificateReportApprovalRequest; import com.casic.missiles.dto.business.certificate.CertificateReportResponse; import com.casic.missiles.dto.flowable.ApprovalDeleteRequest; -import com.casic.missiles.dto.meter.TraceSupplierListRequest; import com.casic.missiles.enums.BusinessExceptionEnum; import com.casic.missiles.exception.BusinessException; import com.casic.missiles.model.business.BusinessCertificateReport; import com.casic.missiles.model.exception.enums.CoreExceptionEnum; -import com.casic.missiles.model.meter.MeterTraceSupplier; import com.casic.missiles.service.business.IBusinessCertificateReportService; -import com.casic.missiles.service.meter.IMeterTraceSupplierService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.util.CollectionUtils; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.*; @@ -45,28 +41,7 @@ public class BusinessCertificateReportController extends ExportController { @Resource private IBusinessCertificateReportService certificateReportService; - @Autowired - private IMeterTraceSupplierService traceSupplierService; - @ApiOperation("证书报告列表(分页)") - @PostMapping("/listPage") - @ResponseBody - public ReturnDTO> supplierListPage(@RequestBody @Valid TraceSupplierListRequest request, BindingResult bindingResult) { - if (bindingResult.hasErrors()) { - throw new BusinessException(CoreExceptionEnum.REQUEST_NULL.getCode(), bindingResult.getFieldError().getDefaultMessage()); - } - Page page = PageFactory.defaultPage(); - return ReturnUtil.success(super.packForBT(traceSupplierService.listPage(page, request))); - } - @ApiOperation("证书报告列表") - @PostMapping("/list") - @ResponseBody - public ReturnDTO> supplierList(@RequestBody @Valid TraceSupplierListRequest request, BindingResult bindingResult) { - if (bindingResult.hasErrors()) { - throw new BusinessException(CoreExceptionEnum.REQUEST_NULL.getCode(), bindingResult.getFieldError().getDefaultMessage()); - } - return ReturnUtil.success(traceSupplierService.list(request)); - } @ApiOperation("证书报告记录导出") @PostMapping("/listExport") @@ -113,18 +88,6 @@ return certificateReportService.submitCertificateReport(request); } - @ApiOperation("证书报告更新(审批通过后还能更新??暂时保留。。)") - @PostMapping("/update") - @ResponseBody - public ReturnDTO supplierUpdate(@RequestBody @Valid MeterTraceSupplier traceSupplier, BindingResult bindingResult) { - Assert.isFalse(Objects.isNull(traceSupplier.getId()), () -> { - throw new BusinessException(BusinessExceptionEnum.ID_NULL); - }); - Assert.isFalse(bindingResult.hasErrors(), () -> { - throw new BusinessException(CoreExceptionEnum.REQUEST_NULL.getCode(), bindingResult.getFieldError().getDefaultMessage()); - }); - return traceSupplierService.updateTraceSupplier(traceSupplier); - } @ApiOperation("证书报告批量删除") @PostMapping("/batchDelete") diff --git a/casic-metering-api/src/main/java/com/casic/missiles/controller/system/PoiController.java b/casic-metering-api/src/main/java/com/casic/missiles/controller/system/PoiController.java index 021eaa8..9848e68 100644 --- a/casic-metering-api/src/main/java/com/casic/missiles/controller/system/PoiController.java +++ b/casic-metering-api/src/main/java/com/casic/missiles/controller/system/PoiController.java @@ -3,12 +3,14 @@ import cn.afterturn.easypoi.entity.ImageEntity; import com.casic.missiles.utils.PdfUtil; +import com.casic.missiles.utils.StampUtils; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.stereotype.Controller; import org.springframework.util.Assert; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpServletResponse; import java.io.*; @@ -23,7 +25,51 @@ private String filepath="C:\\upload"; @ApiOperation("word转pdf") + @PostMapping(value = "/convertWordToPdf1") + @ResponseBody + public void convertWordToPdf1() throws Exception { + File uploadFile = new File(filepath); + String wordDir = ""; + if (!uploadFile.exists()) { + uploadFile.mkdirs(); + } + if (!filepath.endsWith("/")) { + wordDir = filepath + File.separator + "word"; + } + File tf = new File(wordDir + File.separator + "tem.docx"); + File tf_pic = new File(wordDir + File.separator + "logo.jpg"); + String pic_url = tf_pic.getCanonicalPath(); + Calendar now = Calendar.getInstance(); + Map params = new HashMap<>(); + List> dataList=new ArrayList<>(); + for (int i = 0; i < 5; i++) { + Map param = new HashMap<>(); + param.put("name", "彭于晏"+i); + param.put("sex", "男"+i); + param.put("address", "中国"+i); + ImageEntity image = new ImageEntity(); + image.setHeight(100); + image.setWidth(100); + image.setUrl(pic_url); + image.setData(PdfUtil.getImageBase64(pic_url)); + param.put("image", image); + dataList.add(param); + } + + params.put("dataList",dataList); + params.put("y", now.get(Calendar.YEAR)); + params.put("m", (now.get(Calendar.MONTH) + 1)); + params.put("d", now.get(Calendar.DAY_OF_MONTH)); + + String fileName = "wordExport.docx"; + String word = StampUtils.exportWord(tf.getPath(), wordDir, fileName, params); + System.out.println("****新模板"+word); + + } + + @ApiOperation("word转pdf") @PostMapping(value = "/convertWordToPdf") + @ResponseBody public void convertWordToPdf(HttpServletResponse response) throws Exception { File uploadFile = new File(filepath); String wordDir = ""; @@ -117,4 +163,5 @@ } } } + } diff --git a/casic-metering-common/pom.xml b/casic-metering-common/pom.xml index bb00ab9..e028713 100644 --- a/casic-metering-common/pom.xml +++ b/casic-metering-common/pom.xml @@ -11,6 +11,7 @@ casic-metering-common + @@ -171,6 +172,14 @@ 4.1.2 + + + + e-iceblue + spire.office.free + 5.3.1 + + com.google.zxing diff --git a/casic-metering-common/src/main/java/com/casic/missiles/utils/CustomXWPFDocumentUtil.java b/casic-metering-common/src/main/java/com/casic/missiles/utils/CustomXWPFDocumentUtil.java deleted file mode 100644 index 9e7ed3f..0000000 --- a/casic-metering-common/src/main/java/com/casic/missiles/utils/CustomXWPFDocumentUtil.java +++ /dev/null @@ -1,309 +0,0 @@ -package com.casic.missiles.utils; - -import java.io.*; -import java.util.*; -import java.util.Map.Entry; - -import cn.afterturn.easypoi.entity.ImageEntity; -import org.apache.commons.lang3.StringUtils; -import org.apache.poi.ooxml.POIXMLDocument; -import org.apache.poi.openxml4j.exceptions.InvalidFormatException; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.util.Units; -import org.apache.poi.xwpf.usermodel.*; -import org.apache.xmlbeans.XmlException; -import org.apache.xmlbeans.XmlToken; -import org.openxmlformats.schemas.drawingml.x2006.main.CTGraphicalObject; -import org.openxmlformats.schemas.drawingml.x2006.main.CTNonVisualDrawingProps; -import org.openxmlformats.schemas.drawingml.x2006.main.CTPositiveSize2D; -import org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.CTAnchor; -import org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.CTInline; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTDrawing; - -public class CustomXWPFDocumentUtil extends XWPFDocument { - - public CustomXWPFDocumentUtil(InputStream in) throws IOException { - super(in); - } - - public CustomXWPFDocumentUtil() { - super(); - } - - public CustomXWPFDocumentUtil(OPCPackage pkg) throws IOException { - super(pkg); - } - - /** - * 根据指定的参数值、模板,生成 word 文档 - * - * @param param 需要替换的变量 - * @param template 模板 - */ - public static XWPFDocument generateWord(Map param, String template) { - XWPFDocument doc = null; - try { - OPCPackage pack = POIXMLDocument.openPackage(template); - doc = new CustomXWPFDocumentUtil(pack); - if (param != null && param.size() > 0) { - - //处理段落 - List paragraphList = doc.getParagraphs(); - processParagraphs(paragraphList, param, doc); - - //处理表格 - Iterator it = doc.getTablesIterator(); - while (it.hasNext()) { - XWPFTable table = it.next(); - List rows = table.getRows(); - for (XWPFTableRow row : rows) { - List cells = row.getTableCells(); - for (XWPFTableCell cell : cells) { - List paragraphListTable = cell.getParagraphs(); - processParagraphs(paragraphListTable, param, doc); - } - } - } - } - } catch (IOException e) { - e.printStackTrace(); - } catch (Exception e) { - e.printStackTrace(); - } - return doc; - } - - /** - * 处理段落 - * - * @param paragraphList - * @param - * @throws FileNotFoundException - * @throws InvalidFormatException - */ - public static void processParagraphs(List paragraphList, Map param, XWPFDocument doc) throws InvalidFormatException, FileNotFoundException { - if (paragraphList != null && paragraphList.size() > 0) { - for (XWPFParagraph paragraph : paragraphList) { - List runs = paragraph.getRuns(); - for (XWPFRun run : runs) { - String text = run.getText(0); - //System.out.println("text=="+text); - if (text != null) { - boolean isSetText = false; - for (Entry entry : param.entrySet()) { - String key = entry.getKey(); - if (text.indexOf(key) != -1) { - isSetText = true; - Object value = entry.getValue(); - if (value instanceof String) {//文本替换 - //System.out.println("key=="+key); - text = text.replace(key, value.toString()); - } else if (value instanceof Map) { //图片替换 - text = text.replace(text, ""); - Map pic = (Map) value; - int width = Integer.parseInt(pic.get("width").toString()); - int height = Integer.parseInt(pic.get("height").toString()); - int picType = getPictureType(pic.get("type").toString()); - String picPath = (String) pic.get("picPath"); - CTInline inline = run.getCTR().addNewDrawing().addNewInline(); - insertPicture(doc, picPath, inline, width, height); - CTDrawing drawing = run.getCTR().getDrawingArray(0); - CTGraphicalObject graphicalobject = drawing.getInlineArray(0).getGraphic(); - //拿到新插入的图片替换添加CTAnchor 设置浮动属性 删除inline属性 - CTAnchor anchor = getAnchorWithGraphic(graphicalobject, "11", - Units.toEMU(width), Units.toEMU(height),//图片大小 - Units.toEMU(0), Units.toEMU(0));//相对当前段落位置的偏移位置,左右偏移:负数向左,正数向右,上下偏移:负数向上,正数向下 - drawing.setAnchorArray(new CTAnchor[]{anchor});//添加浮动属性 - drawing.removeInline(0);//删除行内属性 - } - } - } - if (isSetText) { - run.setText(text, 0); - } - } - } - } - } - } - - /** - * 根据图片类型,取得对应的图片类型代码 - * - * @param picType - * @return int - */ - private static int getPictureType(String picType) { - int res = CustomXWPFDocumentUtil.PICTURE_TYPE_PICT; - if (picType != null) { - if (picType.equalsIgnoreCase("png")) { - res = CustomXWPFDocumentUtil.PICTURE_TYPE_PNG; - } else if (picType.equalsIgnoreCase("dib")) { - res = CustomXWPFDocumentUtil.PICTURE_TYPE_DIB; - } else if (picType.equalsIgnoreCase("emf")) { - res = CustomXWPFDocumentUtil.PICTURE_TYPE_EMF; - } else if (picType.equalsIgnoreCase("jpg") || picType.equalsIgnoreCase("jpeg")) { - res = CustomXWPFDocumentUtil.PICTURE_TYPE_JPEG; - } else if (picType.equalsIgnoreCase("wmf")) { - res = CustomXWPFDocumentUtil.PICTURE_TYPE_WMF; - } - } - return res; - } - - /** - * insert Picture - * - * @param document - * @param filePath - * @param inline - * @param width - * @param height - * @throws InvalidFormatException - * @throws FileNotFoundException - */ - private static void insertPicture(XWPFDocument document, String filePath, - CTInline inline, int width, - int height) throws InvalidFormatException, - FileNotFoundException { - document.addPictureData(new FileInputStream(filePath), XWPFDocument.PICTURE_TYPE_PNG); - int id = document.getAllPictures().size() - 1; - final int EMU = 9525; - width *= EMU; - height *= EMU; - String blipId = - document.getAllPictures().get(id).getRelationId(document); - String picXml = getPicXml(blipId, width, height); - XmlToken xmlToken = null; - try { - xmlToken = XmlToken.Factory.parse(picXml); - } catch (XmlException xe) { - xe.printStackTrace(); - } - inline.set(xmlToken); - inline.setDistT(0); - inline.setDistB(0); - inline.setDistL(0); - inline.setDistR(0); - CTPositiveSize2D extent = inline.addNewExtent(); - extent.setCx(width); - extent.setCy(height); - CTNonVisualDrawingProps docPr = inline.addNewDocPr(); - docPr.setId(id); - docPr.setName("IMG_" + id); - docPr.setDescr("IMG_" + id); - } - - /** - * get the xml of the picture - * - * @param blipId - * @param width - * @param height - * @return - */ - private static String getPicXml(String blipId, int width, int height) { - String picXml = - "" + "" + - " " + - " " + - " " + " " + " " + - " " + " " + - " " + - " " + " " + - " " + " " + - " " + " " + - " " + - " " + " " + - " " + - " " + " " + - " " + " " + - " " + ""; - return picXml; - } - - /** - * @param ctGraphicalObject 图片数据 - * @param deskFileName 图片描述 - * @param width 宽 - * @param height 高 - * @param leftOffset 水平偏移:负数向左,正数向右 - * @param topOffset 垂直偏移:负数向上,正数向下 - * @return CTAnchor - * @throws Exception - */ - public static CTAnchor getAnchorWithGraphic(CTGraphicalObject ctGraphicalObject, - String deskFileName, int width, int height, - int leftOffset, int topOffset) { - //浮在文字上的设置主要是anchor标签下的behindDoc属性设为0,同时添加一个的空标签。 - if (StringUtils.isBlank(deskFileName)) { - deskFileName = new Random().nextInt(999) + "";//描述不能为空,赋值一个随机数 - } - String anchorXML = - "" - + "" - + "" - + "" + leftOffset + "" - + "" - + "" - + "" + topOffset + "" + - "" - + "" - + "" - + "" - + "" - + ""; - CTDrawing drawing = null; - try { - drawing = CTDrawing.Factory.parse(anchorXML); - } catch (XmlException e) { - e.printStackTrace(); - } - CTAnchor anchor = drawing.getAnchorArray(0); - anchor.setGraphic(ctGraphicalObject); - return anchor; - } - public static void main(String[] args) throws IOException{ - Map params = new HashMap<>(); - List> dataList=new ArrayList<>(); - for (int i = 0; i < 5; i++) { - Map param = new HashMap<>(); - param.put("name", "彭于晏"+i); - param.put("sex", "男"+i); - param.put("address", "中国"+i); - ImageEntity image = new ImageEntity(); - image.setHeight(100); - image.setWidth(100); - image.setUrl("C:\\upload\\word\\"); - image.setData(PdfUtil.getImageBase64("C:\\upload\\word\\logo.jpg")); - param.put("image", image); - dataList.add(param); - } - Calendar now = Calendar.getInstance(); - params.put("dataList",dataList); - params.put("y", now.get(Calendar.YEAR)+""); - params.put("m", (now.get(Calendar.MONTH) + 1)+""); - params.put("d", now.get(Calendar.DAY_OF_MONTH)+""); - String template="C:\\upload\\word\\tem.docx"; - ByteArrayOutputStream baos = null; - try { - XWPFDocument document = generateWord(params, template); - baos = new ByteArrayOutputStream(); - document.write(baos);//临时存储流到内存 - baos.flush(); - } catch (Exception e) { - e.printStackTrace(); - }finally{ - if(baos != null){ - baos.close(); - } - } - - - } - -} diff --git a/casic-metering-api/src/main/java/com/casic/missiles/controller/business/BusinessCertificateReportController.java b/casic-metering-api/src/main/java/com/casic/missiles/controller/business/BusinessCertificateReportController.java index c440253..408b580 100644 --- a/casic-metering-api/src/main/java/com/casic/missiles/controller/business/BusinessCertificateReportController.java +++ b/casic-metering-api/src/main/java/com/casic/missiles/controller/business/BusinessCertificateReportController.java @@ -9,17 +9,13 @@ import com.casic.missiles.dto.business.certificate.CertificateReportApprovalRequest; import com.casic.missiles.dto.business.certificate.CertificateReportResponse; import com.casic.missiles.dto.flowable.ApprovalDeleteRequest; -import com.casic.missiles.dto.meter.TraceSupplierListRequest; import com.casic.missiles.enums.BusinessExceptionEnum; import com.casic.missiles.exception.BusinessException; import com.casic.missiles.model.business.BusinessCertificateReport; import com.casic.missiles.model.exception.enums.CoreExceptionEnum; -import com.casic.missiles.model.meter.MeterTraceSupplier; import com.casic.missiles.service.business.IBusinessCertificateReportService; -import com.casic.missiles.service.meter.IMeterTraceSupplierService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.util.CollectionUtils; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.*; @@ -45,28 +41,7 @@ public class BusinessCertificateReportController extends ExportController { @Resource private IBusinessCertificateReportService certificateReportService; - @Autowired - private IMeterTraceSupplierService traceSupplierService; - @ApiOperation("证书报告列表(分页)") - @PostMapping("/listPage") - @ResponseBody - public ReturnDTO> supplierListPage(@RequestBody @Valid TraceSupplierListRequest request, BindingResult bindingResult) { - if (bindingResult.hasErrors()) { - throw new BusinessException(CoreExceptionEnum.REQUEST_NULL.getCode(), bindingResult.getFieldError().getDefaultMessage()); - } - Page page = PageFactory.defaultPage(); - return ReturnUtil.success(super.packForBT(traceSupplierService.listPage(page, request))); - } - @ApiOperation("证书报告列表") - @PostMapping("/list") - @ResponseBody - public ReturnDTO> supplierList(@RequestBody @Valid TraceSupplierListRequest request, BindingResult bindingResult) { - if (bindingResult.hasErrors()) { - throw new BusinessException(CoreExceptionEnum.REQUEST_NULL.getCode(), bindingResult.getFieldError().getDefaultMessage()); - } - return ReturnUtil.success(traceSupplierService.list(request)); - } @ApiOperation("证书报告记录导出") @PostMapping("/listExport") @@ -113,18 +88,6 @@ return certificateReportService.submitCertificateReport(request); } - @ApiOperation("证书报告更新(审批通过后还能更新??暂时保留。。)") - @PostMapping("/update") - @ResponseBody - public ReturnDTO supplierUpdate(@RequestBody @Valid MeterTraceSupplier traceSupplier, BindingResult bindingResult) { - Assert.isFalse(Objects.isNull(traceSupplier.getId()), () -> { - throw new BusinessException(BusinessExceptionEnum.ID_NULL); - }); - Assert.isFalse(bindingResult.hasErrors(), () -> { - throw new BusinessException(CoreExceptionEnum.REQUEST_NULL.getCode(), bindingResult.getFieldError().getDefaultMessage()); - }); - return traceSupplierService.updateTraceSupplier(traceSupplier); - } @ApiOperation("证书报告批量删除") @PostMapping("/batchDelete") diff --git a/casic-metering-api/src/main/java/com/casic/missiles/controller/system/PoiController.java b/casic-metering-api/src/main/java/com/casic/missiles/controller/system/PoiController.java index 021eaa8..9848e68 100644 --- a/casic-metering-api/src/main/java/com/casic/missiles/controller/system/PoiController.java +++ b/casic-metering-api/src/main/java/com/casic/missiles/controller/system/PoiController.java @@ -3,12 +3,14 @@ import cn.afterturn.easypoi.entity.ImageEntity; import com.casic.missiles.utils.PdfUtil; +import com.casic.missiles.utils.StampUtils; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.stereotype.Controller; import org.springframework.util.Assert; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpServletResponse; import java.io.*; @@ -23,7 +25,51 @@ private String filepath="C:\\upload"; @ApiOperation("word转pdf") + @PostMapping(value = "/convertWordToPdf1") + @ResponseBody + public void convertWordToPdf1() throws Exception { + File uploadFile = new File(filepath); + String wordDir = ""; + if (!uploadFile.exists()) { + uploadFile.mkdirs(); + } + if (!filepath.endsWith("/")) { + wordDir = filepath + File.separator + "word"; + } + File tf = new File(wordDir + File.separator + "tem.docx"); + File tf_pic = new File(wordDir + File.separator + "logo.jpg"); + String pic_url = tf_pic.getCanonicalPath(); + Calendar now = Calendar.getInstance(); + Map params = new HashMap<>(); + List> dataList=new ArrayList<>(); + for (int i = 0; i < 5; i++) { + Map param = new HashMap<>(); + param.put("name", "彭于晏"+i); + param.put("sex", "男"+i); + param.put("address", "中国"+i); + ImageEntity image = new ImageEntity(); + image.setHeight(100); + image.setWidth(100); + image.setUrl(pic_url); + image.setData(PdfUtil.getImageBase64(pic_url)); + param.put("image", image); + dataList.add(param); + } + + params.put("dataList",dataList); + params.put("y", now.get(Calendar.YEAR)); + params.put("m", (now.get(Calendar.MONTH) + 1)); + params.put("d", now.get(Calendar.DAY_OF_MONTH)); + + String fileName = "wordExport.docx"; + String word = StampUtils.exportWord(tf.getPath(), wordDir, fileName, params); + System.out.println("****新模板"+word); + + } + + @ApiOperation("word转pdf") @PostMapping(value = "/convertWordToPdf") + @ResponseBody public void convertWordToPdf(HttpServletResponse response) throws Exception { File uploadFile = new File(filepath); String wordDir = ""; @@ -117,4 +163,5 @@ } } } + } diff --git a/casic-metering-common/pom.xml b/casic-metering-common/pom.xml index bb00ab9..e028713 100644 --- a/casic-metering-common/pom.xml +++ b/casic-metering-common/pom.xml @@ -11,6 +11,7 @@ casic-metering-common + @@ -171,6 +172,14 @@ 4.1.2 + + + + e-iceblue + spire.office.free + 5.3.1 + + com.google.zxing diff --git a/casic-metering-common/src/main/java/com/casic/missiles/utils/CustomXWPFDocumentUtil.java b/casic-metering-common/src/main/java/com/casic/missiles/utils/CustomXWPFDocumentUtil.java deleted file mode 100644 index 9e7ed3f..0000000 --- a/casic-metering-common/src/main/java/com/casic/missiles/utils/CustomXWPFDocumentUtil.java +++ /dev/null @@ -1,309 +0,0 @@ -package com.casic.missiles.utils; - -import java.io.*; -import java.util.*; -import java.util.Map.Entry; - -import cn.afterturn.easypoi.entity.ImageEntity; -import org.apache.commons.lang3.StringUtils; -import org.apache.poi.ooxml.POIXMLDocument; -import org.apache.poi.openxml4j.exceptions.InvalidFormatException; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.util.Units; -import org.apache.poi.xwpf.usermodel.*; -import org.apache.xmlbeans.XmlException; -import org.apache.xmlbeans.XmlToken; -import org.openxmlformats.schemas.drawingml.x2006.main.CTGraphicalObject; -import org.openxmlformats.schemas.drawingml.x2006.main.CTNonVisualDrawingProps; -import org.openxmlformats.schemas.drawingml.x2006.main.CTPositiveSize2D; -import org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.CTAnchor; -import org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.CTInline; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTDrawing; - -public class CustomXWPFDocumentUtil extends XWPFDocument { - - public CustomXWPFDocumentUtil(InputStream in) throws IOException { - super(in); - } - - public CustomXWPFDocumentUtil() { - super(); - } - - public CustomXWPFDocumentUtil(OPCPackage pkg) throws IOException { - super(pkg); - } - - /** - * 根据指定的参数值、模板,生成 word 文档 - * - * @param param 需要替换的变量 - * @param template 模板 - */ - public static XWPFDocument generateWord(Map param, String template) { - XWPFDocument doc = null; - try { - OPCPackage pack = POIXMLDocument.openPackage(template); - doc = new CustomXWPFDocumentUtil(pack); - if (param != null && param.size() > 0) { - - //处理段落 - List paragraphList = doc.getParagraphs(); - processParagraphs(paragraphList, param, doc); - - //处理表格 - Iterator it = doc.getTablesIterator(); - while (it.hasNext()) { - XWPFTable table = it.next(); - List rows = table.getRows(); - for (XWPFTableRow row : rows) { - List cells = row.getTableCells(); - for (XWPFTableCell cell : cells) { - List paragraphListTable = cell.getParagraphs(); - processParagraphs(paragraphListTable, param, doc); - } - } - } - } - } catch (IOException e) { - e.printStackTrace(); - } catch (Exception e) { - e.printStackTrace(); - } - return doc; - } - - /** - * 处理段落 - * - * @param paragraphList - * @param - * @throws FileNotFoundException - * @throws InvalidFormatException - */ - public static void processParagraphs(List paragraphList, Map param, XWPFDocument doc) throws InvalidFormatException, FileNotFoundException { - if (paragraphList != null && paragraphList.size() > 0) { - for (XWPFParagraph paragraph : paragraphList) { - List runs = paragraph.getRuns(); - for (XWPFRun run : runs) { - String text = run.getText(0); - //System.out.println("text=="+text); - if (text != null) { - boolean isSetText = false; - for (Entry entry : param.entrySet()) { - String key = entry.getKey(); - if (text.indexOf(key) != -1) { - isSetText = true; - Object value = entry.getValue(); - if (value instanceof String) {//文本替换 - //System.out.println("key=="+key); - text = text.replace(key, value.toString()); - } else if (value instanceof Map) { //图片替换 - text = text.replace(text, ""); - Map pic = (Map) value; - int width = Integer.parseInt(pic.get("width").toString()); - int height = Integer.parseInt(pic.get("height").toString()); - int picType = getPictureType(pic.get("type").toString()); - String picPath = (String) pic.get("picPath"); - CTInline inline = run.getCTR().addNewDrawing().addNewInline(); - insertPicture(doc, picPath, inline, width, height); - CTDrawing drawing = run.getCTR().getDrawingArray(0); - CTGraphicalObject graphicalobject = drawing.getInlineArray(0).getGraphic(); - //拿到新插入的图片替换添加CTAnchor 设置浮动属性 删除inline属性 - CTAnchor anchor = getAnchorWithGraphic(graphicalobject, "11", - Units.toEMU(width), Units.toEMU(height),//图片大小 - Units.toEMU(0), Units.toEMU(0));//相对当前段落位置的偏移位置,左右偏移:负数向左,正数向右,上下偏移:负数向上,正数向下 - drawing.setAnchorArray(new CTAnchor[]{anchor});//添加浮动属性 - drawing.removeInline(0);//删除行内属性 - } - } - } - if (isSetText) { - run.setText(text, 0); - } - } - } - } - } - } - - /** - * 根据图片类型,取得对应的图片类型代码 - * - * @param picType - * @return int - */ - private static int getPictureType(String picType) { - int res = CustomXWPFDocumentUtil.PICTURE_TYPE_PICT; - if (picType != null) { - if (picType.equalsIgnoreCase("png")) { - res = CustomXWPFDocumentUtil.PICTURE_TYPE_PNG; - } else if (picType.equalsIgnoreCase("dib")) { - res = CustomXWPFDocumentUtil.PICTURE_TYPE_DIB; - } else if (picType.equalsIgnoreCase("emf")) { - res = CustomXWPFDocumentUtil.PICTURE_TYPE_EMF; - } else if (picType.equalsIgnoreCase("jpg") || picType.equalsIgnoreCase("jpeg")) { - res = CustomXWPFDocumentUtil.PICTURE_TYPE_JPEG; - } else if (picType.equalsIgnoreCase("wmf")) { - res = CustomXWPFDocumentUtil.PICTURE_TYPE_WMF; - } - } - return res; - } - - /** - * insert Picture - * - * @param document - * @param filePath - * @param inline - * @param width - * @param height - * @throws InvalidFormatException - * @throws FileNotFoundException - */ - private static void insertPicture(XWPFDocument document, String filePath, - CTInline inline, int width, - int height) throws InvalidFormatException, - FileNotFoundException { - document.addPictureData(new FileInputStream(filePath), XWPFDocument.PICTURE_TYPE_PNG); - int id = document.getAllPictures().size() - 1; - final int EMU = 9525; - width *= EMU; - height *= EMU; - String blipId = - document.getAllPictures().get(id).getRelationId(document); - String picXml = getPicXml(blipId, width, height); - XmlToken xmlToken = null; - try { - xmlToken = XmlToken.Factory.parse(picXml); - } catch (XmlException xe) { - xe.printStackTrace(); - } - inline.set(xmlToken); - inline.setDistT(0); - inline.setDistB(0); - inline.setDistL(0); - inline.setDistR(0); - CTPositiveSize2D extent = inline.addNewExtent(); - extent.setCx(width); - extent.setCy(height); - CTNonVisualDrawingProps docPr = inline.addNewDocPr(); - docPr.setId(id); - docPr.setName("IMG_" + id); - docPr.setDescr("IMG_" + id); - } - - /** - * get the xml of the picture - * - * @param blipId - * @param width - * @param height - * @return - */ - private static String getPicXml(String blipId, int width, int height) { - String picXml = - "" + "" + - " " + - " " + - " " + " " + " " + - " " + " " + - " " + - " " + " " + - " " + " " + - " " + " " + - " " + - " " + " " + - " " + - " " + " " + - " " + " " + - " " + ""; - return picXml; - } - - /** - * @param ctGraphicalObject 图片数据 - * @param deskFileName 图片描述 - * @param width 宽 - * @param height 高 - * @param leftOffset 水平偏移:负数向左,正数向右 - * @param topOffset 垂直偏移:负数向上,正数向下 - * @return CTAnchor - * @throws Exception - */ - public static CTAnchor getAnchorWithGraphic(CTGraphicalObject ctGraphicalObject, - String deskFileName, int width, int height, - int leftOffset, int topOffset) { - //浮在文字上的设置主要是anchor标签下的behindDoc属性设为0,同时添加一个的空标签。 - if (StringUtils.isBlank(deskFileName)) { - deskFileName = new Random().nextInt(999) + "";//描述不能为空,赋值一个随机数 - } - String anchorXML = - "" - + "" - + "" - + "" + leftOffset + "" - + "" - + "" - + "" + topOffset + "" + - "" - + "" - + "" - + "" - + "" - + ""; - CTDrawing drawing = null; - try { - drawing = CTDrawing.Factory.parse(anchorXML); - } catch (XmlException e) { - e.printStackTrace(); - } - CTAnchor anchor = drawing.getAnchorArray(0); - anchor.setGraphic(ctGraphicalObject); - return anchor; - } - public static void main(String[] args) throws IOException{ - Map params = new HashMap<>(); - List> dataList=new ArrayList<>(); - for (int i = 0; i < 5; i++) { - Map param = new HashMap<>(); - param.put("name", "彭于晏"+i); - param.put("sex", "男"+i); - param.put("address", "中国"+i); - ImageEntity image = new ImageEntity(); - image.setHeight(100); - image.setWidth(100); - image.setUrl("C:\\upload\\word\\"); - image.setData(PdfUtil.getImageBase64("C:\\upload\\word\\logo.jpg")); - param.put("image", image); - dataList.add(param); - } - Calendar now = Calendar.getInstance(); - params.put("dataList",dataList); - params.put("y", now.get(Calendar.YEAR)+""); - params.put("m", (now.get(Calendar.MONTH) + 1)+""); - params.put("d", now.get(Calendar.DAY_OF_MONTH)+""); - String template="C:\\upload\\word\\tem.docx"; - ByteArrayOutputStream baos = null; - try { - XWPFDocument document = generateWord(params, template); - baos = new ByteArrayOutputStream(); - document.write(baos);//临时存储流到内存 - baos.flush(); - } catch (Exception e) { - e.printStackTrace(); - }finally{ - if(baos != null){ - baos.close(); - } - } - - - } - -} diff --git a/casic-metering-common/src/main/java/com/casic/missiles/utils/PdfUtil.java b/casic-metering-common/src/main/java/com/casic/missiles/utils/PdfUtil.java index 3d80a8e..3e4f58b 100644 --- a/casic-metering-common/src/main/java/com/casic/missiles/utils/PdfUtil.java +++ b/casic-metering-common/src/main/java/com/casic/missiles/utils/PdfUtil.java @@ -23,12 +23,12 @@ public class PdfUtil { /** - * 生成word 只支持docx + * 按照模板 填充数据生成word 只支持docx * * @param templatePath 模板文件路径 - * @param temDir 生成文件的目录 - * @param fileName 生成文件名 - * @param params 参数 + * @param temDir 生成文件的目录 + * @param fileName 生成文件名 + * @param params 参数 */ public static String exportWord(String templatePath, String temDir, String fileName, Map params) { Assert.notNull(templatePath, "模板路径不能为空"); @@ -39,8 +39,9 @@ temDir = temDir + File.separator; } File dir = new File(temDir); - if (!dir.exists()) { - dir.mkdirs(); + if (!dir.getParentFile().exists()) { + // 新建文件夹 + dir.getParentFile().mkdirs(); } String tmpPath = ""; try { @@ -51,13 +52,13 @@ fos.flush(); fos.close(); } catch (Exception e) { - //e.printStackTrace(); + e.printStackTrace(); } return tmpPath; } - public static String convertDocx2Pdf(String wordPath,String pdfPath) { + public static String convertDocx2Pdf(String wordPath, String pdfPath) { OutputStream os = null; InputStream is = null; try { diff --git a/casic-metering-api/src/main/java/com/casic/missiles/controller/business/BusinessCertificateReportController.java b/casic-metering-api/src/main/java/com/casic/missiles/controller/business/BusinessCertificateReportController.java index c440253..408b580 100644 --- a/casic-metering-api/src/main/java/com/casic/missiles/controller/business/BusinessCertificateReportController.java +++ b/casic-metering-api/src/main/java/com/casic/missiles/controller/business/BusinessCertificateReportController.java @@ -9,17 +9,13 @@ import com.casic.missiles.dto.business.certificate.CertificateReportApprovalRequest; import com.casic.missiles.dto.business.certificate.CertificateReportResponse; import com.casic.missiles.dto.flowable.ApprovalDeleteRequest; -import com.casic.missiles.dto.meter.TraceSupplierListRequest; import com.casic.missiles.enums.BusinessExceptionEnum; import com.casic.missiles.exception.BusinessException; import com.casic.missiles.model.business.BusinessCertificateReport; import com.casic.missiles.model.exception.enums.CoreExceptionEnum; -import com.casic.missiles.model.meter.MeterTraceSupplier; import com.casic.missiles.service.business.IBusinessCertificateReportService; -import com.casic.missiles.service.meter.IMeterTraceSupplierService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.util.CollectionUtils; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.*; @@ -45,28 +41,7 @@ public class BusinessCertificateReportController extends ExportController { @Resource private IBusinessCertificateReportService certificateReportService; - @Autowired - private IMeterTraceSupplierService traceSupplierService; - @ApiOperation("证书报告列表(分页)") - @PostMapping("/listPage") - @ResponseBody - public ReturnDTO> supplierListPage(@RequestBody @Valid TraceSupplierListRequest request, BindingResult bindingResult) { - if (bindingResult.hasErrors()) { - throw new BusinessException(CoreExceptionEnum.REQUEST_NULL.getCode(), bindingResult.getFieldError().getDefaultMessage()); - } - Page page = PageFactory.defaultPage(); - return ReturnUtil.success(super.packForBT(traceSupplierService.listPage(page, request))); - } - @ApiOperation("证书报告列表") - @PostMapping("/list") - @ResponseBody - public ReturnDTO> supplierList(@RequestBody @Valid TraceSupplierListRequest request, BindingResult bindingResult) { - if (bindingResult.hasErrors()) { - throw new BusinessException(CoreExceptionEnum.REQUEST_NULL.getCode(), bindingResult.getFieldError().getDefaultMessage()); - } - return ReturnUtil.success(traceSupplierService.list(request)); - } @ApiOperation("证书报告记录导出") @PostMapping("/listExport") @@ -113,18 +88,6 @@ return certificateReportService.submitCertificateReport(request); } - @ApiOperation("证书报告更新(审批通过后还能更新??暂时保留。。)") - @PostMapping("/update") - @ResponseBody - public ReturnDTO supplierUpdate(@RequestBody @Valid MeterTraceSupplier traceSupplier, BindingResult bindingResult) { - Assert.isFalse(Objects.isNull(traceSupplier.getId()), () -> { - throw new BusinessException(BusinessExceptionEnum.ID_NULL); - }); - Assert.isFalse(bindingResult.hasErrors(), () -> { - throw new BusinessException(CoreExceptionEnum.REQUEST_NULL.getCode(), bindingResult.getFieldError().getDefaultMessage()); - }); - return traceSupplierService.updateTraceSupplier(traceSupplier); - } @ApiOperation("证书报告批量删除") @PostMapping("/batchDelete") diff --git a/casic-metering-api/src/main/java/com/casic/missiles/controller/system/PoiController.java b/casic-metering-api/src/main/java/com/casic/missiles/controller/system/PoiController.java index 021eaa8..9848e68 100644 --- a/casic-metering-api/src/main/java/com/casic/missiles/controller/system/PoiController.java +++ b/casic-metering-api/src/main/java/com/casic/missiles/controller/system/PoiController.java @@ -3,12 +3,14 @@ import cn.afterturn.easypoi.entity.ImageEntity; import com.casic.missiles.utils.PdfUtil; +import com.casic.missiles.utils.StampUtils; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.stereotype.Controller; import org.springframework.util.Assert; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpServletResponse; import java.io.*; @@ -23,7 +25,51 @@ private String filepath="C:\\upload"; @ApiOperation("word转pdf") + @PostMapping(value = "/convertWordToPdf1") + @ResponseBody + public void convertWordToPdf1() throws Exception { + File uploadFile = new File(filepath); + String wordDir = ""; + if (!uploadFile.exists()) { + uploadFile.mkdirs(); + } + if (!filepath.endsWith("/")) { + wordDir = filepath + File.separator + "word"; + } + File tf = new File(wordDir + File.separator + "tem.docx"); + File tf_pic = new File(wordDir + File.separator + "logo.jpg"); + String pic_url = tf_pic.getCanonicalPath(); + Calendar now = Calendar.getInstance(); + Map params = new HashMap<>(); + List> dataList=new ArrayList<>(); + for (int i = 0; i < 5; i++) { + Map param = new HashMap<>(); + param.put("name", "彭于晏"+i); + param.put("sex", "男"+i); + param.put("address", "中国"+i); + ImageEntity image = new ImageEntity(); + image.setHeight(100); + image.setWidth(100); + image.setUrl(pic_url); + image.setData(PdfUtil.getImageBase64(pic_url)); + param.put("image", image); + dataList.add(param); + } + + params.put("dataList",dataList); + params.put("y", now.get(Calendar.YEAR)); + params.put("m", (now.get(Calendar.MONTH) + 1)); + params.put("d", now.get(Calendar.DAY_OF_MONTH)); + + String fileName = "wordExport.docx"; + String word = StampUtils.exportWord(tf.getPath(), wordDir, fileName, params); + System.out.println("****新模板"+word); + + } + + @ApiOperation("word转pdf") @PostMapping(value = "/convertWordToPdf") + @ResponseBody public void convertWordToPdf(HttpServletResponse response) throws Exception { File uploadFile = new File(filepath); String wordDir = ""; @@ -117,4 +163,5 @@ } } } + } diff --git a/casic-metering-common/pom.xml b/casic-metering-common/pom.xml index bb00ab9..e028713 100644 --- a/casic-metering-common/pom.xml +++ b/casic-metering-common/pom.xml @@ -11,6 +11,7 @@ casic-metering-common + @@ -171,6 +172,14 @@ 4.1.2 + + + + e-iceblue + spire.office.free + 5.3.1 + + com.google.zxing diff --git a/casic-metering-common/src/main/java/com/casic/missiles/utils/CustomXWPFDocumentUtil.java b/casic-metering-common/src/main/java/com/casic/missiles/utils/CustomXWPFDocumentUtil.java deleted file mode 100644 index 9e7ed3f..0000000 --- a/casic-metering-common/src/main/java/com/casic/missiles/utils/CustomXWPFDocumentUtil.java +++ /dev/null @@ -1,309 +0,0 @@ -package com.casic.missiles.utils; - -import java.io.*; -import java.util.*; -import java.util.Map.Entry; - -import cn.afterturn.easypoi.entity.ImageEntity; -import org.apache.commons.lang3.StringUtils; -import org.apache.poi.ooxml.POIXMLDocument; -import org.apache.poi.openxml4j.exceptions.InvalidFormatException; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.util.Units; -import org.apache.poi.xwpf.usermodel.*; -import org.apache.xmlbeans.XmlException; -import org.apache.xmlbeans.XmlToken; -import org.openxmlformats.schemas.drawingml.x2006.main.CTGraphicalObject; -import org.openxmlformats.schemas.drawingml.x2006.main.CTNonVisualDrawingProps; -import org.openxmlformats.schemas.drawingml.x2006.main.CTPositiveSize2D; -import org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.CTAnchor; -import org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.CTInline; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTDrawing; - -public class CustomXWPFDocumentUtil extends XWPFDocument { - - public CustomXWPFDocumentUtil(InputStream in) throws IOException { - super(in); - } - - public CustomXWPFDocumentUtil() { - super(); - } - - public CustomXWPFDocumentUtil(OPCPackage pkg) throws IOException { - super(pkg); - } - - /** - * 根据指定的参数值、模板,生成 word 文档 - * - * @param param 需要替换的变量 - * @param template 模板 - */ - public static XWPFDocument generateWord(Map param, String template) { - XWPFDocument doc = null; - try { - OPCPackage pack = POIXMLDocument.openPackage(template); - doc = new CustomXWPFDocumentUtil(pack); - if (param != null && param.size() > 0) { - - //处理段落 - List paragraphList = doc.getParagraphs(); - processParagraphs(paragraphList, param, doc); - - //处理表格 - Iterator it = doc.getTablesIterator(); - while (it.hasNext()) { - XWPFTable table = it.next(); - List rows = table.getRows(); - for (XWPFTableRow row : rows) { - List cells = row.getTableCells(); - for (XWPFTableCell cell : cells) { - List paragraphListTable = cell.getParagraphs(); - processParagraphs(paragraphListTable, param, doc); - } - } - } - } - } catch (IOException e) { - e.printStackTrace(); - } catch (Exception e) { - e.printStackTrace(); - } - return doc; - } - - /** - * 处理段落 - * - * @param paragraphList - * @param - * @throws FileNotFoundException - * @throws InvalidFormatException - */ - public static void processParagraphs(List paragraphList, Map param, XWPFDocument doc) throws InvalidFormatException, FileNotFoundException { - if (paragraphList != null && paragraphList.size() > 0) { - for (XWPFParagraph paragraph : paragraphList) { - List runs = paragraph.getRuns(); - for (XWPFRun run : runs) { - String text = run.getText(0); - //System.out.println("text=="+text); - if (text != null) { - boolean isSetText = false; - for (Entry entry : param.entrySet()) { - String key = entry.getKey(); - if (text.indexOf(key) != -1) { - isSetText = true; - Object value = entry.getValue(); - if (value instanceof String) {//文本替换 - //System.out.println("key=="+key); - text = text.replace(key, value.toString()); - } else if (value instanceof Map) { //图片替换 - text = text.replace(text, ""); - Map pic = (Map) value; - int width = Integer.parseInt(pic.get("width").toString()); - int height = Integer.parseInt(pic.get("height").toString()); - int picType = getPictureType(pic.get("type").toString()); - String picPath = (String) pic.get("picPath"); - CTInline inline = run.getCTR().addNewDrawing().addNewInline(); - insertPicture(doc, picPath, inline, width, height); - CTDrawing drawing = run.getCTR().getDrawingArray(0); - CTGraphicalObject graphicalobject = drawing.getInlineArray(0).getGraphic(); - //拿到新插入的图片替换添加CTAnchor 设置浮动属性 删除inline属性 - CTAnchor anchor = getAnchorWithGraphic(graphicalobject, "11", - Units.toEMU(width), Units.toEMU(height),//图片大小 - Units.toEMU(0), Units.toEMU(0));//相对当前段落位置的偏移位置,左右偏移:负数向左,正数向右,上下偏移:负数向上,正数向下 - drawing.setAnchorArray(new CTAnchor[]{anchor});//添加浮动属性 - drawing.removeInline(0);//删除行内属性 - } - } - } - if (isSetText) { - run.setText(text, 0); - } - } - } - } - } - } - - /** - * 根据图片类型,取得对应的图片类型代码 - * - * @param picType - * @return int - */ - private static int getPictureType(String picType) { - int res = CustomXWPFDocumentUtil.PICTURE_TYPE_PICT; - if (picType != null) { - if (picType.equalsIgnoreCase("png")) { - res = CustomXWPFDocumentUtil.PICTURE_TYPE_PNG; - } else if (picType.equalsIgnoreCase("dib")) { - res = CustomXWPFDocumentUtil.PICTURE_TYPE_DIB; - } else if (picType.equalsIgnoreCase("emf")) { - res = CustomXWPFDocumentUtil.PICTURE_TYPE_EMF; - } else if (picType.equalsIgnoreCase("jpg") || picType.equalsIgnoreCase("jpeg")) { - res = CustomXWPFDocumentUtil.PICTURE_TYPE_JPEG; - } else if (picType.equalsIgnoreCase("wmf")) { - res = CustomXWPFDocumentUtil.PICTURE_TYPE_WMF; - } - } - return res; - } - - /** - * insert Picture - * - * @param document - * @param filePath - * @param inline - * @param width - * @param height - * @throws InvalidFormatException - * @throws FileNotFoundException - */ - private static void insertPicture(XWPFDocument document, String filePath, - CTInline inline, int width, - int height) throws InvalidFormatException, - FileNotFoundException { - document.addPictureData(new FileInputStream(filePath), XWPFDocument.PICTURE_TYPE_PNG); - int id = document.getAllPictures().size() - 1; - final int EMU = 9525; - width *= EMU; - height *= EMU; - String blipId = - document.getAllPictures().get(id).getRelationId(document); - String picXml = getPicXml(blipId, width, height); - XmlToken xmlToken = null; - try { - xmlToken = XmlToken.Factory.parse(picXml); - } catch (XmlException xe) { - xe.printStackTrace(); - } - inline.set(xmlToken); - inline.setDistT(0); - inline.setDistB(0); - inline.setDistL(0); - inline.setDistR(0); - CTPositiveSize2D extent = inline.addNewExtent(); - extent.setCx(width); - extent.setCy(height); - CTNonVisualDrawingProps docPr = inline.addNewDocPr(); - docPr.setId(id); - docPr.setName("IMG_" + id); - docPr.setDescr("IMG_" + id); - } - - /** - * get the xml of the picture - * - * @param blipId - * @param width - * @param height - * @return - */ - private static String getPicXml(String blipId, int width, int height) { - String picXml = - "" + "" + - " " + - " " + - " " + " " + " " + - " " + " " + - " " + - " " + " " + - " " + " " + - " " + " " + - " " + - " " + " " + - " " + - " " + " " + - " " + " " + - " " + ""; - return picXml; - } - - /** - * @param ctGraphicalObject 图片数据 - * @param deskFileName 图片描述 - * @param width 宽 - * @param height 高 - * @param leftOffset 水平偏移:负数向左,正数向右 - * @param topOffset 垂直偏移:负数向上,正数向下 - * @return CTAnchor - * @throws Exception - */ - public static CTAnchor getAnchorWithGraphic(CTGraphicalObject ctGraphicalObject, - String deskFileName, int width, int height, - int leftOffset, int topOffset) { - //浮在文字上的设置主要是anchor标签下的behindDoc属性设为0,同时添加一个的空标签。 - if (StringUtils.isBlank(deskFileName)) { - deskFileName = new Random().nextInt(999) + "";//描述不能为空,赋值一个随机数 - } - String anchorXML = - "" - + "" - + "" - + "" + leftOffset + "" - + "" - + "" - + "" + topOffset + "" + - "" - + "" - + "" - + "" - + "" - + ""; - CTDrawing drawing = null; - try { - drawing = CTDrawing.Factory.parse(anchorXML); - } catch (XmlException e) { - e.printStackTrace(); - } - CTAnchor anchor = drawing.getAnchorArray(0); - anchor.setGraphic(ctGraphicalObject); - return anchor; - } - public static void main(String[] args) throws IOException{ - Map params = new HashMap<>(); - List> dataList=new ArrayList<>(); - for (int i = 0; i < 5; i++) { - Map param = new HashMap<>(); - param.put("name", "彭于晏"+i); - param.put("sex", "男"+i); - param.put("address", "中国"+i); - ImageEntity image = new ImageEntity(); - image.setHeight(100); - image.setWidth(100); - image.setUrl("C:\\upload\\word\\"); - image.setData(PdfUtil.getImageBase64("C:\\upload\\word\\logo.jpg")); - param.put("image", image); - dataList.add(param); - } - Calendar now = Calendar.getInstance(); - params.put("dataList",dataList); - params.put("y", now.get(Calendar.YEAR)+""); - params.put("m", (now.get(Calendar.MONTH) + 1)+""); - params.put("d", now.get(Calendar.DAY_OF_MONTH)+""); - String template="C:\\upload\\word\\tem.docx"; - ByteArrayOutputStream baos = null; - try { - XWPFDocument document = generateWord(params, template); - baos = new ByteArrayOutputStream(); - document.write(baos);//临时存储流到内存 - baos.flush(); - } catch (Exception e) { - e.printStackTrace(); - }finally{ - if(baos != null){ - baos.close(); - } - } - - - } - -} diff --git a/casic-metering-common/src/main/java/com/casic/missiles/utils/PdfUtil.java b/casic-metering-common/src/main/java/com/casic/missiles/utils/PdfUtil.java index 3d80a8e..3e4f58b 100644 --- a/casic-metering-common/src/main/java/com/casic/missiles/utils/PdfUtil.java +++ b/casic-metering-common/src/main/java/com/casic/missiles/utils/PdfUtil.java @@ -23,12 +23,12 @@ public class PdfUtil { /** - * 生成word 只支持docx + * 按照模板 填充数据生成word 只支持docx * * @param templatePath 模板文件路径 - * @param temDir 生成文件的目录 - * @param fileName 生成文件名 - * @param params 参数 + * @param temDir 生成文件的目录 + * @param fileName 生成文件名 + * @param params 参数 */ public static String exportWord(String templatePath, String temDir, String fileName, Map params) { Assert.notNull(templatePath, "模板路径不能为空"); @@ -39,8 +39,9 @@ temDir = temDir + File.separator; } File dir = new File(temDir); - if (!dir.exists()) { - dir.mkdirs(); + if (!dir.getParentFile().exists()) { + // 新建文件夹 + dir.getParentFile().mkdirs(); } String tmpPath = ""; try { @@ -51,13 +52,13 @@ fos.flush(); fos.close(); } catch (Exception e) { - //e.printStackTrace(); + e.printStackTrace(); } return tmpPath; } - public static String convertDocx2Pdf(String wordPath,String pdfPath) { + public static String convertDocx2Pdf(String wordPath, String pdfPath) { OutputStream os = null; InputStream is = null; try { diff --git a/casic-metering-common/src/main/java/com/casic/missiles/utils/PictureUtil.java b/casic-metering-common/src/main/java/com/casic/missiles/utils/PictureUtil.java deleted file mode 100644 index 4baa893..0000000 --- a/casic-metering-common/src/main/java/com/casic/missiles/utils/PictureUtil.java +++ /dev/null @@ -1,184 +0,0 @@ -//package com.casic.missiles.utils; -// -//import cn.hutool.core.codec.Base64; -//import com.alibaba.fastjson.JSONObject; -//import com.google.common.collect.Lists; -//import org.apache.poi.xwpf.usermodel.*; -//import org.apache.xmlbeans.XmlException; -//import org.openxmlformats.schemas.drawingml.x2006.main.CTGraphicalObject; -//import org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.CTAnchor; -//import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTDrawing; -// -//import java.io.*; -//import java.util.List; -//import java.util.Map; -//import java.util.Set; -// -//public class PictureUtil { -// public void create(String filePath, JSONObject jsonObject) { -// try { -// FileInputStream template = new FileInputStream(new File(filePath)); -// //获取docx解析对象 -// XWPFDocument document = new XWPFDocument(template); -// List tableList = Lists.newArrayList(); -// -// //解析替换表格对象 -// List tables = document.getTables(); -// for (int i = 0; i < tables.size(); i++) { -// //只处理行数大于等于2的表格,且不循环表头 -// XWPFTable table = tables.get(i); -// if (table.getRows().size() > 1) { -// //判断表格是需要替换还是需要插入,判断逻辑有$为替换,表格无$为插入 -// if (WordUtil.checkText(table.getText())) { -// List rows = table.getRows(); -// //遍历表格,并替换模板 -// eachTable(rows, jsonObject); -// } -// } -// } -// -// // workBook写入输出流 -// ByteArrayOutputStream baos = new ByteArrayOutputStream(); -// document.write(baos); -// baos.flush(); -// } catch (Exception e) { -// e.printStackTrace(); -// } -// } -// /** -// * 遍历表格 -// * -// * @param rows 表格行对象 -// * @param textMap 需要替换的信息集合 -// */ -// public static void eachTable(List rows, JSONObject textMap) { -// for (XWPFTableRow row : rows) { -// List cells = row.getTableCells(); -// for (XWPFTableCell cell : cells) { -// //判断单元格是否需要替换 -// if (checkText(cell.getText())) { -// List paragraphs = cell.getParagraphs(); -// for (XWPFParagraph paragraph : paragraphs) { -// List runs = paragraph.getRuns(); -// for (XWPFRun run : runs) { -//// run.setText(changeValue(run.toString(), textMap), 0); -// //新增制证照片单独处理 -// if (run.toString().indexOf("${jpeg}") != -1 && textMap.containsKey("jpeg")){ -// addPic(run,textMap, 1188000, 1728000,0, 0); -// break; -// } -// String value = changeValue(run.toString(), textMap); -// setWrap(value, run); -// } -// } -// } -// } -// } -// } -// -// /** -// * 匹配传入信息集合与模板 -// * -// * @param value 模板需要替换的区域 -// * @param textMap 传入信息集合 -// * @return 模板需要替换区域信息集合对应值 -// */ -// public static String changeValue(String value, JSONObject textMap) { -// -// boolean flag = false; -// Set> textSets = textMap.entrySet(); -// for (Map.Entry textSet : textSets) { -// //匹配模板与替换值 格式${key} -// String key = "${" + textSet.getKey() + "}"; -// if (value.indexOf(key) != -1) { -// value = textSet.getValue() == null ? "" : ("" + textSet.getValue()); -// flag = true; -// break; -// } -// } -// //模板未匹配到区域替换为空 -// if (checkText(value)) { -// value = ""; -// } -// return value; -// } -// public static void setWrap(String value, XWPFRun run) { -// if ( value.indexOf("\n") > 0) { -// //设置换行 -// String[] text = value.split("\n"); -// for (int f = 0; f < text.length; f++) { -// if (f == 0) { -// run.setText(text[f].trim(),0); -// } else { -//// run.addCarriageReturn();//硬回车 -// // 换行 -// run.addBreak(); -// run.setText(text[f]); -// } -// } -// } else { -// run.setText((String) value,0); -// } -// } -// -// /** -// * @param ctGraphicalObject 图片数据 -// * @param deskFileName 图片描述 -// * @param width 宽 -// * @param height 高 -// * @param leftOffset 水平偏移 left -// * @param topOffset 垂直偏移 top -// * @param behind 文字上方,文字下方 -// * @return -// * @throws Exception -// */ -// public static CTAnchor getAnchorWithGraphic(CTGraphicalObject ctGraphicalObject, String deskFileName, int width, int height, int leftOffset, int topOffset, boolean behind) { -// String anchorXML ="" -// +"" -// +" " -// +" " -// +" "+ leftOffset + "" -// +" " -// +" " -// +" "+ topOffset +"" -// +" " -// +" " -// +" " -// +" " -// +" " -// +""; -// try { -// CTDrawing drawing = CTDrawing.Factory.parse(anchorXML); -// CTAnchor anchor = drawing.getAnchorArray(0); -// anchor.setGraphic(ctGraphicalObject); -// return anchor; -// } catch (XmlException e) { -// e.printStackTrace(); -// return null; -// } -// } -// -// /** -// * 新增制证照片单独处理 -// * @param run -// * @param textMap -// */ -// public static void addPic(XWPFRun run, JSONObject textMap, int width, int height, int leftOffset, int topOffset){ -// String runText = run.toString().trim(); -// byte[] zjzp = Base64.decode(textMap.getString("jpeg")); -// try(ByteArrayInputStream byteInputStream = new ByteArrayInputStream(zjzp)) { -// //1、添加图片 -// run.addPicture(byteInputStream,XWPFDocument.PICTURE_TYPE_JPEG,"照片", width, height); -// //2、获取图片 -// CTDrawing cTDrawing = run.getCTR().getDrawingArray(0); -// CTGraphicalObject cTGraphicalObject = cTDrawing.getInlineArray(0).getGraphic(); -// //3、设置属性 -// CTAnchor ctAnchor = getAnchorWithGraphic(cTGraphicalObject,"照片", width, height,leftOffset, topOffset,false); -// cTDrawing.setAnchorArray(new CTAnchor[]{ctAnchor}); -// cTDrawing.removeInline(0); -// run.setText(runText.replace("${jpeg}",""), 0); -// }catch (Exception e){ -// e.printStackTrace(); -// } -// } -//} diff --git a/casic-metering-api/src/main/java/com/casic/missiles/controller/business/BusinessCertificateReportController.java b/casic-metering-api/src/main/java/com/casic/missiles/controller/business/BusinessCertificateReportController.java index c440253..408b580 100644 --- a/casic-metering-api/src/main/java/com/casic/missiles/controller/business/BusinessCertificateReportController.java +++ b/casic-metering-api/src/main/java/com/casic/missiles/controller/business/BusinessCertificateReportController.java @@ -9,17 +9,13 @@ import com.casic.missiles.dto.business.certificate.CertificateReportApprovalRequest; import com.casic.missiles.dto.business.certificate.CertificateReportResponse; import com.casic.missiles.dto.flowable.ApprovalDeleteRequest; -import com.casic.missiles.dto.meter.TraceSupplierListRequest; import com.casic.missiles.enums.BusinessExceptionEnum; import com.casic.missiles.exception.BusinessException; import com.casic.missiles.model.business.BusinessCertificateReport; import com.casic.missiles.model.exception.enums.CoreExceptionEnum; -import com.casic.missiles.model.meter.MeterTraceSupplier; import com.casic.missiles.service.business.IBusinessCertificateReportService; -import com.casic.missiles.service.meter.IMeterTraceSupplierService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.util.CollectionUtils; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.*; @@ -45,28 +41,7 @@ public class BusinessCertificateReportController extends ExportController { @Resource private IBusinessCertificateReportService certificateReportService; - @Autowired - private IMeterTraceSupplierService traceSupplierService; - @ApiOperation("证书报告列表(分页)") - @PostMapping("/listPage") - @ResponseBody - public ReturnDTO> supplierListPage(@RequestBody @Valid TraceSupplierListRequest request, BindingResult bindingResult) { - if (bindingResult.hasErrors()) { - throw new BusinessException(CoreExceptionEnum.REQUEST_NULL.getCode(), bindingResult.getFieldError().getDefaultMessage()); - } - Page page = PageFactory.defaultPage(); - return ReturnUtil.success(super.packForBT(traceSupplierService.listPage(page, request))); - } - @ApiOperation("证书报告列表") - @PostMapping("/list") - @ResponseBody - public ReturnDTO> supplierList(@RequestBody @Valid TraceSupplierListRequest request, BindingResult bindingResult) { - if (bindingResult.hasErrors()) { - throw new BusinessException(CoreExceptionEnum.REQUEST_NULL.getCode(), bindingResult.getFieldError().getDefaultMessage()); - } - return ReturnUtil.success(traceSupplierService.list(request)); - } @ApiOperation("证书报告记录导出") @PostMapping("/listExport") @@ -113,18 +88,6 @@ return certificateReportService.submitCertificateReport(request); } - @ApiOperation("证书报告更新(审批通过后还能更新??暂时保留。。)") - @PostMapping("/update") - @ResponseBody - public ReturnDTO supplierUpdate(@RequestBody @Valid MeterTraceSupplier traceSupplier, BindingResult bindingResult) { - Assert.isFalse(Objects.isNull(traceSupplier.getId()), () -> { - throw new BusinessException(BusinessExceptionEnum.ID_NULL); - }); - Assert.isFalse(bindingResult.hasErrors(), () -> { - throw new BusinessException(CoreExceptionEnum.REQUEST_NULL.getCode(), bindingResult.getFieldError().getDefaultMessage()); - }); - return traceSupplierService.updateTraceSupplier(traceSupplier); - } @ApiOperation("证书报告批量删除") @PostMapping("/batchDelete") diff --git a/casic-metering-api/src/main/java/com/casic/missiles/controller/system/PoiController.java b/casic-metering-api/src/main/java/com/casic/missiles/controller/system/PoiController.java index 021eaa8..9848e68 100644 --- a/casic-metering-api/src/main/java/com/casic/missiles/controller/system/PoiController.java +++ b/casic-metering-api/src/main/java/com/casic/missiles/controller/system/PoiController.java @@ -3,12 +3,14 @@ import cn.afterturn.easypoi.entity.ImageEntity; import com.casic.missiles.utils.PdfUtil; +import com.casic.missiles.utils.StampUtils; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.stereotype.Controller; import org.springframework.util.Assert; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpServletResponse; import java.io.*; @@ -23,7 +25,51 @@ private String filepath="C:\\upload"; @ApiOperation("word转pdf") + @PostMapping(value = "/convertWordToPdf1") + @ResponseBody + public void convertWordToPdf1() throws Exception { + File uploadFile = new File(filepath); + String wordDir = ""; + if (!uploadFile.exists()) { + uploadFile.mkdirs(); + } + if (!filepath.endsWith("/")) { + wordDir = filepath + File.separator + "word"; + } + File tf = new File(wordDir + File.separator + "tem.docx"); + File tf_pic = new File(wordDir + File.separator + "logo.jpg"); + String pic_url = tf_pic.getCanonicalPath(); + Calendar now = Calendar.getInstance(); + Map params = new HashMap<>(); + List> dataList=new ArrayList<>(); + for (int i = 0; i < 5; i++) { + Map param = new HashMap<>(); + param.put("name", "彭于晏"+i); + param.put("sex", "男"+i); + param.put("address", "中国"+i); + ImageEntity image = new ImageEntity(); + image.setHeight(100); + image.setWidth(100); + image.setUrl(pic_url); + image.setData(PdfUtil.getImageBase64(pic_url)); + param.put("image", image); + dataList.add(param); + } + + params.put("dataList",dataList); + params.put("y", now.get(Calendar.YEAR)); + params.put("m", (now.get(Calendar.MONTH) + 1)); + params.put("d", now.get(Calendar.DAY_OF_MONTH)); + + String fileName = "wordExport.docx"; + String word = StampUtils.exportWord(tf.getPath(), wordDir, fileName, params); + System.out.println("****新模板"+word); + + } + + @ApiOperation("word转pdf") @PostMapping(value = "/convertWordToPdf") + @ResponseBody public void convertWordToPdf(HttpServletResponse response) throws Exception { File uploadFile = new File(filepath); String wordDir = ""; @@ -117,4 +163,5 @@ } } } + } diff --git a/casic-metering-common/pom.xml b/casic-metering-common/pom.xml index bb00ab9..e028713 100644 --- a/casic-metering-common/pom.xml +++ b/casic-metering-common/pom.xml @@ -11,6 +11,7 @@ casic-metering-common + @@ -171,6 +172,14 @@ 4.1.2 + + + + e-iceblue + spire.office.free + 5.3.1 + + com.google.zxing diff --git a/casic-metering-common/src/main/java/com/casic/missiles/utils/CustomXWPFDocumentUtil.java b/casic-metering-common/src/main/java/com/casic/missiles/utils/CustomXWPFDocumentUtil.java deleted file mode 100644 index 9e7ed3f..0000000 --- a/casic-metering-common/src/main/java/com/casic/missiles/utils/CustomXWPFDocumentUtil.java +++ /dev/null @@ -1,309 +0,0 @@ -package com.casic.missiles.utils; - -import java.io.*; -import java.util.*; -import java.util.Map.Entry; - -import cn.afterturn.easypoi.entity.ImageEntity; -import org.apache.commons.lang3.StringUtils; -import org.apache.poi.ooxml.POIXMLDocument; -import org.apache.poi.openxml4j.exceptions.InvalidFormatException; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.util.Units; -import org.apache.poi.xwpf.usermodel.*; -import org.apache.xmlbeans.XmlException; -import org.apache.xmlbeans.XmlToken; -import org.openxmlformats.schemas.drawingml.x2006.main.CTGraphicalObject; -import org.openxmlformats.schemas.drawingml.x2006.main.CTNonVisualDrawingProps; -import org.openxmlformats.schemas.drawingml.x2006.main.CTPositiveSize2D; -import org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.CTAnchor; -import org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.CTInline; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTDrawing; - -public class CustomXWPFDocumentUtil extends XWPFDocument { - - public CustomXWPFDocumentUtil(InputStream in) throws IOException { - super(in); - } - - public CustomXWPFDocumentUtil() { - super(); - } - - public CustomXWPFDocumentUtil(OPCPackage pkg) throws IOException { - super(pkg); - } - - /** - * 根据指定的参数值、模板,生成 word 文档 - * - * @param param 需要替换的变量 - * @param template 模板 - */ - public static XWPFDocument generateWord(Map param, String template) { - XWPFDocument doc = null; - try { - OPCPackage pack = POIXMLDocument.openPackage(template); - doc = new CustomXWPFDocumentUtil(pack); - if (param != null && param.size() > 0) { - - //处理段落 - List paragraphList = doc.getParagraphs(); - processParagraphs(paragraphList, param, doc); - - //处理表格 - Iterator it = doc.getTablesIterator(); - while (it.hasNext()) { - XWPFTable table = it.next(); - List rows = table.getRows(); - for (XWPFTableRow row : rows) { - List cells = row.getTableCells(); - for (XWPFTableCell cell : cells) { - List paragraphListTable = cell.getParagraphs(); - processParagraphs(paragraphListTable, param, doc); - } - } - } - } - } catch (IOException e) { - e.printStackTrace(); - } catch (Exception e) { - e.printStackTrace(); - } - return doc; - } - - /** - * 处理段落 - * - * @param paragraphList - * @param - * @throws FileNotFoundException - * @throws InvalidFormatException - */ - public static void processParagraphs(List paragraphList, Map param, XWPFDocument doc) throws InvalidFormatException, FileNotFoundException { - if (paragraphList != null && paragraphList.size() > 0) { - for (XWPFParagraph paragraph : paragraphList) { - List runs = paragraph.getRuns(); - for (XWPFRun run : runs) { - String text = run.getText(0); - //System.out.println("text=="+text); - if (text != null) { - boolean isSetText = false; - for (Entry entry : param.entrySet()) { - String key = entry.getKey(); - if (text.indexOf(key) != -1) { - isSetText = true; - Object value = entry.getValue(); - if (value instanceof String) {//文本替换 - //System.out.println("key=="+key); - text = text.replace(key, value.toString()); - } else if (value instanceof Map) { //图片替换 - text = text.replace(text, ""); - Map pic = (Map) value; - int width = Integer.parseInt(pic.get("width").toString()); - int height = Integer.parseInt(pic.get("height").toString()); - int picType = getPictureType(pic.get("type").toString()); - String picPath = (String) pic.get("picPath"); - CTInline inline = run.getCTR().addNewDrawing().addNewInline(); - insertPicture(doc, picPath, inline, width, height); - CTDrawing drawing = run.getCTR().getDrawingArray(0); - CTGraphicalObject graphicalobject = drawing.getInlineArray(0).getGraphic(); - //拿到新插入的图片替换添加CTAnchor 设置浮动属性 删除inline属性 - CTAnchor anchor = getAnchorWithGraphic(graphicalobject, "11", - Units.toEMU(width), Units.toEMU(height),//图片大小 - Units.toEMU(0), Units.toEMU(0));//相对当前段落位置的偏移位置,左右偏移:负数向左,正数向右,上下偏移:负数向上,正数向下 - drawing.setAnchorArray(new CTAnchor[]{anchor});//添加浮动属性 - drawing.removeInline(0);//删除行内属性 - } - } - } - if (isSetText) { - run.setText(text, 0); - } - } - } - } - } - } - - /** - * 根据图片类型,取得对应的图片类型代码 - * - * @param picType - * @return int - */ - private static int getPictureType(String picType) { - int res = CustomXWPFDocumentUtil.PICTURE_TYPE_PICT; - if (picType != null) { - if (picType.equalsIgnoreCase("png")) { - res = CustomXWPFDocumentUtil.PICTURE_TYPE_PNG; - } else if (picType.equalsIgnoreCase("dib")) { - res = CustomXWPFDocumentUtil.PICTURE_TYPE_DIB; - } else if (picType.equalsIgnoreCase("emf")) { - res = CustomXWPFDocumentUtil.PICTURE_TYPE_EMF; - } else if (picType.equalsIgnoreCase("jpg") || picType.equalsIgnoreCase("jpeg")) { - res = CustomXWPFDocumentUtil.PICTURE_TYPE_JPEG; - } else if (picType.equalsIgnoreCase("wmf")) { - res = CustomXWPFDocumentUtil.PICTURE_TYPE_WMF; - } - } - return res; - } - - /** - * insert Picture - * - * @param document - * @param filePath - * @param inline - * @param width - * @param height - * @throws InvalidFormatException - * @throws FileNotFoundException - */ - private static void insertPicture(XWPFDocument document, String filePath, - CTInline inline, int width, - int height) throws InvalidFormatException, - FileNotFoundException { - document.addPictureData(new FileInputStream(filePath), XWPFDocument.PICTURE_TYPE_PNG); - int id = document.getAllPictures().size() - 1; - final int EMU = 9525; - width *= EMU; - height *= EMU; - String blipId = - document.getAllPictures().get(id).getRelationId(document); - String picXml = getPicXml(blipId, width, height); - XmlToken xmlToken = null; - try { - xmlToken = XmlToken.Factory.parse(picXml); - } catch (XmlException xe) { - xe.printStackTrace(); - } - inline.set(xmlToken); - inline.setDistT(0); - inline.setDistB(0); - inline.setDistL(0); - inline.setDistR(0); - CTPositiveSize2D extent = inline.addNewExtent(); - extent.setCx(width); - extent.setCy(height); - CTNonVisualDrawingProps docPr = inline.addNewDocPr(); - docPr.setId(id); - docPr.setName("IMG_" + id); - docPr.setDescr("IMG_" + id); - } - - /** - * get the xml of the picture - * - * @param blipId - * @param width - * @param height - * @return - */ - private static String getPicXml(String blipId, int width, int height) { - String picXml = - "" + "" + - " " + - " " + - " " + " " + " " + - " " + " " + - " " + - " " + " " + - " " + " " + - " " + " " + - " " + - " " + " " + - " " + - " " + " " + - " " + " " + - " " + ""; - return picXml; - } - - /** - * @param ctGraphicalObject 图片数据 - * @param deskFileName 图片描述 - * @param width 宽 - * @param height 高 - * @param leftOffset 水平偏移:负数向左,正数向右 - * @param topOffset 垂直偏移:负数向上,正数向下 - * @return CTAnchor - * @throws Exception - */ - public static CTAnchor getAnchorWithGraphic(CTGraphicalObject ctGraphicalObject, - String deskFileName, int width, int height, - int leftOffset, int topOffset) { - //浮在文字上的设置主要是anchor标签下的behindDoc属性设为0,同时添加一个的空标签。 - if (StringUtils.isBlank(deskFileName)) { - deskFileName = new Random().nextInt(999) + "";//描述不能为空,赋值一个随机数 - } - String anchorXML = - "" - + "" - + "" - + "" + leftOffset + "" - + "" - + "" - + "" + topOffset + "" + - "" - + "" - + "" - + "" - + "" - + ""; - CTDrawing drawing = null; - try { - drawing = CTDrawing.Factory.parse(anchorXML); - } catch (XmlException e) { - e.printStackTrace(); - } - CTAnchor anchor = drawing.getAnchorArray(0); - anchor.setGraphic(ctGraphicalObject); - return anchor; - } - public static void main(String[] args) throws IOException{ - Map params = new HashMap<>(); - List> dataList=new ArrayList<>(); - for (int i = 0; i < 5; i++) { - Map param = new HashMap<>(); - param.put("name", "彭于晏"+i); - param.put("sex", "男"+i); - param.put("address", "中国"+i); - ImageEntity image = new ImageEntity(); - image.setHeight(100); - image.setWidth(100); - image.setUrl("C:\\upload\\word\\"); - image.setData(PdfUtil.getImageBase64("C:\\upload\\word\\logo.jpg")); - param.put("image", image); - dataList.add(param); - } - Calendar now = Calendar.getInstance(); - params.put("dataList",dataList); - params.put("y", now.get(Calendar.YEAR)+""); - params.put("m", (now.get(Calendar.MONTH) + 1)+""); - params.put("d", now.get(Calendar.DAY_OF_MONTH)+""); - String template="C:\\upload\\word\\tem.docx"; - ByteArrayOutputStream baos = null; - try { - XWPFDocument document = generateWord(params, template); - baos = new ByteArrayOutputStream(); - document.write(baos);//临时存储流到内存 - baos.flush(); - } catch (Exception e) { - e.printStackTrace(); - }finally{ - if(baos != null){ - baos.close(); - } - } - - - } - -} diff --git a/casic-metering-common/src/main/java/com/casic/missiles/utils/PdfUtil.java b/casic-metering-common/src/main/java/com/casic/missiles/utils/PdfUtil.java index 3d80a8e..3e4f58b 100644 --- a/casic-metering-common/src/main/java/com/casic/missiles/utils/PdfUtil.java +++ b/casic-metering-common/src/main/java/com/casic/missiles/utils/PdfUtil.java @@ -23,12 +23,12 @@ public class PdfUtil { /** - * 生成word 只支持docx + * 按照模板 填充数据生成word 只支持docx * * @param templatePath 模板文件路径 - * @param temDir 生成文件的目录 - * @param fileName 生成文件名 - * @param params 参数 + * @param temDir 生成文件的目录 + * @param fileName 生成文件名 + * @param params 参数 */ public static String exportWord(String templatePath, String temDir, String fileName, Map params) { Assert.notNull(templatePath, "模板路径不能为空"); @@ -39,8 +39,9 @@ temDir = temDir + File.separator; } File dir = new File(temDir); - if (!dir.exists()) { - dir.mkdirs(); + if (!dir.getParentFile().exists()) { + // 新建文件夹 + dir.getParentFile().mkdirs(); } String tmpPath = ""; try { @@ -51,13 +52,13 @@ fos.flush(); fos.close(); } catch (Exception e) { - //e.printStackTrace(); + e.printStackTrace(); } return tmpPath; } - public static String convertDocx2Pdf(String wordPath,String pdfPath) { + public static String convertDocx2Pdf(String wordPath, String pdfPath) { OutputStream os = null; InputStream is = null; try { diff --git a/casic-metering-common/src/main/java/com/casic/missiles/utils/PictureUtil.java b/casic-metering-common/src/main/java/com/casic/missiles/utils/PictureUtil.java deleted file mode 100644 index 4baa893..0000000 --- a/casic-metering-common/src/main/java/com/casic/missiles/utils/PictureUtil.java +++ /dev/null @@ -1,184 +0,0 @@ -//package com.casic.missiles.utils; -// -//import cn.hutool.core.codec.Base64; -//import com.alibaba.fastjson.JSONObject; -//import com.google.common.collect.Lists; -//import org.apache.poi.xwpf.usermodel.*; -//import org.apache.xmlbeans.XmlException; -//import org.openxmlformats.schemas.drawingml.x2006.main.CTGraphicalObject; -//import org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.CTAnchor; -//import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTDrawing; -// -//import java.io.*; -//import java.util.List; -//import java.util.Map; -//import java.util.Set; -// -//public class PictureUtil { -// public void create(String filePath, JSONObject jsonObject) { -// try { -// FileInputStream template = new FileInputStream(new File(filePath)); -// //获取docx解析对象 -// XWPFDocument document = new XWPFDocument(template); -// List tableList = Lists.newArrayList(); -// -// //解析替换表格对象 -// List tables = document.getTables(); -// for (int i = 0; i < tables.size(); i++) { -// //只处理行数大于等于2的表格,且不循环表头 -// XWPFTable table = tables.get(i); -// if (table.getRows().size() > 1) { -// //判断表格是需要替换还是需要插入,判断逻辑有$为替换,表格无$为插入 -// if (WordUtil.checkText(table.getText())) { -// List rows = table.getRows(); -// //遍历表格,并替换模板 -// eachTable(rows, jsonObject); -// } -// } -// } -// -// // workBook写入输出流 -// ByteArrayOutputStream baos = new ByteArrayOutputStream(); -// document.write(baos); -// baos.flush(); -// } catch (Exception e) { -// e.printStackTrace(); -// } -// } -// /** -// * 遍历表格 -// * -// * @param rows 表格行对象 -// * @param textMap 需要替换的信息集合 -// */ -// public static void eachTable(List rows, JSONObject textMap) { -// for (XWPFTableRow row : rows) { -// List cells = row.getTableCells(); -// for (XWPFTableCell cell : cells) { -// //判断单元格是否需要替换 -// if (checkText(cell.getText())) { -// List paragraphs = cell.getParagraphs(); -// for (XWPFParagraph paragraph : paragraphs) { -// List runs = paragraph.getRuns(); -// for (XWPFRun run : runs) { -//// run.setText(changeValue(run.toString(), textMap), 0); -// //新增制证照片单独处理 -// if (run.toString().indexOf("${jpeg}") != -1 && textMap.containsKey("jpeg")){ -// addPic(run,textMap, 1188000, 1728000,0, 0); -// break; -// } -// String value = changeValue(run.toString(), textMap); -// setWrap(value, run); -// } -// } -// } -// } -// } -// } -// -// /** -// * 匹配传入信息集合与模板 -// * -// * @param value 模板需要替换的区域 -// * @param textMap 传入信息集合 -// * @return 模板需要替换区域信息集合对应值 -// */ -// public static String changeValue(String value, JSONObject textMap) { -// -// boolean flag = false; -// Set> textSets = textMap.entrySet(); -// for (Map.Entry textSet : textSets) { -// //匹配模板与替换值 格式${key} -// String key = "${" + textSet.getKey() + "}"; -// if (value.indexOf(key) != -1) { -// value = textSet.getValue() == null ? "" : ("" + textSet.getValue()); -// flag = true; -// break; -// } -// } -// //模板未匹配到区域替换为空 -// if (checkText(value)) { -// value = ""; -// } -// return value; -// } -// public static void setWrap(String value, XWPFRun run) { -// if ( value.indexOf("\n") > 0) { -// //设置换行 -// String[] text = value.split("\n"); -// for (int f = 0; f < text.length; f++) { -// if (f == 0) { -// run.setText(text[f].trim(),0); -// } else { -//// run.addCarriageReturn();//硬回车 -// // 换行 -// run.addBreak(); -// run.setText(text[f]); -// } -// } -// } else { -// run.setText((String) value,0); -// } -// } -// -// /** -// * @param ctGraphicalObject 图片数据 -// * @param deskFileName 图片描述 -// * @param width 宽 -// * @param height 高 -// * @param leftOffset 水平偏移 left -// * @param topOffset 垂直偏移 top -// * @param behind 文字上方,文字下方 -// * @return -// * @throws Exception -// */ -// public static CTAnchor getAnchorWithGraphic(CTGraphicalObject ctGraphicalObject, String deskFileName, int width, int height, int leftOffset, int topOffset, boolean behind) { -// String anchorXML ="" -// +"" -// +" " -// +" " -// +" "+ leftOffset + "" -// +" " -// +" " -// +" "+ topOffset +"" -// +" " -// +" " -// +" " -// +" " -// +" " -// +""; -// try { -// CTDrawing drawing = CTDrawing.Factory.parse(anchorXML); -// CTAnchor anchor = drawing.getAnchorArray(0); -// anchor.setGraphic(ctGraphicalObject); -// return anchor; -// } catch (XmlException e) { -// e.printStackTrace(); -// return null; -// } -// } -// -// /** -// * 新增制证照片单独处理 -// * @param run -// * @param textMap -// */ -// public static void addPic(XWPFRun run, JSONObject textMap, int width, int height, int leftOffset, int topOffset){ -// String runText = run.toString().trim(); -// byte[] zjzp = Base64.decode(textMap.getString("jpeg")); -// try(ByteArrayInputStream byteInputStream = new ByteArrayInputStream(zjzp)) { -// //1、添加图片 -// run.addPicture(byteInputStream,XWPFDocument.PICTURE_TYPE_JPEG,"照片", width, height); -// //2、获取图片 -// CTDrawing cTDrawing = run.getCTR().getDrawingArray(0); -// CTGraphicalObject cTGraphicalObject = cTDrawing.getInlineArray(0).getGraphic(); -// //3、设置属性 -// CTAnchor ctAnchor = getAnchorWithGraphic(cTGraphicalObject,"照片", width, height,leftOffset, topOffset,false); -// cTDrawing.setAnchorArray(new CTAnchor[]{ctAnchor}); -// cTDrawing.removeInline(0); -// run.setText(runText.replace("${jpeg}",""), 0); -// }catch (Exception e){ -// e.printStackTrace(); -// } -// } -//} diff --git a/casic-metering-common/src/main/java/com/casic/missiles/utils/StampUtils.java b/casic-metering-common/src/main/java/com/casic/missiles/utils/StampUtils.java new file mode 100644 index 0000000..fb6d4cf --- /dev/null +++ b/casic-metering-common/src/main/java/com/casic/missiles/utils/StampUtils.java @@ -0,0 +1,482 @@ +package com.casic.missiles.utils; + + +import cn.afterturn.easypoi.word.WordExportUtil; +import cn.hutool.core.lang.Assert; +import com.baomidou.mybatisplus.core.toolkit.ObjectUtils; +import com.spire.doc.*; +import com.spire.doc.documents.*; +import com.spire.doc.fields.DocPicture; +import com.spire.doc.fields.TextRange; +import org.apache.commons.lang3.StringUtils; +import org.apache.poi.xwpf.usermodel.XWPFDocument; + +import javax.imageio.ImageIO; +import java.awt.*; +import java.awt.image.BufferedImage; +import java.io.*; +import java.util.Map; + +/** + * @Author:zt + * @Create:2023/3/7/9:30 + * @Description:TODO Word文件操作工具类 + * @Version:1.0 + */ + +public class StampUtils { + + //关键字索引 (-1) + private final static Integer keyWordIndex = -1; + // 电子印章水平位置 + private final static float horizontal = 300f; + // 电子印章垂直位置 + private final static float vertical = -55f; + // 电子印章宽度 + private final static float stampWidth = 120; + // 电子印章高度 + private final static float stampHeight = 120; + //照片透明度设置 + private final static int alpha = 150; + + + /** + * 1、自定义位置添加电子印章 + * 2、替换书签名位置文本内容 bookmarkName传参为null,则不进行书签替换操作 + * + * @param wordOldUrl word文件路径 + * @param wordNewUrl 新word文件路径 + * @param stampImgUrl 电子印章图片路径 + * @param horizontal 电子印章水平位置 (当前文件推荐260f) + * @param vertical 电子印章垂直位置 (当前推荐455f) + * @param stampWidth 电子印章宽度(推荐120) + * @param stampHeight 电子印章高度(推荐120) + * @param bookmarkName 书签名,通过名称寻找书签文本所在位置 + * @param newBookmarkText 替换的文本新内容 + */ + public void addStamp(String wordOldUrl, String wordNewUrl, String stampImgUrl, + Float horizontal, Float vertical, Float stampWidth, + Float stampHeight, String bookmarkName, String newBookmarkText) { + // 加载文档 + Document document = new Document(); + document.loadFromFile(wordOldUrl); + +// 获取指定段落 + Section section = document.getSections().get(0); +// 获取段落总数 + int count = section.getParagraphs().getCount(); +// log.info("获取文档内容段落总数{}",count); + Paragraph paragraph = section.getParagraphs().get(0); + + // 判断是否需要替换书签位置文本内容 + if (StringUtils.isNotEmpty(bookmarkName)) { + replaceBookmarkContent(document, bookmarkName, newBookmarkText); + } + +// 添加电子印章 + DocPicture docPicture = paragraph.appendPicture(stampImgUrl); + +// 指定电子章位置 +// 水平位置 + docPicture.setHorizontalPosition(horizontal); +// 垂直位置 + docPicture.setVerticalPosition(vertical); + +// 设置电子章大小 + docPicture.setWidth(stampWidth); + docPicture.setHeight(stampHeight); + +// 设置图片位于文字顶层 + docPicture.setTextWrappingStyle(TextWrappingStyle.In_Front_Of_Text); + + // 保存添加电子章的Word文档 + document.saveToFile(wordNewUrl); + document.dispose(); +// log.info("文档添加电子印章结束,新WORD文档地址:{}",wordNewUrl); + + } + + /** + * 1、根据关键词位置添加电子印章 + * 2、替换书签名位置文本内容 bookmarkName传参为null,则不进行书签替换操作 + * + * @param wordOldUrl word文件路径 + * @param wordNewUrl 新word文件路径 + * @param stampImgUrl 电子印章图片路径 + * @param keyWord 关键字 (自定义) + * @param keyWordIndex 关键字索引 (-1) + * @param horizontal 电子印章水平位置 (260f) + * @param vertical 电子印章垂直位置 (-55f) + * @param stampWidth 电子印章宽度 (推荐120) + * @param stampHeight 电子印章高度(推荐120) + */ + public static void addKeyWordStamp(String wordOldUrl, String wordNewUrl, String stampImgUrl, String stampImgUrl1, + String keyWord, Integer keyWordIndex, Float horizontal, + Float vertical, Float stampWidth, Float stampHeight) { + // 加载文档 + Document document = new Document(); + document.loadFromFile(wordOldUrl); + //获取关键字位置 + TextSelection[] textSelections = document.findAllString(keyWord, false, false); + //加签章照片 + if (ObjectUtils.isNotEmpty(textSelections) && StringUtils.isNotEmpty(stampImgUrl)) { + Paragraph paragraph = textSelections[keyWordIndex > -1 ? 0 : textSelections.length - 1].getAsOneRange().getOwnerParagraph(); + //添加公司印章 + DocPicture docPicture = paragraph.appendPicture(stampImgUrl); + + //设置图片位于文字顶层 + docPicture.setTextWrappingStyle(TextWrappingStyle.In_Front_Of_Text); + + //指定电子章位置 + //水平位置 + docPicture.setHorizontalPosition(horizontal); + //垂直位置 + docPicture.setVerticalPosition(vertical); + //设置电子章大小 + docPicture.setWidth(stampWidth); + docPicture.setHeight(stampHeight); + } + + //加签名照片 + if (ObjectUtils.isNotEmpty(textSelections) && StringUtils.isNotEmpty(stampImgUrl1)) { + Paragraph paragraph = textSelections[keyWordIndex > -1 ? 0 : textSelections.length - 1].getAsOneRange().getOwnerParagraph(); + // 添加电子印章 + DocPicture docPicture = paragraph.appendPicture(stampImgUrl1); + //设置图片位于文字顶层 + docPicture.setTextWrappingStyle(TextWrappingStyle.In_Front_Of_Text); + + //指定电子章位置 + //水平位置 + docPicture.setHorizontalPosition(horizontal); + //垂直位置 + docPicture.setVerticalPosition(vertical); + //设置电子章大小 + docPicture.setWidth(stampWidth); + docPicture.setHeight(stampHeight); + } + + //保存添加电子章的Word文档 + document.saveToFile(wordNewUrl); + document.dispose(); + } + + /** + * 替换书签名位置文本内容 + * + * @param document word文档对象 + * @param bookmarkName 书签名 + * @param newBookmarkText 新文本内容 + */ + public void replaceBookmarkContent(Document document, String bookmarkName, String newBookmarkText) { + //定位到指定书签位置 + BookmarksNavigator bookmarksNavigator = new BookmarksNavigator(document); + bookmarksNavigator.moveToBookmark(bookmarkName); + //用文本内容替换原有书签位置的文本,新替换的内容与原文格式一致 + bookmarksNavigator.replaceBookmarkContent(newBookmarkText, true); + } + + /** + * 替换书签名位置文本内容为图片 + * + * @param document word文档对象 + * @param bookmarkName 书签名 + * @param newImgUrl 图片地址 + */ + public void replaceBookmarkContentToImg(Document document, String bookmarkName, String newImgUrl) { + //定位到指定书签位置 + BookmarksNavigator bookmarksNavigator = new BookmarksNavigator(document); + bookmarksNavigator.moveToBookmark(bookmarkName); + //添加图片,替换原有书签内容 + Paragraph para = new Paragraph(document); + para.appendPicture(newImgUrl); + TextBodyPart bodyPart = new TextBodyPart(document); + bodyPart.getBodyItems().add(para); + bookmarksNavigator.replaceBookmarkContent(bodyPart); + } + + /** + * 替换书签名位置文本内容为表格 + * + * @param document word文档对象 + * @param bookmarkName 书签名 + */ + public void replaceBookmarkContentToTable(Document document, String bookmarkName) { + //声明数组内容 + String[][] data = + { + new String[]{"分类", "等级", "编号"}, + new String[]{"A", "一级", "01A"}, + new String[]{"B", "二级", "02B"}, + new String[]{"C", "三级", "03C"}, + }; + + //创建表格 + Table table = new Table(document, true); + table.resetCells(4, 3); + for (int i = 0; i < data.length; i++) { + TableRow dataRow = table.getRows().get(i); + for (int j = 0; j < data[i].length; j++) { + TextRange range = dataRow.getCells().get(j).addParagraph().appendText(data[i][j]); + range.getOwnerParagraph().getFormat().setHorizontalAlignment(HorizontalAlignment.Center); + range.getCharacterFormat().setFontName("楷体"); + dataRow.getRowFormat().setHorizontalAlignment(RowAlignment.Center); + dataRow.getCells().get(j).getCellFormat().setVerticalAlignment(VerticalAlignment.Middle); + } + } + + //创建TextBodyPart对象 + TextBodyPart bodyPart = new TextBodyPart(document); + bodyPart.getBodyItems().add(table); + + //定位到指定书签位置 + BookmarksNavigator bookmarkNavigator = new BookmarksNavigator(document); + bookmarkNavigator.moveToBookmark(bookmarkName); + + //使用表格替换原书签的内容 + bookmarkNavigator.replaceBookmarkContent(bodyPart); + } + + /** + * 文件转流 + * + * @param wordNewUrl + * @return + */ + public byte[] getBytesByFile(String wordNewUrl) { + try { +// byte[] bytes = Files.readAllBytes(Paths.get(wordNewUrl)); + File file = new File(wordNewUrl); + FileInputStream fis = new FileInputStream(file); + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + byte[] b = new byte[1024]; + int len = -1; + while ((len = fis.read(b)) != -1) { + bos.write(b, 0, len); + } + fis.close(); + bos.close(); + byte[] bytes = bos.toByteArray(); + System.out.println("successful..."); + return bytes; + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + /** + * 流转文件 + * + * @param buf 流字节数组 + * @param filePath 新文件路径 + * @param fileName 新文件名称 + */ + public void byte2File(byte[] buf, String filePath, String fileName) { + BufferedOutputStream bos = null; + FileOutputStream fos = null; + File file = null; + try { + File dir = new File(filePath); + if (!dir.exists() && dir.isDirectory()) { + dir.mkdirs(); + } + file = new File(filePath + File.separator + fileName); + fos = new FileOutputStream(file); + bos = new BufferedOutputStream(fos); + bos.write(buf); + } catch (Exception e) { + e.printStackTrace(); + } finally { + if (bos != null) { + try { + bos.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + if (fos != null) { + try { + fos.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + } + + /** + * word转PDF + * + * @param wordNewUrl word文件路径 + * @param pdfNewUrl 存储新PDF文件路径 + */ + public static void wordToPdf(String wordNewUrl, String pdfNewUrl) { +// 将新Word文档转换为PDF文件 + Document document = new Document(); + document.loadFromFile(wordNewUrl); + document.saveToFile(pdfNewUrl, FileFormat.PDF); + document.dispose(); +// log.info("文档转换结束,新PDF文档地址:{}",pdfNewUrl); + } + + + /** + * 图片透明背景转换 + * + * @param imgsrc + * @param alpha + * @return + */ + public static BufferedImage img_alpha(BufferedImage imgsrc, int alpha) { + try { + //创建一个包含透明度的图片,半透明效果必须要存储为png合适才行,存储为jpg,底色为黑色 + BufferedImage back = new BufferedImage(imgsrc.getWidth(), imgsrc.getHeight(), BufferedImage.TYPE_INT_ARGB); + int width = imgsrc.getWidth(); + int height = imgsrc.getHeight(); + for (int j = 0; j < height; j++) { + for (int i = 0; i < width; i++) { + int rgb = imgsrc.getRGB(i, j); + Color color = new Color(rgb); + Color newcolor = new Color(color.getRed(), color.getGreen(), color.getBlue(), alpha); + back.setRGB(i, j, newcolor.getRGB()); + } + } + return back; + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + //读取图片 + public static BufferedImage file2img(String imgpath) { + try { + BufferedImage bufferedImage = ImageIO.read(new File(imgpath)); + return bufferedImage; + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + //保存图片,extent为格式,"jpg"、"png"等 + public static void img2file(BufferedImage img, String extent, String newfile) { + try { + ImageIO.write(img, extent, new File(newfile)); + } catch (Exception e) { + e.printStackTrace(); + } + } + + + /** + * 按照模板 填充数据生成word 只支持docx + * + * @param templatePath 模板文件路径 + * @param temDir 生成文件的目录 + * @param fileName 生成文件名 + * @param params 参数 + */ + public static String exportWord(String templatePath, String temDir, String fileName, Map params) { + Assert.notNull(templatePath, "模板路径不能为空"); + Assert.notNull(temDir, "临时文件路径不能为空"); + Assert.notNull(fileName, "导出文件名不能为空"); + Assert.isTrue(fileName.endsWith(".docx"), "word导出请使用docx格式"); + if (!temDir.endsWith("/")) { + temDir = temDir + File.separator; + } + File dir = new File(temDir); + if (!dir.getParentFile().exists()) { + // 新建文件夹 + dir.getParentFile().mkdirs(); + } + String tmpPath = ""; + try { + XWPFDocument doc = WordExportUtil.exportWord07(templatePath, params); + tmpPath = temDir + fileName; + FileOutputStream fos = new FileOutputStream(tmpPath); + doc.write(fos); + fos.flush(); + fos.close(); + } catch (Exception e) { + e.printStackTrace(); + } + return tmpPath; + } + + /** + * 按照模板 填充数据生成word 只支持docx + * + * @param templatePath 模板文件路径 + * @param temDir 生成文件的目录 + * @param fileName 生成文件名 + * @param params 填充参数 + */ + public static void generateReport(String templatePath, String temDir, + String fileName, Map params, + String stampImgUrl, String stampImgUrl1, + String wordNewUrl, String keyWord, + Integer keyWordIndex, Float horizontal, + Float vertical, Float stampWidth, + Float stampHeight, String pdfNewUrl) { + //1、按照模板填充数据,并导出word + String wordOldUrl = exportWord(templatePath, temDir, fileName, params); + //2、照片背景透明设置 + //2.1签章背景透明设置 + BufferedImage bi = file2img(stampImgUrl); + BufferedImage bii = img_alpha(bi, alpha); + String newPngPath = stampImgUrl.substring(0, stampImgUrl.length() - 4) + "1.png"; + img2file(bii, "PNG", newPngPath); + //2.2签名背景透明设置 + BufferedImage b = file2img(stampImgUrl1); + BufferedImage b0 = img_alpha(b, alpha); + String newPngPath1 = stampImgUrl.substring(0, stampImgUrl1.length() - 4) + "1.png"; + img2file(b0, "PNG", newPngPath1); + + //3、添加签章和签名 + addKeyWordStamp(wordOldUrl, wordNewUrl, newPngPath, newPngPath1, keyWord, keyWordIndex, + horizontal, vertical, stampWidth, stampHeight); + // 4、将新word转化为pdf文件 + wordToPdf(wordNewUrl, pdfNewUrl); + } + + + public static void main(String[] args) { + + //文件与BufferedImage间的转换 + //读取图片 + BufferedImage bi = file2img("C:\\upload\\word\\sign.png"); + BufferedImage bii = img_alpha(bi, alpha); + //生成透明背景图片 + img2file(bii, "PNG", "C:\\upload\\word\\sign1.png"); + + //文件与BufferedImage间的转换 + //读取图片 + BufferedImage b = file2img("C:\\upload\\word\\name.png"); + BufferedImage b0 = img_alpha(b, alpha); + //生成透明背景图片 + img2file(b0, "PNG", "C:\\upload\\word\\name1.png"); + + // 目标文件地址 + String wordOldUrl = "C:\\upload\\word\\wordExport.docx"; + // 添加电子印章后文件存放地址 + String wordNewUrl = "C:\\upload\\word\\tem2.docx"; + //WORD转PDF存放位置 + String pdfNewUrl = "C:\\upload\\word\\tem2.pdf"; + //电子印章图片地址 + String stampImgUrl = "C:\\upload\\word\\sign1.png"; + //电子签名图片地址 + String stampImgUrl1 = "C:\\upload\\word\\name1.png"; + // word文档内容关键字 + String keyWord = "盖章"; + StampUtils addStampUtils = new StampUtils(); + //获取关键字位置并加盖印章并替换书签名位置文本内容 + addStampUtils.addKeyWordStamp(wordOldUrl, wordNewUrl, + stampImgUrl, stampImgUrl1, + keyWord, keyWordIndex, + horizontal, vertical, + stampWidth, stampHeight); + // 将新word转化为pdf文件 + addStampUtils.wordToPdf(wordNewUrl, pdfNewUrl); + } +} \ No newline at end of file diff --git a/casic-metering-api/src/main/java/com/casic/missiles/controller/business/BusinessCertificateReportController.java b/casic-metering-api/src/main/java/com/casic/missiles/controller/business/BusinessCertificateReportController.java index c440253..408b580 100644 --- a/casic-metering-api/src/main/java/com/casic/missiles/controller/business/BusinessCertificateReportController.java +++ b/casic-metering-api/src/main/java/com/casic/missiles/controller/business/BusinessCertificateReportController.java @@ -9,17 +9,13 @@ import com.casic.missiles.dto.business.certificate.CertificateReportApprovalRequest; import com.casic.missiles.dto.business.certificate.CertificateReportResponse; import com.casic.missiles.dto.flowable.ApprovalDeleteRequest; -import com.casic.missiles.dto.meter.TraceSupplierListRequest; import com.casic.missiles.enums.BusinessExceptionEnum; import com.casic.missiles.exception.BusinessException; import com.casic.missiles.model.business.BusinessCertificateReport; import com.casic.missiles.model.exception.enums.CoreExceptionEnum; -import com.casic.missiles.model.meter.MeterTraceSupplier; import com.casic.missiles.service.business.IBusinessCertificateReportService; -import com.casic.missiles.service.meter.IMeterTraceSupplierService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.util.CollectionUtils; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.*; @@ -45,28 +41,7 @@ public class BusinessCertificateReportController extends ExportController { @Resource private IBusinessCertificateReportService certificateReportService; - @Autowired - private IMeterTraceSupplierService traceSupplierService; - @ApiOperation("证书报告列表(分页)") - @PostMapping("/listPage") - @ResponseBody - public ReturnDTO> supplierListPage(@RequestBody @Valid TraceSupplierListRequest request, BindingResult bindingResult) { - if (bindingResult.hasErrors()) { - throw new BusinessException(CoreExceptionEnum.REQUEST_NULL.getCode(), bindingResult.getFieldError().getDefaultMessage()); - } - Page page = PageFactory.defaultPage(); - return ReturnUtil.success(super.packForBT(traceSupplierService.listPage(page, request))); - } - @ApiOperation("证书报告列表") - @PostMapping("/list") - @ResponseBody - public ReturnDTO> supplierList(@RequestBody @Valid TraceSupplierListRequest request, BindingResult bindingResult) { - if (bindingResult.hasErrors()) { - throw new BusinessException(CoreExceptionEnum.REQUEST_NULL.getCode(), bindingResult.getFieldError().getDefaultMessage()); - } - return ReturnUtil.success(traceSupplierService.list(request)); - } @ApiOperation("证书报告记录导出") @PostMapping("/listExport") @@ -113,18 +88,6 @@ return certificateReportService.submitCertificateReport(request); } - @ApiOperation("证书报告更新(审批通过后还能更新??暂时保留。。)") - @PostMapping("/update") - @ResponseBody - public ReturnDTO supplierUpdate(@RequestBody @Valid MeterTraceSupplier traceSupplier, BindingResult bindingResult) { - Assert.isFalse(Objects.isNull(traceSupplier.getId()), () -> { - throw new BusinessException(BusinessExceptionEnum.ID_NULL); - }); - Assert.isFalse(bindingResult.hasErrors(), () -> { - throw new BusinessException(CoreExceptionEnum.REQUEST_NULL.getCode(), bindingResult.getFieldError().getDefaultMessage()); - }); - return traceSupplierService.updateTraceSupplier(traceSupplier); - } @ApiOperation("证书报告批量删除") @PostMapping("/batchDelete") diff --git a/casic-metering-api/src/main/java/com/casic/missiles/controller/system/PoiController.java b/casic-metering-api/src/main/java/com/casic/missiles/controller/system/PoiController.java index 021eaa8..9848e68 100644 --- a/casic-metering-api/src/main/java/com/casic/missiles/controller/system/PoiController.java +++ b/casic-metering-api/src/main/java/com/casic/missiles/controller/system/PoiController.java @@ -3,12 +3,14 @@ import cn.afterturn.easypoi.entity.ImageEntity; import com.casic.missiles.utils.PdfUtil; +import com.casic.missiles.utils.StampUtils; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.stereotype.Controller; import org.springframework.util.Assert; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpServletResponse; import java.io.*; @@ -23,7 +25,51 @@ private String filepath="C:\\upload"; @ApiOperation("word转pdf") + @PostMapping(value = "/convertWordToPdf1") + @ResponseBody + public void convertWordToPdf1() throws Exception { + File uploadFile = new File(filepath); + String wordDir = ""; + if (!uploadFile.exists()) { + uploadFile.mkdirs(); + } + if (!filepath.endsWith("/")) { + wordDir = filepath + File.separator + "word"; + } + File tf = new File(wordDir + File.separator + "tem.docx"); + File tf_pic = new File(wordDir + File.separator + "logo.jpg"); + String pic_url = tf_pic.getCanonicalPath(); + Calendar now = Calendar.getInstance(); + Map params = new HashMap<>(); + List> dataList=new ArrayList<>(); + for (int i = 0; i < 5; i++) { + Map param = new HashMap<>(); + param.put("name", "彭于晏"+i); + param.put("sex", "男"+i); + param.put("address", "中国"+i); + ImageEntity image = new ImageEntity(); + image.setHeight(100); + image.setWidth(100); + image.setUrl(pic_url); + image.setData(PdfUtil.getImageBase64(pic_url)); + param.put("image", image); + dataList.add(param); + } + + params.put("dataList",dataList); + params.put("y", now.get(Calendar.YEAR)); + params.put("m", (now.get(Calendar.MONTH) + 1)); + params.put("d", now.get(Calendar.DAY_OF_MONTH)); + + String fileName = "wordExport.docx"; + String word = StampUtils.exportWord(tf.getPath(), wordDir, fileName, params); + System.out.println("****新模板"+word); + + } + + @ApiOperation("word转pdf") @PostMapping(value = "/convertWordToPdf") + @ResponseBody public void convertWordToPdf(HttpServletResponse response) throws Exception { File uploadFile = new File(filepath); String wordDir = ""; @@ -117,4 +163,5 @@ } } } + } diff --git a/casic-metering-common/pom.xml b/casic-metering-common/pom.xml index bb00ab9..e028713 100644 --- a/casic-metering-common/pom.xml +++ b/casic-metering-common/pom.xml @@ -11,6 +11,7 @@ casic-metering-common + @@ -171,6 +172,14 @@ 4.1.2 + + + + e-iceblue + spire.office.free + 5.3.1 + + com.google.zxing diff --git a/casic-metering-common/src/main/java/com/casic/missiles/utils/CustomXWPFDocumentUtil.java b/casic-metering-common/src/main/java/com/casic/missiles/utils/CustomXWPFDocumentUtil.java deleted file mode 100644 index 9e7ed3f..0000000 --- a/casic-metering-common/src/main/java/com/casic/missiles/utils/CustomXWPFDocumentUtil.java +++ /dev/null @@ -1,309 +0,0 @@ -package com.casic.missiles.utils; - -import java.io.*; -import java.util.*; -import java.util.Map.Entry; - -import cn.afterturn.easypoi.entity.ImageEntity; -import org.apache.commons.lang3.StringUtils; -import org.apache.poi.ooxml.POIXMLDocument; -import org.apache.poi.openxml4j.exceptions.InvalidFormatException; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.util.Units; -import org.apache.poi.xwpf.usermodel.*; -import org.apache.xmlbeans.XmlException; -import org.apache.xmlbeans.XmlToken; -import org.openxmlformats.schemas.drawingml.x2006.main.CTGraphicalObject; -import org.openxmlformats.schemas.drawingml.x2006.main.CTNonVisualDrawingProps; -import org.openxmlformats.schemas.drawingml.x2006.main.CTPositiveSize2D; -import org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.CTAnchor; -import org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.CTInline; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTDrawing; - -public class CustomXWPFDocumentUtil extends XWPFDocument { - - public CustomXWPFDocumentUtil(InputStream in) throws IOException { - super(in); - } - - public CustomXWPFDocumentUtil() { - super(); - } - - public CustomXWPFDocumentUtil(OPCPackage pkg) throws IOException { - super(pkg); - } - - /** - * 根据指定的参数值、模板,生成 word 文档 - * - * @param param 需要替换的变量 - * @param template 模板 - */ - public static XWPFDocument generateWord(Map param, String template) { - XWPFDocument doc = null; - try { - OPCPackage pack = POIXMLDocument.openPackage(template); - doc = new CustomXWPFDocumentUtil(pack); - if (param != null && param.size() > 0) { - - //处理段落 - List paragraphList = doc.getParagraphs(); - processParagraphs(paragraphList, param, doc); - - //处理表格 - Iterator it = doc.getTablesIterator(); - while (it.hasNext()) { - XWPFTable table = it.next(); - List rows = table.getRows(); - for (XWPFTableRow row : rows) { - List cells = row.getTableCells(); - for (XWPFTableCell cell : cells) { - List paragraphListTable = cell.getParagraphs(); - processParagraphs(paragraphListTable, param, doc); - } - } - } - } - } catch (IOException e) { - e.printStackTrace(); - } catch (Exception e) { - e.printStackTrace(); - } - return doc; - } - - /** - * 处理段落 - * - * @param paragraphList - * @param - * @throws FileNotFoundException - * @throws InvalidFormatException - */ - public static void processParagraphs(List paragraphList, Map param, XWPFDocument doc) throws InvalidFormatException, FileNotFoundException { - if (paragraphList != null && paragraphList.size() > 0) { - for (XWPFParagraph paragraph : paragraphList) { - List runs = paragraph.getRuns(); - for (XWPFRun run : runs) { - String text = run.getText(0); - //System.out.println("text=="+text); - if (text != null) { - boolean isSetText = false; - for (Entry entry : param.entrySet()) { - String key = entry.getKey(); - if (text.indexOf(key) != -1) { - isSetText = true; - Object value = entry.getValue(); - if (value instanceof String) {//文本替换 - //System.out.println("key=="+key); - text = text.replace(key, value.toString()); - } else if (value instanceof Map) { //图片替换 - text = text.replace(text, ""); - Map pic = (Map) value; - int width = Integer.parseInt(pic.get("width").toString()); - int height = Integer.parseInt(pic.get("height").toString()); - int picType = getPictureType(pic.get("type").toString()); - String picPath = (String) pic.get("picPath"); - CTInline inline = run.getCTR().addNewDrawing().addNewInline(); - insertPicture(doc, picPath, inline, width, height); - CTDrawing drawing = run.getCTR().getDrawingArray(0); - CTGraphicalObject graphicalobject = drawing.getInlineArray(0).getGraphic(); - //拿到新插入的图片替换添加CTAnchor 设置浮动属性 删除inline属性 - CTAnchor anchor = getAnchorWithGraphic(graphicalobject, "11", - Units.toEMU(width), Units.toEMU(height),//图片大小 - Units.toEMU(0), Units.toEMU(0));//相对当前段落位置的偏移位置,左右偏移:负数向左,正数向右,上下偏移:负数向上,正数向下 - drawing.setAnchorArray(new CTAnchor[]{anchor});//添加浮动属性 - drawing.removeInline(0);//删除行内属性 - } - } - } - if (isSetText) { - run.setText(text, 0); - } - } - } - } - } - } - - /** - * 根据图片类型,取得对应的图片类型代码 - * - * @param picType - * @return int - */ - private static int getPictureType(String picType) { - int res = CustomXWPFDocumentUtil.PICTURE_TYPE_PICT; - if (picType != null) { - if (picType.equalsIgnoreCase("png")) { - res = CustomXWPFDocumentUtil.PICTURE_TYPE_PNG; - } else if (picType.equalsIgnoreCase("dib")) { - res = CustomXWPFDocumentUtil.PICTURE_TYPE_DIB; - } else if (picType.equalsIgnoreCase("emf")) { - res = CustomXWPFDocumentUtil.PICTURE_TYPE_EMF; - } else if (picType.equalsIgnoreCase("jpg") || picType.equalsIgnoreCase("jpeg")) { - res = CustomXWPFDocumentUtil.PICTURE_TYPE_JPEG; - } else if (picType.equalsIgnoreCase("wmf")) { - res = CustomXWPFDocumentUtil.PICTURE_TYPE_WMF; - } - } - return res; - } - - /** - * insert Picture - * - * @param document - * @param filePath - * @param inline - * @param width - * @param height - * @throws InvalidFormatException - * @throws FileNotFoundException - */ - private static void insertPicture(XWPFDocument document, String filePath, - CTInline inline, int width, - int height) throws InvalidFormatException, - FileNotFoundException { - document.addPictureData(new FileInputStream(filePath), XWPFDocument.PICTURE_TYPE_PNG); - int id = document.getAllPictures().size() - 1; - final int EMU = 9525; - width *= EMU; - height *= EMU; - String blipId = - document.getAllPictures().get(id).getRelationId(document); - String picXml = getPicXml(blipId, width, height); - XmlToken xmlToken = null; - try { - xmlToken = XmlToken.Factory.parse(picXml); - } catch (XmlException xe) { - xe.printStackTrace(); - } - inline.set(xmlToken); - inline.setDistT(0); - inline.setDistB(0); - inline.setDistL(0); - inline.setDistR(0); - CTPositiveSize2D extent = inline.addNewExtent(); - extent.setCx(width); - extent.setCy(height); - CTNonVisualDrawingProps docPr = inline.addNewDocPr(); - docPr.setId(id); - docPr.setName("IMG_" + id); - docPr.setDescr("IMG_" + id); - } - - /** - * get the xml of the picture - * - * @param blipId - * @param width - * @param height - * @return - */ - private static String getPicXml(String blipId, int width, int height) { - String picXml = - "" + "" + - " " + - " " + - " " + " " + " " + - " " + " " + - " " + - " " + " " + - " " + " " + - " " + " " + - " " + - " " + " " + - " " + - " " + " " + - " " + " " + - " " + ""; - return picXml; - } - - /** - * @param ctGraphicalObject 图片数据 - * @param deskFileName 图片描述 - * @param width 宽 - * @param height 高 - * @param leftOffset 水平偏移:负数向左,正数向右 - * @param topOffset 垂直偏移:负数向上,正数向下 - * @return CTAnchor - * @throws Exception - */ - public static CTAnchor getAnchorWithGraphic(CTGraphicalObject ctGraphicalObject, - String deskFileName, int width, int height, - int leftOffset, int topOffset) { - //浮在文字上的设置主要是anchor标签下的behindDoc属性设为0,同时添加一个的空标签。 - if (StringUtils.isBlank(deskFileName)) { - deskFileName = new Random().nextInt(999) + "";//描述不能为空,赋值一个随机数 - } - String anchorXML = - "" - + "" - + "" - + "" + leftOffset + "" - + "" - + "" - + "" + topOffset + "" + - "" - + "" - + "" - + "" - + "" - + ""; - CTDrawing drawing = null; - try { - drawing = CTDrawing.Factory.parse(anchorXML); - } catch (XmlException e) { - e.printStackTrace(); - } - CTAnchor anchor = drawing.getAnchorArray(0); - anchor.setGraphic(ctGraphicalObject); - return anchor; - } - public static void main(String[] args) throws IOException{ - Map params = new HashMap<>(); - List> dataList=new ArrayList<>(); - for (int i = 0; i < 5; i++) { - Map param = new HashMap<>(); - param.put("name", "彭于晏"+i); - param.put("sex", "男"+i); - param.put("address", "中国"+i); - ImageEntity image = new ImageEntity(); - image.setHeight(100); - image.setWidth(100); - image.setUrl("C:\\upload\\word\\"); - image.setData(PdfUtil.getImageBase64("C:\\upload\\word\\logo.jpg")); - param.put("image", image); - dataList.add(param); - } - Calendar now = Calendar.getInstance(); - params.put("dataList",dataList); - params.put("y", now.get(Calendar.YEAR)+""); - params.put("m", (now.get(Calendar.MONTH) + 1)+""); - params.put("d", now.get(Calendar.DAY_OF_MONTH)+""); - String template="C:\\upload\\word\\tem.docx"; - ByteArrayOutputStream baos = null; - try { - XWPFDocument document = generateWord(params, template); - baos = new ByteArrayOutputStream(); - document.write(baos);//临时存储流到内存 - baos.flush(); - } catch (Exception e) { - e.printStackTrace(); - }finally{ - if(baos != null){ - baos.close(); - } - } - - - } - -} diff --git a/casic-metering-common/src/main/java/com/casic/missiles/utils/PdfUtil.java b/casic-metering-common/src/main/java/com/casic/missiles/utils/PdfUtil.java index 3d80a8e..3e4f58b 100644 --- a/casic-metering-common/src/main/java/com/casic/missiles/utils/PdfUtil.java +++ b/casic-metering-common/src/main/java/com/casic/missiles/utils/PdfUtil.java @@ -23,12 +23,12 @@ public class PdfUtil { /** - * 生成word 只支持docx + * 按照模板 填充数据生成word 只支持docx * * @param templatePath 模板文件路径 - * @param temDir 生成文件的目录 - * @param fileName 生成文件名 - * @param params 参数 + * @param temDir 生成文件的目录 + * @param fileName 生成文件名 + * @param params 参数 */ public static String exportWord(String templatePath, String temDir, String fileName, Map params) { Assert.notNull(templatePath, "模板路径不能为空"); @@ -39,8 +39,9 @@ temDir = temDir + File.separator; } File dir = new File(temDir); - if (!dir.exists()) { - dir.mkdirs(); + if (!dir.getParentFile().exists()) { + // 新建文件夹 + dir.getParentFile().mkdirs(); } String tmpPath = ""; try { @@ -51,13 +52,13 @@ fos.flush(); fos.close(); } catch (Exception e) { - //e.printStackTrace(); + e.printStackTrace(); } return tmpPath; } - public static String convertDocx2Pdf(String wordPath,String pdfPath) { + public static String convertDocx2Pdf(String wordPath, String pdfPath) { OutputStream os = null; InputStream is = null; try { diff --git a/casic-metering-common/src/main/java/com/casic/missiles/utils/PictureUtil.java b/casic-metering-common/src/main/java/com/casic/missiles/utils/PictureUtil.java deleted file mode 100644 index 4baa893..0000000 --- a/casic-metering-common/src/main/java/com/casic/missiles/utils/PictureUtil.java +++ /dev/null @@ -1,184 +0,0 @@ -//package com.casic.missiles.utils; -// -//import cn.hutool.core.codec.Base64; -//import com.alibaba.fastjson.JSONObject; -//import com.google.common.collect.Lists; -//import org.apache.poi.xwpf.usermodel.*; -//import org.apache.xmlbeans.XmlException; -//import org.openxmlformats.schemas.drawingml.x2006.main.CTGraphicalObject; -//import org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.CTAnchor; -//import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTDrawing; -// -//import java.io.*; -//import java.util.List; -//import java.util.Map; -//import java.util.Set; -// -//public class PictureUtil { -// public void create(String filePath, JSONObject jsonObject) { -// try { -// FileInputStream template = new FileInputStream(new File(filePath)); -// //获取docx解析对象 -// XWPFDocument document = new XWPFDocument(template); -// List tableList = Lists.newArrayList(); -// -// //解析替换表格对象 -// List tables = document.getTables(); -// for (int i = 0; i < tables.size(); i++) { -// //只处理行数大于等于2的表格,且不循环表头 -// XWPFTable table = tables.get(i); -// if (table.getRows().size() > 1) { -// //判断表格是需要替换还是需要插入,判断逻辑有$为替换,表格无$为插入 -// if (WordUtil.checkText(table.getText())) { -// List rows = table.getRows(); -// //遍历表格,并替换模板 -// eachTable(rows, jsonObject); -// } -// } -// } -// -// // workBook写入输出流 -// ByteArrayOutputStream baos = new ByteArrayOutputStream(); -// document.write(baos); -// baos.flush(); -// } catch (Exception e) { -// e.printStackTrace(); -// } -// } -// /** -// * 遍历表格 -// * -// * @param rows 表格行对象 -// * @param textMap 需要替换的信息集合 -// */ -// public static void eachTable(List rows, JSONObject textMap) { -// for (XWPFTableRow row : rows) { -// List cells = row.getTableCells(); -// for (XWPFTableCell cell : cells) { -// //判断单元格是否需要替换 -// if (checkText(cell.getText())) { -// List paragraphs = cell.getParagraphs(); -// for (XWPFParagraph paragraph : paragraphs) { -// List runs = paragraph.getRuns(); -// for (XWPFRun run : runs) { -//// run.setText(changeValue(run.toString(), textMap), 0); -// //新增制证照片单独处理 -// if (run.toString().indexOf("${jpeg}") != -1 && textMap.containsKey("jpeg")){ -// addPic(run,textMap, 1188000, 1728000,0, 0); -// break; -// } -// String value = changeValue(run.toString(), textMap); -// setWrap(value, run); -// } -// } -// } -// } -// } -// } -// -// /** -// * 匹配传入信息集合与模板 -// * -// * @param value 模板需要替换的区域 -// * @param textMap 传入信息集合 -// * @return 模板需要替换区域信息集合对应值 -// */ -// public static String changeValue(String value, JSONObject textMap) { -// -// boolean flag = false; -// Set> textSets = textMap.entrySet(); -// for (Map.Entry textSet : textSets) { -// //匹配模板与替换值 格式${key} -// String key = "${" + textSet.getKey() + "}"; -// if (value.indexOf(key) != -1) { -// value = textSet.getValue() == null ? "" : ("" + textSet.getValue()); -// flag = true; -// break; -// } -// } -// //模板未匹配到区域替换为空 -// if (checkText(value)) { -// value = ""; -// } -// return value; -// } -// public static void setWrap(String value, XWPFRun run) { -// if ( value.indexOf("\n") > 0) { -// //设置换行 -// String[] text = value.split("\n"); -// for (int f = 0; f < text.length; f++) { -// if (f == 0) { -// run.setText(text[f].trim(),0); -// } else { -//// run.addCarriageReturn();//硬回车 -// // 换行 -// run.addBreak(); -// run.setText(text[f]); -// } -// } -// } else { -// run.setText((String) value,0); -// } -// } -// -// /** -// * @param ctGraphicalObject 图片数据 -// * @param deskFileName 图片描述 -// * @param width 宽 -// * @param height 高 -// * @param leftOffset 水平偏移 left -// * @param topOffset 垂直偏移 top -// * @param behind 文字上方,文字下方 -// * @return -// * @throws Exception -// */ -// public static CTAnchor getAnchorWithGraphic(CTGraphicalObject ctGraphicalObject, String deskFileName, int width, int height, int leftOffset, int topOffset, boolean behind) { -// String anchorXML ="" -// +"" -// +" " -// +" " -// +" "+ leftOffset + "" -// +" " -// +" " -// +" "+ topOffset +"" -// +" " -// +" " -// +" " -// +" " -// +" " -// +""; -// try { -// CTDrawing drawing = CTDrawing.Factory.parse(anchorXML); -// CTAnchor anchor = drawing.getAnchorArray(0); -// anchor.setGraphic(ctGraphicalObject); -// return anchor; -// } catch (XmlException e) { -// e.printStackTrace(); -// return null; -// } -// } -// -// /** -// * 新增制证照片单独处理 -// * @param run -// * @param textMap -// */ -// public static void addPic(XWPFRun run, JSONObject textMap, int width, int height, int leftOffset, int topOffset){ -// String runText = run.toString().trim(); -// byte[] zjzp = Base64.decode(textMap.getString("jpeg")); -// try(ByteArrayInputStream byteInputStream = new ByteArrayInputStream(zjzp)) { -// //1、添加图片 -// run.addPicture(byteInputStream,XWPFDocument.PICTURE_TYPE_JPEG,"照片", width, height); -// //2、获取图片 -// CTDrawing cTDrawing = run.getCTR().getDrawingArray(0); -// CTGraphicalObject cTGraphicalObject = cTDrawing.getInlineArray(0).getGraphic(); -// //3、设置属性 -// CTAnchor ctAnchor = getAnchorWithGraphic(cTGraphicalObject,"照片", width, height,leftOffset, topOffset,false); -// cTDrawing.setAnchorArray(new CTAnchor[]{ctAnchor}); -// cTDrawing.removeInline(0); -// run.setText(runText.replace("${jpeg}",""), 0); -// }catch (Exception e){ -// e.printStackTrace(); -// } -// } -//} diff --git a/casic-metering-common/src/main/java/com/casic/missiles/utils/StampUtils.java b/casic-metering-common/src/main/java/com/casic/missiles/utils/StampUtils.java new file mode 100644 index 0000000..fb6d4cf --- /dev/null +++ b/casic-metering-common/src/main/java/com/casic/missiles/utils/StampUtils.java @@ -0,0 +1,482 @@ +package com.casic.missiles.utils; + + +import cn.afterturn.easypoi.word.WordExportUtil; +import cn.hutool.core.lang.Assert; +import com.baomidou.mybatisplus.core.toolkit.ObjectUtils; +import com.spire.doc.*; +import com.spire.doc.documents.*; +import com.spire.doc.fields.DocPicture; +import com.spire.doc.fields.TextRange; +import org.apache.commons.lang3.StringUtils; +import org.apache.poi.xwpf.usermodel.XWPFDocument; + +import javax.imageio.ImageIO; +import java.awt.*; +import java.awt.image.BufferedImage; +import java.io.*; +import java.util.Map; + +/** + * @Author:zt + * @Create:2023/3/7/9:30 + * @Description:TODO Word文件操作工具类 + * @Version:1.0 + */ + +public class StampUtils { + + //关键字索引 (-1) + private final static Integer keyWordIndex = -1; + // 电子印章水平位置 + private final static float horizontal = 300f; + // 电子印章垂直位置 + private final static float vertical = -55f; + // 电子印章宽度 + private final static float stampWidth = 120; + // 电子印章高度 + private final static float stampHeight = 120; + //照片透明度设置 + private final static int alpha = 150; + + + /** + * 1、自定义位置添加电子印章 + * 2、替换书签名位置文本内容 bookmarkName传参为null,则不进行书签替换操作 + * + * @param wordOldUrl word文件路径 + * @param wordNewUrl 新word文件路径 + * @param stampImgUrl 电子印章图片路径 + * @param horizontal 电子印章水平位置 (当前文件推荐260f) + * @param vertical 电子印章垂直位置 (当前推荐455f) + * @param stampWidth 电子印章宽度(推荐120) + * @param stampHeight 电子印章高度(推荐120) + * @param bookmarkName 书签名,通过名称寻找书签文本所在位置 + * @param newBookmarkText 替换的文本新内容 + */ + public void addStamp(String wordOldUrl, String wordNewUrl, String stampImgUrl, + Float horizontal, Float vertical, Float stampWidth, + Float stampHeight, String bookmarkName, String newBookmarkText) { + // 加载文档 + Document document = new Document(); + document.loadFromFile(wordOldUrl); + +// 获取指定段落 + Section section = document.getSections().get(0); +// 获取段落总数 + int count = section.getParagraphs().getCount(); +// log.info("获取文档内容段落总数{}",count); + Paragraph paragraph = section.getParagraphs().get(0); + + // 判断是否需要替换书签位置文本内容 + if (StringUtils.isNotEmpty(bookmarkName)) { + replaceBookmarkContent(document, bookmarkName, newBookmarkText); + } + +// 添加电子印章 + DocPicture docPicture = paragraph.appendPicture(stampImgUrl); + +// 指定电子章位置 +// 水平位置 + docPicture.setHorizontalPosition(horizontal); +// 垂直位置 + docPicture.setVerticalPosition(vertical); + +// 设置电子章大小 + docPicture.setWidth(stampWidth); + docPicture.setHeight(stampHeight); + +// 设置图片位于文字顶层 + docPicture.setTextWrappingStyle(TextWrappingStyle.In_Front_Of_Text); + + // 保存添加电子章的Word文档 + document.saveToFile(wordNewUrl); + document.dispose(); +// log.info("文档添加电子印章结束,新WORD文档地址:{}",wordNewUrl); + + } + + /** + * 1、根据关键词位置添加电子印章 + * 2、替换书签名位置文本内容 bookmarkName传参为null,则不进行书签替换操作 + * + * @param wordOldUrl word文件路径 + * @param wordNewUrl 新word文件路径 + * @param stampImgUrl 电子印章图片路径 + * @param keyWord 关键字 (自定义) + * @param keyWordIndex 关键字索引 (-1) + * @param horizontal 电子印章水平位置 (260f) + * @param vertical 电子印章垂直位置 (-55f) + * @param stampWidth 电子印章宽度 (推荐120) + * @param stampHeight 电子印章高度(推荐120) + */ + public static void addKeyWordStamp(String wordOldUrl, String wordNewUrl, String stampImgUrl, String stampImgUrl1, + String keyWord, Integer keyWordIndex, Float horizontal, + Float vertical, Float stampWidth, Float stampHeight) { + // 加载文档 + Document document = new Document(); + document.loadFromFile(wordOldUrl); + //获取关键字位置 + TextSelection[] textSelections = document.findAllString(keyWord, false, false); + //加签章照片 + if (ObjectUtils.isNotEmpty(textSelections) && StringUtils.isNotEmpty(stampImgUrl)) { + Paragraph paragraph = textSelections[keyWordIndex > -1 ? 0 : textSelections.length - 1].getAsOneRange().getOwnerParagraph(); + //添加公司印章 + DocPicture docPicture = paragraph.appendPicture(stampImgUrl); + + //设置图片位于文字顶层 + docPicture.setTextWrappingStyle(TextWrappingStyle.In_Front_Of_Text); + + //指定电子章位置 + //水平位置 + docPicture.setHorizontalPosition(horizontal); + //垂直位置 + docPicture.setVerticalPosition(vertical); + //设置电子章大小 + docPicture.setWidth(stampWidth); + docPicture.setHeight(stampHeight); + } + + //加签名照片 + if (ObjectUtils.isNotEmpty(textSelections) && StringUtils.isNotEmpty(stampImgUrl1)) { + Paragraph paragraph = textSelections[keyWordIndex > -1 ? 0 : textSelections.length - 1].getAsOneRange().getOwnerParagraph(); + // 添加电子印章 + DocPicture docPicture = paragraph.appendPicture(stampImgUrl1); + //设置图片位于文字顶层 + docPicture.setTextWrappingStyle(TextWrappingStyle.In_Front_Of_Text); + + //指定电子章位置 + //水平位置 + docPicture.setHorizontalPosition(horizontal); + //垂直位置 + docPicture.setVerticalPosition(vertical); + //设置电子章大小 + docPicture.setWidth(stampWidth); + docPicture.setHeight(stampHeight); + } + + //保存添加电子章的Word文档 + document.saveToFile(wordNewUrl); + document.dispose(); + } + + /** + * 替换书签名位置文本内容 + * + * @param document word文档对象 + * @param bookmarkName 书签名 + * @param newBookmarkText 新文本内容 + */ + public void replaceBookmarkContent(Document document, String bookmarkName, String newBookmarkText) { + //定位到指定书签位置 + BookmarksNavigator bookmarksNavigator = new BookmarksNavigator(document); + bookmarksNavigator.moveToBookmark(bookmarkName); + //用文本内容替换原有书签位置的文本,新替换的内容与原文格式一致 + bookmarksNavigator.replaceBookmarkContent(newBookmarkText, true); + } + + /** + * 替换书签名位置文本内容为图片 + * + * @param document word文档对象 + * @param bookmarkName 书签名 + * @param newImgUrl 图片地址 + */ + public void replaceBookmarkContentToImg(Document document, String bookmarkName, String newImgUrl) { + //定位到指定书签位置 + BookmarksNavigator bookmarksNavigator = new BookmarksNavigator(document); + bookmarksNavigator.moveToBookmark(bookmarkName); + //添加图片,替换原有书签内容 + Paragraph para = new Paragraph(document); + para.appendPicture(newImgUrl); + TextBodyPart bodyPart = new TextBodyPart(document); + bodyPart.getBodyItems().add(para); + bookmarksNavigator.replaceBookmarkContent(bodyPart); + } + + /** + * 替换书签名位置文本内容为表格 + * + * @param document word文档对象 + * @param bookmarkName 书签名 + */ + public void replaceBookmarkContentToTable(Document document, String bookmarkName) { + //声明数组内容 + String[][] data = + { + new String[]{"分类", "等级", "编号"}, + new String[]{"A", "一级", "01A"}, + new String[]{"B", "二级", "02B"}, + new String[]{"C", "三级", "03C"}, + }; + + //创建表格 + Table table = new Table(document, true); + table.resetCells(4, 3); + for (int i = 0; i < data.length; i++) { + TableRow dataRow = table.getRows().get(i); + for (int j = 0; j < data[i].length; j++) { + TextRange range = dataRow.getCells().get(j).addParagraph().appendText(data[i][j]); + range.getOwnerParagraph().getFormat().setHorizontalAlignment(HorizontalAlignment.Center); + range.getCharacterFormat().setFontName("楷体"); + dataRow.getRowFormat().setHorizontalAlignment(RowAlignment.Center); + dataRow.getCells().get(j).getCellFormat().setVerticalAlignment(VerticalAlignment.Middle); + } + } + + //创建TextBodyPart对象 + TextBodyPart bodyPart = new TextBodyPart(document); + bodyPart.getBodyItems().add(table); + + //定位到指定书签位置 + BookmarksNavigator bookmarkNavigator = new BookmarksNavigator(document); + bookmarkNavigator.moveToBookmark(bookmarkName); + + //使用表格替换原书签的内容 + bookmarkNavigator.replaceBookmarkContent(bodyPart); + } + + /** + * 文件转流 + * + * @param wordNewUrl + * @return + */ + public byte[] getBytesByFile(String wordNewUrl) { + try { +// byte[] bytes = Files.readAllBytes(Paths.get(wordNewUrl)); + File file = new File(wordNewUrl); + FileInputStream fis = new FileInputStream(file); + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + byte[] b = new byte[1024]; + int len = -1; + while ((len = fis.read(b)) != -1) { + bos.write(b, 0, len); + } + fis.close(); + bos.close(); + byte[] bytes = bos.toByteArray(); + System.out.println("successful..."); + return bytes; + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + /** + * 流转文件 + * + * @param buf 流字节数组 + * @param filePath 新文件路径 + * @param fileName 新文件名称 + */ + public void byte2File(byte[] buf, String filePath, String fileName) { + BufferedOutputStream bos = null; + FileOutputStream fos = null; + File file = null; + try { + File dir = new File(filePath); + if (!dir.exists() && dir.isDirectory()) { + dir.mkdirs(); + } + file = new File(filePath + File.separator + fileName); + fos = new FileOutputStream(file); + bos = new BufferedOutputStream(fos); + bos.write(buf); + } catch (Exception e) { + e.printStackTrace(); + } finally { + if (bos != null) { + try { + bos.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + if (fos != null) { + try { + fos.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + } + + /** + * word转PDF + * + * @param wordNewUrl word文件路径 + * @param pdfNewUrl 存储新PDF文件路径 + */ + public static void wordToPdf(String wordNewUrl, String pdfNewUrl) { +// 将新Word文档转换为PDF文件 + Document document = new Document(); + document.loadFromFile(wordNewUrl); + document.saveToFile(pdfNewUrl, FileFormat.PDF); + document.dispose(); +// log.info("文档转换结束,新PDF文档地址:{}",pdfNewUrl); + } + + + /** + * 图片透明背景转换 + * + * @param imgsrc + * @param alpha + * @return + */ + public static BufferedImage img_alpha(BufferedImage imgsrc, int alpha) { + try { + //创建一个包含透明度的图片,半透明效果必须要存储为png合适才行,存储为jpg,底色为黑色 + BufferedImage back = new BufferedImage(imgsrc.getWidth(), imgsrc.getHeight(), BufferedImage.TYPE_INT_ARGB); + int width = imgsrc.getWidth(); + int height = imgsrc.getHeight(); + for (int j = 0; j < height; j++) { + for (int i = 0; i < width; i++) { + int rgb = imgsrc.getRGB(i, j); + Color color = new Color(rgb); + Color newcolor = new Color(color.getRed(), color.getGreen(), color.getBlue(), alpha); + back.setRGB(i, j, newcolor.getRGB()); + } + } + return back; + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + //读取图片 + public static BufferedImage file2img(String imgpath) { + try { + BufferedImage bufferedImage = ImageIO.read(new File(imgpath)); + return bufferedImage; + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + //保存图片,extent为格式,"jpg"、"png"等 + public static void img2file(BufferedImage img, String extent, String newfile) { + try { + ImageIO.write(img, extent, new File(newfile)); + } catch (Exception e) { + e.printStackTrace(); + } + } + + + /** + * 按照模板 填充数据生成word 只支持docx + * + * @param templatePath 模板文件路径 + * @param temDir 生成文件的目录 + * @param fileName 生成文件名 + * @param params 参数 + */ + public static String exportWord(String templatePath, String temDir, String fileName, Map params) { + Assert.notNull(templatePath, "模板路径不能为空"); + Assert.notNull(temDir, "临时文件路径不能为空"); + Assert.notNull(fileName, "导出文件名不能为空"); + Assert.isTrue(fileName.endsWith(".docx"), "word导出请使用docx格式"); + if (!temDir.endsWith("/")) { + temDir = temDir + File.separator; + } + File dir = new File(temDir); + if (!dir.getParentFile().exists()) { + // 新建文件夹 + dir.getParentFile().mkdirs(); + } + String tmpPath = ""; + try { + XWPFDocument doc = WordExportUtil.exportWord07(templatePath, params); + tmpPath = temDir + fileName; + FileOutputStream fos = new FileOutputStream(tmpPath); + doc.write(fos); + fos.flush(); + fos.close(); + } catch (Exception e) { + e.printStackTrace(); + } + return tmpPath; + } + + /** + * 按照模板 填充数据生成word 只支持docx + * + * @param templatePath 模板文件路径 + * @param temDir 生成文件的目录 + * @param fileName 生成文件名 + * @param params 填充参数 + */ + public static void generateReport(String templatePath, String temDir, + String fileName, Map params, + String stampImgUrl, String stampImgUrl1, + String wordNewUrl, String keyWord, + Integer keyWordIndex, Float horizontal, + Float vertical, Float stampWidth, + Float stampHeight, String pdfNewUrl) { + //1、按照模板填充数据,并导出word + String wordOldUrl = exportWord(templatePath, temDir, fileName, params); + //2、照片背景透明设置 + //2.1签章背景透明设置 + BufferedImage bi = file2img(stampImgUrl); + BufferedImage bii = img_alpha(bi, alpha); + String newPngPath = stampImgUrl.substring(0, stampImgUrl.length() - 4) + "1.png"; + img2file(bii, "PNG", newPngPath); + //2.2签名背景透明设置 + BufferedImage b = file2img(stampImgUrl1); + BufferedImage b0 = img_alpha(b, alpha); + String newPngPath1 = stampImgUrl.substring(0, stampImgUrl1.length() - 4) + "1.png"; + img2file(b0, "PNG", newPngPath1); + + //3、添加签章和签名 + addKeyWordStamp(wordOldUrl, wordNewUrl, newPngPath, newPngPath1, keyWord, keyWordIndex, + horizontal, vertical, stampWidth, stampHeight); + // 4、将新word转化为pdf文件 + wordToPdf(wordNewUrl, pdfNewUrl); + } + + + public static void main(String[] args) { + + //文件与BufferedImage间的转换 + //读取图片 + BufferedImage bi = file2img("C:\\upload\\word\\sign.png"); + BufferedImage bii = img_alpha(bi, alpha); + //生成透明背景图片 + img2file(bii, "PNG", "C:\\upload\\word\\sign1.png"); + + //文件与BufferedImage间的转换 + //读取图片 + BufferedImage b = file2img("C:\\upload\\word\\name.png"); + BufferedImage b0 = img_alpha(b, alpha); + //生成透明背景图片 + img2file(b0, "PNG", "C:\\upload\\word\\name1.png"); + + // 目标文件地址 + String wordOldUrl = "C:\\upload\\word\\wordExport.docx"; + // 添加电子印章后文件存放地址 + String wordNewUrl = "C:\\upload\\word\\tem2.docx"; + //WORD转PDF存放位置 + String pdfNewUrl = "C:\\upload\\word\\tem2.pdf"; + //电子印章图片地址 + String stampImgUrl = "C:\\upload\\word\\sign1.png"; + //电子签名图片地址 + String stampImgUrl1 = "C:\\upload\\word\\name1.png"; + // word文档内容关键字 + String keyWord = "盖章"; + StampUtils addStampUtils = new StampUtils(); + //获取关键字位置并加盖印章并替换书签名位置文本内容 + addStampUtils.addKeyWordStamp(wordOldUrl, wordNewUrl, + stampImgUrl, stampImgUrl1, + keyWord, keyWordIndex, + horizontal, vertical, + stampWidth, stampHeight); + // 将新word转化为pdf文件 + addStampUtils.wordToPdf(wordNewUrl, pdfNewUrl); + } +} \ No newline at end of file diff --git a/casic-metering-model/src/main/java/com/casic/missiles/dto/business/certificate/CertificateReportResponse.java b/casic-metering-model/src/main/java/com/casic/missiles/dto/business/certificate/CertificateReportResponse.java index b43617c..4581acf 100644 --- a/casic-metering-model/src/main/java/com/casic/missiles/dto/business/certificate/CertificateReportResponse.java +++ b/casic-metering-model/src/main/java/com/casic/missiles/dto/business/certificate/CertificateReportResponse.java @@ -1,6 +1,7 @@ package com.casic.missiles.dto.business.certificate; import com.alibaba.excel.annotation.ExcelIgnoreUnannotated; +import com.alibaba.excel.annotation.ExcelProperty; import com.alibaba.excel.annotation.write.style.ColumnWidth; import com.alibaba.excel.annotation.write.style.ContentRowHeight; import com.alibaba.excel.annotation.write.style.ContentStyle; @@ -28,73 +29,56 @@ private Long id; @ApiModelProperty(value = "证书报告编号", dataType = "String") + @ExcelProperty(value = "证书号", order = 0) private String certificateReportCode; @ApiModelProperty(value = "证书报告名称", dataType = "String") + @ExcelProperty(value = "证书名称", order = 1) private String certificateReportName; @ApiModelProperty(value = "样品编号", dataType = "String") + @ExcelProperty(value = "样品编号", order = 2) private String sampleNo; + @ApiModelProperty(value = "样品名称", dataType = "String") + @ExcelProperty(value = "样品名称", order = 3) private String sampleName; + @ApiModelProperty(value = "型号", dataType = "String") + @ExcelProperty(value = "型号", order = 4) private String sampleModel; + @ApiModelProperty(value = "出厂编号", dataType = "String") + @ExcelProperty(value = "出厂编号", order = 5) private String manufacturingNo; + @ApiModelProperty(value = "委托书编号", dataType = "String") + @ExcelProperty(value = "委托书编号", order = 6) private String orderCode; @ApiModelProperty(value = "检校专业", dataType = "String") @DictCodeField(message = "检校专业不合法", cacheName = MeterDictCode.CALIBRATION_MAJOR) private String calibrationMajor; -// @ApiModelProperty(value = "出具日期", dataType = "String") -// private String issuanceDate; -// -// -// @ApiModelProperty(value = "证书有效期", dataType = "String") -// private String expirationDate; -// -// @ApiModelProperty(value = "检定结果", dataType = "String") -// private String measureResult; -// -// -// @ApiModelProperty(value = "原始记录id", dataType = "Long") -// private Long originalRecordId; -// -// -// @ApiModelProperty(value = "可打印状态", dataType = "String") -// private String printStatus; -// -// -// @ApiModelProperty(value = "打印次数", dataType = "Integer") -// private Integer printNum; - - - @ApiModelProperty(value = "检定人员", dataType = "String") + @ApiModelProperty(value = "检定人员id", dataType = "String") private String measurePersonId; @ApiModelProperty(value = "检定人员名称", dataType = "String") + @ExcelProperty(value = "检定人员", order = 8) private String measurePersonName; @ApiModelProperty(value = "审批状态", dataType = "String") @DictCodeField(message = "审批状态不合法", cacheName = MeterDictCode.APPROVAL_STATUS) private String approvalStatus; -// @ApiModelProperty(value = "备注", dataType = "String") -// private String remark; -// -// private Long createUser; -// @ApiModelProperty(value = "创建时间", dataType = "String") + @ExcelProperty(value = "创建时间", order = 10) private String createTime; -// @ApiModelProperty(value = "检校专业名称", dataType = "String") -// private String calibrationMajorName; - @ApiModelProperty(value = "审批状态名称", dataType = "String") + @ExcelProperty(value = "审批状态", order = 9) private String approvalStatusName; /** @@ -120,6 +104,7 @@ private String measureCategory; @ApiModelProperty(value = "校验类别名称", dataType = "String") + @ExcelProperty(value = "校验类别", order = 7) private String measureCategoryName; diff --git a/casic-metering-api/src/main/java/com/casic/missiles/controller/business/BusinessCertificateReportController.java b/casic-metering-api/src/main/java/com/casic/missiles/controller/business/BusinessCertificateReportController.java index c440253..408b580 100644 --- a/casic-metering-api/src/main/java/com/casic/missiles/controller/business/BusinessCertificateReportController.java +++ b/casic-metering-api/src/main/java/com/casic/missiles/controller/business/BusinessCertificateReportController.java @@ -9,17 +9,13 @@ import com.casic.missiles.dto.business.certificate.CertificateReportApprovalRequest; import com.casic.missiles.dto.business.certificate.CertificateReportResponse; import com.casic.missiles.dto.flowable.ApprovalDeleteRequest; -import com.casic.missiles.dto.meter.TraceSupplierListRequest; import com.casic.missiles.enums.BusinessExceptionEnum; import com.casic.missiles.exception.BusinessException; import com.casic.missiles.model.business.BusinessCertificateReport; import com.casic.missiles.model.exception.enums.CoreExceptionEnum; -import com.casic.missiles.model.meter.MeterTraceSupplier; import com.casic.missiles.service.business.IBusinessCertificateReportService; -import com.casic.missiles.service.meter.IMeterTraceSupplierService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.util.CollectionUtils; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.*; @@ -45,28 +41,7 @@ public class BusinessCertificateReportController extends ExportController { @Resource private IBusinessCertificateReportService certificateReportService; - @Autowired - private IMeterTraceSupplierService traceSupplierService; - @ApiOperation("证书报告列表(分页)") - @PostMapping("/listPage") - @ResponseBody - public ReturnDTO> supplierListPage(@RequestBody @Valid TraceSupplierListRequest request, BindingResult bindingResult) { - if (bindingResult.hasErrors()) { - throw new BusinessException(CoreExceptionEnum.REQUEST_NULL.getCode(), bindingResult.getFieldError().getDefaultMessage()); - } - Page page = PageFactory.defaultPage(); - return ReturnUtil.success(super.packForBT(traceSupplierService.listPage(page, request))); - } - @ApiOperation("证书报告列表") - @PostMapping("/list") - @ResponseBody - public ReturnDTO> supplierList(@RequestBody @Valid TraceSupplierListRequest request, BindingResult bindingResult) { - if (bindingResult.hasErrors()) { - throw new BusinessException(CoreExceptionEnum.REQUEST_NULL.getCode(), bindingResult.getFieldError().getDefaultMessage()); - } - return ReturnUtil.success(traceSupplierService.list(request)); - } @ApiOperation("证书报告记录导出") @PostMapping("/listExport") @@ -113,18 +88,6 @@ return certificateReportService.submitCertificateReport(request); } - @ApiOperation("证书报告更新(审批通过后还能更新??暂时保留。。)") - @PostMapping("/update") - @ResponseBody - public ReturnDTO supplierUpdate(@RequestBody @Valid MeterTraceSupplier traceSupplier, BindingResult bindingResult) { - Assert.isFalse(Objects.isNull(traceSupplier.getId()), () -> { - throw new BusinessException(BusinessExceptionEnum.ID_NULL); - }); - Assert.isFalse(bindingResult.hasErrors(), () -> { - throw new BusinessException(CoreExceptionEnum.REQUEST_NULL.getCode(), bindingResult.getFieldError().getDefaultMessage()); - }); - return traceSupplierService.updateTraceSupplier(traceSupplier); - } @ApiOperation("证书报告批量删除") @PostMapping("/batchDelete") diff --git a/casic-metering-api/src/main/java/com/casic/missiles/controller/system/PoiController.java b/casic-metering-api/src/main/java/com/casic/missiles/controller/system/PoiController.java index 021eaa8..9848e68 100644 --- a/casic-metering-api/src/main/java/com/casic/missiles/controller/system/PoiController.java +++ b/casic-metering-api/src/main/java/com/casic/missiles/controller/system/PoiController.java @@ -3,12 +3,14 @@ import cn.afterturn.easypoi.entity.ImageEntity; import com.casic.missiles.utils.PdfUtil; +import com.casic.missiles.utils.StampUtils; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.stereotype.Controller; import org.springframework.util.Assert; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpServletResponse; import java.io.*; @@ -23,7 +25,51 @@ private String filepath="C:\\upload"; @ApiOperation("word转pdf") + @PostMapping(value = "/convertWordToPdf1") + @ResponseBody + public void convertWordToPdf1() throws Exception { + File uploadFile = new File(filepath); + String wordDir = ""; + if (!uploadFile.exists()) { + uploadFile.mkdirs(); + } + if (!filepath.endsWith("/")) { + wordDir = filepath + File.separator + "word"; + } + File tf = new File(wordDir + File.separator + "tem.docx"); + File tf_pic = new File(wordDir + File.separator + "logo.jpg"); + String pic_url = tf_pic.getCanonicalPath(); + Calendar now = Calendar.getInstance(); + Map params = new HashMap<>(); + List> dataList=new ArrayList<>(); + for (int i = 0; i < 5; i++) { + Map param = new HashMap<>(); + param.put("name", "彭于晏"+i); + param.put("sex", "男"+i); + param.put("address", "中国"+i); + ImageEntity image = new ImageEntity(); + image.setHeight(100); + image.setWidth(100); + image.setUrl(pic_url); + image.setData(PdfUtil.getImageBase64(pic_url)); + param.put("image", image); + dataList.add(param); + } + + params.put("dataList",dataList); + params.put("y", now.get(Calendar.YEAR)); + params.put("m", (now.get(Calendar.MONTH) + 1)); + params.put("d", now.get(Calendar.DAY_OF_MONTH)); + + String fileName = "wordExport.docx"; + String word = StampUtils.exportWord(tf.getPath(), wordDir, fileName, params); + System.out.println("****新模板"+word); + + } + + @ApiOperation("word转pdf") @PostMapping(value = "/convertWordToPdf") + @ResponseBody public void convertWordToPdf(HttpServletResponse response) throws Exception { File uploadFile = new File(filepath); String wordDir = ""; @@ -117,4 +163,5 @@ } } } + } diff --git a/casic-metering-common/pom.xml b/casic-metering-common/pom.xml index bb00ab9..e028713 100644 --- a/casic-metering-common/pom.xml +++ b/casic-metering-common/pom.xml @@ -11,6 +11,7 @@ casic-metering-common + @@ -171,6 +172,14 @@ 4.1.2 + + + + e-iceblue + spire.office.free + 5.3.1 + + com.google.zxing diff --git a/casic-metering-common/src/main/java/com/casic/missiles/utils/CustomXWPFDocumentUtil.java b/casic-metering-common/src/main/java/com/casic/missiles/utils/CustomXWPFDocumentUtil.java deleted file mode 100644 index 9e7ed3f..0000000 --- a/casic-metering-common/src/main/java/com/casic/missiles/utils/CustomXWPFDocumentUtil.java +++ /dev/null @@ -1,309 +0,0 @@ -package com.casic.missiles.utils; - -import java.io.*; -import java.util.*; -import java.util.Map.Entry; - -import cn.afterturn.easypoi.entity.ImageEntity; -import org.apache.commons.lang3.StringUtils; -import org.apache.poi.ooxml.POIXMLDocument; -import org.apache.poi.openxml4j.exceptions.InvalidFormatException; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.util.Units; -import org.apache.poi.xwpf.usermodel.*; -import org.apache.xmlbeans.XmlException; -import org.apache.xmlbeans.XmlToken; -import org.openxmlformats.schemas.drawingml.x2006.main.CTGraphicalObject; -import org.openxmlformats.schemas.drawingml.x2006.main.CTNonVisualDrawingProps; -import org.openxmlformats.schemas.drawingml.x2006.main.CTPositiveSize2D; -import org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.CTAnchor; -import org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.CTInline; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTDrawing; - -public class CustomXWPFDocumentUtil extends XWPFDocument { - - public CustomXWPFDocumentUtil(InputStream in) throws IOException { - super(in); - } - - public CustomXWPFDocumentUtil() { - super(); - } - - public CustomXWPFDocumentUtil(OPCPackage pkg) throws IOException { - super(pkg); - } - - /** - * 根据指定的参数值、模板,生成 word 文档 - * - * @param param 需要替换的变量 - * @param template 模板 - */ - public static XWPFDocument generateWord(Map param, String template) { - XWPFDocument doc = null; - try { - OPCPackage pack = POIXMLDocument.openPackage(template); - doc = new CustomXWPFDocumentUtil(pack); - if (param != null && param.size() > 0) { - - //处理段落 - List paragraphList = doc.getParagraphs(); - processParagraphs(paragraphList, param, doc); - - //处理表格 - Iterator it = doc.getTablesIterator(); - while (it.hasNext()) { - XWPFTable table = it.next(); - List rows = table.getRows(); - for (XWPFTableRow row : rows) { - List cells = row.getTableCells(); - for (XWPFTableCell cell : cells) { - List paragraphListTable = cell.getParagraphs(); - processParagraphs(paragraphListTable, param, doc); - } - } - } - } - } catch (IOException e) { - e.printStackTrace(); - } catch (Exception e) { - e.printStackTrace(); - } - return doc; - } - - /** - * 处理段落 - * - * @param paragraphList - * @param - * @throws FileNotFoundException - * @throws InvalidFormatException - */ - public static void processParagraphs(List paragraphList, Map param, XWPFDocument doc) throws InvalidFormatException, FileNotFoundException { - if (paragraphList != null && paragraphList.size() > 0) { - for (XWPFParagraph paragraph : paragraphList) { - List runs = paragraph.getRuns(); - for (XWPFRun run : runs) { - String text = run.getText(0); - //System.out.println("text=="+text); - if (text != null) { - boolean isSetText = false; - for (Entry entry : param.entrySet()) { - String key = entry.getKey(); - if (text.indexOf(key) != -1) { - isSetText = true; - Object value = entry.getValue(); - if (value instanceof String) {//文本替换 - //System.out.println("key=="+key); - text = text.replace(key, value.toString()); - } else if (value instanceof Map) { //图片替换 - text = text.replace(text, ""); - Map pic = (Map) value; - int width = Integer.parseInt(pic.get("width").toString()); - int height = Integer.parseInt(pic.get("height").toString()); - int picType = getPictureType(pic.get("type").toString()); - String picPath = (String) pic.get("picPath"); - CTInline inline = run.getCTR().addNewDrawing().addNewInline(); - insertPicture(doc, picPath, inline, width, height); - CTDrawing drawing = run.getCTR().getDrawingArray(0); - CTGraphicalObject graphicalobject = drawing.getInlineArray(0).getGraphic(); - //拿到新插入的图片替换添加CTAnchor 设置浮动属性 删除inline属性 - CTAnchor anchor = getAnchorWithGraphic(graphicalobject, "11", - Units.toEMU(width), Units.toEMU(height),//图片大小 - Units.toEMU(0), Units.toEMU(0));//相对当前段落位置的偏移位置,左右偏移:负数向左,正数向右,上下偏移:负数向上,正数向下 - drawing.setAnchorArray(new CTAnchor[]{anchor});//添加浮动属性 - drawing.removeInline(0);//删除行内属性 - } - } - } - if (isSetText) { - run.setText(text, 0); - } - } - } - } - } - } - - /** - * 根据图片类型,取得对应的图片类型代码 - * - * @param picType - * @return int - */ - private static int getPictureType(String picType) { - int res = CustomXWPFDocumentUtil.PICTURE_TYPE_PICT; - if (picType != null) { - if (picType.equalsIgnoreCase("png")) { - res = CustomXWPFDocumentUtil.PICTURE_TYPE_PNG; - } else if (picType.equalsIgnoreCase("dib")) { - res = CustomXWPFDocumentUtil.PICTURE_TYPE_DIB; - } else if (picType.equalsIgnoreCase("emf")) { - res = CustomXWPFDocumentUtil.PICTURE_TYPE_EMF; - } else if (picType.equalsIgnoreCase("jpg") || picType.equalsIgnoreCase("jpeg")) { - res = CustomXWPFDocumentUtil.PICTURE_TYPE_JPEG; - } else if (picType.equalsIgnoreCase("wmf")) { - res = CustomXWPFDocumentUtil.PICTURE_TYPE_WMF; - } - } - return res; - } - - /** - * insert Picture - * - * @param document - * @param filePath - * @param inline - * @param width - * @param height - * @throws InvalidFormatException - * @throws FileNotFoundException - */ - private static void insertPicture(XWPFDocument document, String filePath, - CTInline inline, int width, - int height) throws InvalidFormatException, - FileNotFoundException { - document.addPictureData(new FileInputStream(filePath), XWPFDocument.PICTURE_TYPE_PNG); - int id = document.getAllPictures().size() - 1; - final int EMU = 9525; - width *= EMU; - height *= EMU; - String blipId = - document.getAllPictures().get(id).getRelationId(document); - String picXml = getPicXml(blipId, width, height); - XmlToken xmlToken = null; - try { - xmlToken = XmlToken.Factory.parse(picXml); - } catch (XmlException xe) { - xe.printStackTrace(); - } - inline.set(xmlToken); - inline.setDistT(0); - inline.setDistB(0); - inline.setDistL(0); - inline.setDistR(0); - CTPositiveSize2D extent = inline.addNewExtent(); - extent.setCx(width); - extent.setCy(height); - CTNonVisualDrawingProps docPr = inline.addNewDocPr(); - docPr.setId(id); - docPr.setName("IMG_" + id); - docPr.setDescr("IMG_" + id); - } - - /** - * get the xml of the picture - * - * @param blipId - * @param width - * @param height - * @return - */ - private static String getPicXml(String blipId, int width, int height) { - String picXml = - "" + "" + - " " + - " " + - " " + " " + " " + - " " + " " + - " " + - " " + " " + - " " + " " + - " " + " " + - " " + - " " + " " + - " " + - " " + " " + - " " + " " + - " " + ""; - return picXml; - } - - /** - * @param ctGraphicalObject 图片数据 - * @param deskFileName 图片描述 - * @param width 宽 - * @param height 高 - * @param leftOffset 水平偏移:负数向左,正数向右 - * @param topOffset 垂直偏移:负数向上,正数向下 - * @return CTAnchor - * @throws Exception - */ - public static CTAnchor getAnchorWithGraphic(CTGraphicalObject ctGraphicalObject, - String deskFileName, int width, int height, - int leftOffset, int topOffset) { - //浮在文字上的设置主要是anchor标签下的behindDoc属性设为0,同时添加一个的空标签。 - if (StringUtils.isBlank(deskFileName)) { - deskFileName = new Random().nextInt(999) + "";//描述不能为空,赋值一个随机数 - } - String anchorXML = - "" - + "" - + "" - + "" + leftOffset + "" - + "" - + "" - + "" + topOffset + "" + - "" - + "" - + "" - + "" - + "" - + ""; - CTDrawing drawing = null; - try { - drawing = CTDrawing.Factory.parse(anchorXML); - } catch (XmlException e) { - e.printStackTrace(); - } - CTAnchor anchor = drawing.getAnchorArray(0); - anchor.setGraphic(ctGraphicalObject); - return anchor; - } - public static void main(String[] args) throws IOException{ - Map params = new HashMap<>(); - List> dataList=new ArrayList<>(); - for (int i = 0; i < 5; i++) { - Map param = new HashMap<>(); - param.put("name", "彭于晏"+i); - param.put("sex", "男"+i); - param.put("address", "中国"+i); - ImageEntity image = new ImageEntity(); - image.setHeight(100); - image.setWidth(100); - image.setUrl("C:\\upload\\word\\"); - image.setData(PdfUtil.getImageBase64("C:\\upload\\word\\logo.jpg")); - param.put("image", image); - dataList.add(param); - } - Calendar now = Calendar.getInstance(); - params.put("dataList",dataList); - params.put("y", now.get(Calendar.YEAR)+""); - params.put("m", (now.get(Calendar.MONTH) + 1)+""); - params.put("d", now.get(Calendar.DAY_OF_MONTH)+""); - String template="C:\\upload\\word\\tem.docx"; - ByteArrayOutputStream baos = null; - try { - XWPFDocument document = generateWord(params, template); - baos = new ByteArrayOutputStream(); - document.write(baos);//临时存储流到内存 - baos.flush(); - } catch (Exception e) { - e.printStackTrace(); - }finally{ - if(baos != null){ - baos.close(); - } - } - - - } - -} diff --git a/casic-metering-common/src/main/java/com/casic/missiles/utils/PdfUtil.java b/casic-metering-common/src/main/java/com/casic/missiles/utils/PdfUtil.java index 3d80a8e..3e4f58b 100644 --- a/casic-metering-common/src/main/java/com/casic/missiles/utils/PdfUtil.java +++ b/casic-metering-common/src/main/java/com/casic/missiles/utils/PdfUtil.java @@ -23,12 +23,12 @@ public class PdfUtil { /** - * 生成word 只支持docx + * 按照模板 填充数据生成word 只支持docx * * @param templatePath 模板文件路径 - * @param temDir 生成文件的目录 - * @param fileName 生成文件名 - * @param params 参数 + * @param temDir 生成文件的目录 + * @param fileName 生成文件名 + * @param params 参数 */ public static String exportWord(String templatePath, String temDir, String fileName, Map params) { Assert.notNull(templatePath, "模板路径不能为空"); @@ -39,8 +39,9 @@ temDir = temDir + File.separator; } File dir = new File(temDir); - if (!dir.exists()) { - dir.mkdirs(); + if (!dir.getParentFile().exists()) { + // 新建文件夹 + dir.getParentFile().mkdirs(); } String tmpPath = ""; try { @@ -51,13 +52,13 @@ fos.flush(); fos.close(); } catch (Exception e) { - //e.printStackTrace(); + e.printStackTrace(); } return tmpPath; } - public static String convertDocx2Pdf(String wordPath,String pdfPath) { + public static String convertDocx2Pdf(String wordPath, String pdfPath) { OutputStream os = null; InputStream is = null; try { diff --git a/casic-metering-common/src/main/java/com/casic/missiles/utils/PictureUtil.java b/casic-metering-common/src/main/java/com/casic/missiles/utils/PictureUtil.java deleted file mode 100644 index 4baa893..0000000 --- a/casic-metering-common/src/main/java/com/casic/missiles/utils/PictureUtil.java +++ /dev/null @@ -1,184 +0,0 @@ -//package com.casic.missiles.utils; -// -//import cn.hutool.core.codec.Base64; -//import com.alibaba.fastjson.JSONObject; -//import com.google.common.collect.Lists; -//import org.apache.poi.xwpf.usermodel.*; -//import org.apache.xmlbeans.XmlException; -//import org.openxmlformats.schemas.drawingml.x2006.main.CTGraphicalObject; -//import org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.CTAnchor; -//import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTDrawing; -// -//import java.io.*; -//import java.util.List; -//import java.util.Map; -//import java.util.Set; -// -//public class PictureUtil { -// public void create(String filePath, JSONObject jsonObject) { -// try { -// FileInputStream template = new FileInputStream(new File(filePath)); -// //获取docx解析对象 -// XWPFDocument document = new XWPFDocument(template); -// List tableList = Lists.newArrayList(); -// -// //解析替换表格对象 -// List tables = document.getTables(); -// for (int i = 0; i < tables.size(); i++) { -// //只处理行数大于等于2的表格,且不循环表头 -// XWPFTable table = tables.get(i); -// if (table.getRows().size() > 1) { -// //判断表格是需要替换还是需要插入,判断逻辑有$为替换,表格无$为插入 -// if (WordUtil.checkText(table.getText())) { -// List rows = table.getRows(); -// //遍历表格,并替换模板 -// eachTable(rows, jsonObject); -// } -// } -// } -// -// // workBook写入输出流 -// ByteArrayOutputStream baos = new ByteArrayOutputStream(); -// document.write(baos); -// baos.flush(); -// } catch (Exception e) { -// e.printStackTrace(); -// } -// } -// /** -// * 遍历表格 -// * -// * @param rows 表格行对象 -// * @param textMap 需要替换的信息集合 -// */ -// public static void eachTable(List rows, JSONObject textMap) { -// for (XWPFTableRow row : rows) { -// List cells = row.getTableCells(); -// for (XWPFTableCell cell : cells) { -// //判断单元格是否需要替换 -// if (checkText(cell.getText())) { -// List paragraphs = cell.getParagraphs(); -// for (XWPFParagraph paragraph : paragraphs) { -// List runs = paragraph.getRuns(); -// for (XWPFRun run : runs) { -//// run.setText(changeValue(run.toString(), textMap), 0); -// //新增制证照片单独处理 -// if (run.toString().indexOf("${jpeg}") != -1 && textMap.containsKey("jpeg")){ -// addPic(run,textMap, 1188000, 1728000,0, 0); -// break; -// } -// String value = changeValue(run.toString(), textMap); -// setWrap(value, run); -// } -// } -// } -// } -// } -// } -// -// /** -// * 匹配传入信息集合与模板 -// * -// * @param value 模板需要替换的区域 -// * @param textMap 传入信息集合 -// * @return 模板需要替换区域信息集合对应值 -// */ -// public static String changeValue(String value, JSONObject textMap) { -// -// boolean flag = false; -// Set> textSets = textMap.entrySet(); -// for (Map.Entry textSet : textSets) { -// //匹配模板与替换值 格式${key} -// String key = "${" + textSet.getKey() + "}"; -// if (value.indexOf(key) != -1) { -// value = textSet.getValue() == null ? "" : ("" + textSet.getValue()); -// flag = true; -// break; -// } -// } -// //模板未匹配到区域替换为空 -// if (checkText(value)) { -// value = ""; -// } -// return value; -// } -// public static void setWrap(String value, XWPFRun run) { -// if ( value.indexOf("\n") > 0) { -// //设置换行 -// String[] text = value.split("\n"); -// for (int f = 0; f < text.length; f++) { -// if (f == 0) { -// run.setText(text[f].trim(),0); -// } else { -//// run.addCarriageReturn();//硬回车 -// // 换行 -// run.addBreak(); -// run.setText(text[f]); -// } -// } -// } else { -// run.setText((String) value,0); -// } -// } -// -// /** -// * @param ctGraphicalObject 图片数据 -// * @param deskFileName 图片描述 -// * @param width 宽 -// * @param height 高 -// * @param leftOffset 水平偏移 left -// * @param topOffset 垂直偏移 top -// * @param behind 文字上方,文字下方 -// * @return -// * @throws Exception -// */ -// public static CTAnchor getAnchorWithGraphic(CTGraphicalObject ctGraphicalObject, String deskFileName, int width, int height, int leftOffset, int topOffset, boolean behind) { -// String anchorXML ="" -// +"" -// +" " -// +" " -// +" "+ leftOffset + "" -// +" " -// +" " -// +" "+ topOffset +"" -// +" " -// +" " -// +" " -// +" " -// +" " -// +""; -// try { -// CTDrawing drawing = CTDrawing.Factory.parse(anchorXML); -// CTAnchor anchor = drawing.getAnchorArray(0); -// anchor.setGraphic(ctGraphicalObject); -// return anchor; -// } catch (XmlException e) { -// e.printStackTrace(); -// return null; -// } -// } -// -// /** -// * 新增制证照片单独处理 -// * @param run -// * @param textMap -// */ -// public static void addPic(XWPFRun run, JSONObject textMap, int width, int height, int leftOffset, int topOffset){ -// String runText = run.toString().trim(); -// byte[] zjzp = Base64.decode(textMap.getString("jpeg")); -// try(ByteArrayInputStream byteInputStream = new ByteArrayInputStream(zjzp)) { -// //1、添加图片 -// run.addPicture(byteInputStream,XWPFDocument.PICTURE_TYPE_JPEG,"照片", width, height); -// //2、获取图片 -// CTDrawing cTDrawing = run.getCTR().getDrawingArray(0); -// CTGraphicalObject cTGraphicalObject = cTDrawing.getInlineArray(0).getGraphic(); -// //3、设置属性 -// CTAnchor ctAnchor = getAnchorWithGraphic(cTGraphicalObject,"照片", width, height,leftOffset, topOffset,false); -// cTDrawing.setAnchorArray(new CTAnchor[]{ctAnchor}); -// cTDrawing.removeInline(0); -// run.setText(runText.replace("${jpeg}",""), 0); -// }catch (Exception e){ -// e.printStackTrace(); -// } -// } -//} diff --git a/casic-metering-common/src/main/java/com/casic/missiles/utils/StampUtils.java b/casic-metering-common/src/main/java/com/casic/missiles/utils/StampUtils.java new file mode 100644 index 0000000..fb6d4cf --- /dev/null +++ b/casic-metering-common/src/main/java/com/casic/missiles/utils/StampUtils.java @@ -0,0 +1,482 @@ +package com.casic.missiles.utils; + + +import cn.afterturn.easypoi.word.WordExportUtil; +import cn.hutool.core.lang.Assert; +import com.baomidou.mybatisplus.core.toolkit.ObjectUtils; +import com.spire.doc.*; +import com.spire.doc.documents.*; +import com.spire.doc.fields.DocPicture; +import com.spire.doc.fields.TextRange; +import org.apache.commons.lang3.StringUtils; +import org.apache.poi.xwpf.usermodel.XWPFDocument; + +import javax.imageio.ImageIO; +import java.awt.*; +import java.awt.image.BufferedImage; +import java.io.*; +import java.util.Map; + +/** + * @Author:zt + * @Create:2023/3/7/9:30 + * @Description:TODO Word文件操作工具类 + * @Version:1.0 + */ + +public class StampUtils { + + //关键字索引 (-1) + private final static Integer keyWordIndex = -1; + // 电子印章水平位置 + private final static float horizontal = 300f; + // 电子印章垂直位置 + private final static float vertical = -55f; + // 电子印章宽度 + private final static float stampWidth = 120; + // 电子印章高度 + private final static float stampHeight = 120; + //照片透明度设置 + private final static int alpha = 150; + + + /** + * 1、自定义位置添加电子印章 + * 2、替换书签名位置文本内容 bookmarkName传参为null,则不进行书签替换操作 + * + * @param wordOldUrl word文件路径 + * @param wordNewUrl 新word文件路径 + * @param stampImgUrl 电子印章图片路径 + * @param horizontal 电子印章水平位置 (当前文件推荐260f) + * @param vertical 电子印章垂直位置 (当前推荐455f) + * @param stampWidth 电子印章宽度(推荐120) + * @param stampHeight 电子印章高度(推荐120) + * @param bookmarkName 书签名,通过名称寻找书签文本所在位置 + * @param newBookmarkText 替换的文本新内容 + */ + public void addStamp(String wordOldUrl, String wordNewUrl, String stampImgUrl, + Float horizontal, Float vertical, Float stampWidth, + Float stampHeight, String bookmarkName, String newBookmarkText) { + // 加载文档 + Document document = new Document(); + document.loadFromFile(wordOldUrl); + +// 获取指定段落 + Section section = document.getSections().get(0); +// 获取段落总数 + int count = section.getParagraphs().getCount(); +// log.info("获取文档内容段落总数{}",count); + Paragraph paragraph = section.getParagraphs().get(0); + + // 判断是否需要替换书签位置文本内容 + if (StringUtils.isNotEmpty(bookmarkName)) { + replaceBookmarkContent(document, bookmarkName, newBookmarkText); + } + +// 添加电子印章 + DocPicture docPicture = paragraph.appendPicture(stampImgUrl); + +// 指定电子章位置 +// 水平位置 + docPicture.setHorizontalPosition(horizontal); +// 垂直位置 + docPicture.setVerticalPosition(vertical); + +// 设置电子章大小 + docPicture.setWidth(stampWidth); + docPicture.setHeight(stampHeight); + +// 设置图片位于文字顶层 + docPicture.setTextWrappingStyle(TextWrappingStyle.In_Front_Of_Text); + + // 保存添加电子章的Word文档 + document.saveToFile(wordNewUrl); + document.dispose(); +// log.info("文档添加电子印章结束,新WORD文档地址:{}",wordNewUrl); + + } + + /** + * 1、根据关键词位置添加电子印章 + * 2、替换书签名位置文本内容 bookmarkName传参为null,则不进行书签替换操作 + * + * @param wordOldUrl word文件路径 + * @param wordNewUrl 新word文件路径 + * @param stampImgUrl 电子印章图片路径 + * @param keyWord 关键字 (自定义) + * @param keyWordIndex 关键字索引 (-1) + * @param horizontal 电子印章水平位置 (260f) + * @param vertical 电子印章垂直位置 (-55f) + * @param stampWidth 电子印章宽度 (推荐120) + * @param stampHeight 电子印章高度(推荐120) + */ + public static void addKeyWordStamp(String wordOldUrl, String wordNewUrl, String stampImgUrl, String stampImgUrl1, + String keyWord, Integer keyWordIndex, Float horizontal, + Float vertical, Float stampWidth, Float stampHeight) { + // 加载文档 + Document document = new Document(); + document.loadFromFile(wordOldUrl); + //获取关键字位置 + TextSelection[] textSelections = document.findAllString(keyWord, false, false); + //加签章照片 + if (ObjectUtils.isNotEmpty(textSelections) && StringUtils.isNotEmpty(stampImgUrl)) { + Paragraph paragraph = textSelections[keyWordIndex > -1 ? 0 : textSelections.length - 1].getAsOneRange().getOwnerParagraph(); + //添加公司印章 + DocPicture docPicture = paragraph.appendPicture(stampImgUrl); + + //设置图片位于文字顶层 + docPicture.setTextWrappingStyle(TextWrappingStyle.In_Front_Of_Text); + + //指定电子章位置 + //水平位置 + docPicture.setHorizontalPosition(horizontal); + //垂直位置 + docPicture.setVerticalPosition(vertical); + //设置电子章大小 + docPicture.setWidth(stampWidth); + docPicture.setHeight(stampHeight); + } + + //加签名照片 + if (ObjectUtils.isNotEmpty(textSelections) && StringUtils.isNotEmpty(stampImgUrl1)) { + Paragraph paragraph = textSelections[keyWordIndex > -1 ? 0 : textSelections.length - 1].getAsOneRange().getOwnerParagraph(); + // 添加电子印章 + DocPicture docPicture = paragraph.appendPicture(stampImgUrl1); + //设置图片位于文字顶层 + docPicture.setTextWrappingStyle(TextWrappingStyle.In_Front_Of_Text); + + //指定电子章位置 + //水平位置 + docPicture.setHorizontalPosition(horizontal); + //垂直位置 + docPicture.setVerticalPosition(vertical); + //设置电子章大小 + docPicture.setWidth(stampWidth); + docPicture.setHeight(stampHeight); + } + + //保存添加电子章的Word文档 + document.saveToFile(wordNewUrl); + document.dispose(); + } + + /** + * 替换书签名位置文本内容 + * + * @param document word文档对象 + * @param bookmarkName 书签名 + * @param newBookmarkText 新文本内容 + */ + public void replaceBookmarkContent(Document document, String bookmarkName, String newBookmarkText) { + //定位到指定书签位置 + BookmarksNavigator bookmarksNavigator = new BookmarksNavigator(document); + bookmarksNavigator.moveToBookmark(bookmarkName); + //用文本内容替换原有书签位置的文本,新替换的内容与原文格式一致 + bookmarksNavigator.replaceBookmarkContent(newBookmarkText, true); + } + + /** + * 替换书签名位置文本内容为图片 + * + * @param document word文档对象 + * @param bookmarkName 书签名 + * @param newImgUrl 图片地址 + */ + public void replaceBookmarkContentToImg(Document document, String bookmarkName, String newImgUrl) { + //定位到指定书签位置 + BookmarksNavigator bookmarksNavigator = new BookmarksNavigator(document); + bookmarksNavigator.moveToBookmark(bookmarkName); + //添加图片,替换原有书签内容 + Paragraph para = new Paragraph(document); + para.appendPicture(newImgUrl); + TextBodyPart bodyPart = new TextBodyPart(document); + bodyPart.getBodyItems().add(para); + bookmarksNavigator.replaceBookmarkContent(bodyPart); + } + + /** + * 替换书签名位置文本内容为表格 + * + * @param document word文档对象 + * @param bookmarkName 书签名 + */ + public void replaceBookmarkContentToTable(Document document, String bookmarkName) { + //声明数组内容 + String[][] data = + { + new String[]{"分类", "等级", "编号"}, + new String[]{"A", "一级", "01A"}, + new String[]{"B", "二级", "02B"}, + new String[]{"C", "三级", "03C"}, + }; + + //创建表格 + Table table = new Table(document, true); + table.resetCells(4, 3); + for (int i = 0; i < data.length; i++) { + TableRow dataRow = table.getRows().get(i); + for (int j = 0; j < data[i].length; j++) { + TextRange range = dataRow.getCells().get(j).addParagraph().appendText(data[i][j]); + range.getOwnerParagraph().getFormat().setHorizontalAlignment(HorizontalAlignment.Center); + range.getCharacterFormat().setFontName("楷体"); + dataRow.getRowFormat().setHorizontalAlignment(RowAlignment.Center); + dataRow.getCells().get(j).getCellFormat().setVerticalAlignment(VerticalAlignment.Middle); + } + } + + //创建TextBodyPart对象 + TextBodyPart bodyPart = new TextBodyPart(document); + bodyPart.getBodyItems().add(table); + + //定位到指定书签位置 + BookmarksNavigator bookmarkNavigator = new BookmarksNavigator(document); + bookmarkNavigator.moveToBookmark(bookmarkName); + + //使用表格替换原书签的内容 + bookmarkNavigator.replaceBookmarkContent(bodyPart); + } + + /** + * 文件转流 + * + * @param wordNewUrl + * @return + */ + public byte[] getBytesByFile(String wordNewUrl) { + try { +// byte[] bytes = Files.readAllBytes(Paths.get(wordNewUrl)); + File file = new File(wordNewUrl); + FileInputStream fis = new FileInputStream(file); + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + byte[] b = new byte[1024]; + int len = -1; + while ((len = fis.read(b)) != -1) { + bos.write(b, 0, len); + } + fis.close(); + bos.close(); + byte[] bytes = bos.toByteArray(); + System.out.println("successful..."); + return bytes; + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + /** + * 流转文件 + * + * @param buf 流字节数组 + * @param filePath 新文件路径 + * @param fileName 新文件名称 + */ + public void byte2File(byte[] buf, String filePath, String fileName) { + BufferedOutputStream bos = null; + FileOutputStream fos = null; + File file = null; + try { + File dir = new File(filePath); + if (!dir.exists() && dir.isDirectory()) { + dir.mkdirs(); + } + file = new File(filePath + File.separator + fileName); + fos = new FileOutputStream(file); + bos = new BufferedOutputStream(fos); + bos.write(buf); + } catch (Exception e) { + e.printStackTrace(); + } finally { + if (bos != null) { + try { + bos.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + if (fos != null) { + try { + fos.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + } + + /** + * word转PDF + * + * @param wordNewUrl word文件路径 + * @param pdfNewUrl 存储新PDF文件路径 + */ + public static void wordToPdf(String wordNewUrl, String pdfNewUrl) { +// 将新Word文档转换为PDF文件 + Document document = new Document(); + document.loadFromFile(wordNewUrl); + document.saveToFile(pdfNewUrl, FileFormat.PDF); + document.dispose(); +// log.info("文档转换结束,新PDF文档地址:{}",pdfNewUrl); + } + + + /** + * 图片透明背景转换 + * + * @param imgsrc + * @param alpha + * @return + */ + public static BufferedImage img_alpha(BufferedImage imgsrc, int alpha) { + try { + //创建一个包含透明度的图片,半透明效果必须要存储为png合适才行,存储为jpg,底色为黑色 + BufferedImage back = new BufferedImage(imgsrc.getWidth(), imgsrc.getHeight(), BufferedImage.TYPE_INT_ARGB); + int width = imgsrc.getWidth(); + int height = imgsrc.getHeight(); + for (int j = 0; j < height; j++) { + for (int i = 0; i < width; i++) { + int rgb = imgsrc.getRGB(i, j); + Color color = new Color(rgb); + Color newcolor = new Color(color.getRed(), color.getGreen(), color.getBlue(), alpha); + back.setRGB(i, j, newcolor.getRGB()); + } + } + return back; + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + //读取图片 + public static BufferedImage file2img(String imgpath) { + try { + BufferedImage bufferedImage = ImageIO.read(new File(imgpath)); + return bufferedImage; + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + //保存图片,extent为格式,"jpg"、"png"等 + public static void img2file(BufferedImage img, String extent, String newfile) { + try { + ImageIO.write(img, extent, new File(newfile)); + } catch (Exception e) { + e.printStackTrace(); + } + } + + + /** + * 按照模板 填充数据生成word 只支持docx + * + * @param templatePath 模板文件路径 + * @param temDir 生成文件的目录 + * @param fileName 生成文件名 + * @param params 参数 + */ + public static String exportWord(String templatePath, String temDir, String fileName, Map params) { + Assert.notNull(templatePath, "模板路径不能为空"); + Assert.notNull(temDir, "临时文件路径不能为空"); + Assert.notNull(fileName, "导出文件名不能为空"); + Assert.isTrue(fileName.endsWith(".docx"), "word导出请使用docx格式"); + if (!temDir.endsWith("/")) { + temDir = temDir + File.separator; + } + File dir = new File(temDir); + if (!dir.getParentFile().exists()) { + // 新建文件夹 + dir.getParentFile().mkdirs(); + } + String tmpPath = ""; + try { + XWPFDocument doc = WordExportUtil.exportWord07(templatePath, params); + tmpPath = temDir + fileName; + FileOutputStream fos = new FileOutputStream(tmpPath); + doc.write(fos); + fos.flush(); + fos.close(); + } catch (Exception e) { + e.printStackTrace(); + } + return tmpPath; + } + + /** + * 按照模板 填充数据生成word 只支持docx + * + * @param templatePath 模板文件路径 + * @param temDir 生成文件的目录 + * @param fileName 生成文件名 + * @param params 填充参数 + */ + public static void generateReport(String templatePath, String temDir, + String fileName, Map params, + String stampImgUrl, String stampImgUrl1, + String wordNewUrl, String keyWord, + Integer keyWordIndex, Float horizontal, + Float vertical, Float stampWidth, + Float stampHeight, String pdfNewUrl) { + //1、按照模板填充数据,并导出word + String wordOldUrl = exportWord(templatePath, temDir, fileName, params); + //2、照片背景透明设置 + //2.1签章背景透明设置 + BufferedImage bi = file2img(stampImgUrl); + BufferedImage bii = img_alpha(bi, alpha); + String newPngPath = stampImgUrl.substring(0, stampImgUrl.length() - 4) + "1.png"; + img2file(bii, "PNG", newPngPath); + //2.2签名背景透明设置 + BufferedImage b = file2img(stampImgUrl1); + BufferedImage b0 = img_alpha(b, alpha); + String newPngPath1 = stampImgUrl.substring(0, stampImgUrl1.length() - 4) + "1.png"; + img2file(b0, "PNG", newPngPath1); + + //3、添加签章和签名 + addKeyWordStamp(wordOldUrl, wordNewUrl, newPngPath, newPngPath1, keyWord, keyWordIndex, + horizontal, vertical, stampWidth, stampHeight); + // 4、将新word转化为pdf文件 + wordToPdf(wordNewUrl, pdfNewUrl); + } + + + public static void main(String[] args) { + + //文件与BufferedImage间的转换 + //读取图片 + BufferedImage bi = file2img("C:\\upload\\word\\sign.png"); + BufferedImage bii = img_alpha(bi, alpha); + //生成透明背景图片 + img2file(bii, "PNG", "C:\\upload\\word\\sign1.png"); + + //文件与BufferedImage间的转换 + //读取图片 + BufferedImage b = file2img("C:\\upload\\word\\name.png"); + BufferedImage b0 = img_alpha(b, alpha); + //生成透明背景图片 + img2file(b0, "PNG", "C:\\upload\\word\\name1.png"); + + // 目标文件地址 + String wordOldUrl = "C:\\upload\\word\\wordExport.docx"; + // 添加电子印章后文件存放地址 + String wordNewUrl = "C:\\upload\\word\\tem2.docx"; + //WORD转PDF存放位置 + String pdfNewUrl = "C:\\upload\\word\\tem2.pdf"; + //电子印章图片地址 + String stampImgUrl = "C:\\upload\\word\\sign1.png"; + //电子签名图片地址 + String stampImgUrl1 = "C:\\upload\\word\\name1.png"; + // word文档内容关键字 + String keyWord = "盖章"; + StampUtils addStampUtils = new StampUtils(); + //获取关键字位置并加盖印章并替换书签名位置文本内容 + addStampUtils.addKeyWordStamp(wordOldUrl, wordNewUrl, + stampImgUrl, stampImgUrl1, + keyWord, keyWordIndex, + horizontal, vertical, + stampWidth, stampHeight); + // 将新word转化为pdf文件 + addStampUtils.wordToPdf(wordNewUrl, pdfNewUrl); + } +} \ No newline at end of file diff --git a/casic-metering-model/src/main/java/com/casic/missiles/dto/business/certificate/CertificateReportResponse.java b/casic-metering-model/src/main/java/com/casic/missiles/dto/business/certificate/CertificateReportResponse.java index b43617c..4581acf 100644 --- a/casic-metering-model/src/main/java/com/casic/missiles/dto/business/certificate/CertificateReportResponse.java +++ b/casic-metering-model/src/main/java/com/casic/missiles/dto/business/certificate/CertificateReportResponse.java @@ -1,6 +1,7 @@ package com.casic.missiles.dto.business.certificate; import com.alibaba.excel.annotation.ExcelIgnoreUnannotated; +import com.alibaba.excel.annotation.ExcelProperty; import com.alibaba.excel.annotation.write.style.ColumnWidth; import com.alibaba.excel.annotation.write.style.ContentRowHeight; import com.alibaba.excel.annotation.write.style.ContentStyle; @@ -28,73 +29,56 @@ private Long id; @ApiModelProperty(value = "证书报告编号", dataType = "String") + @ExcelProperty(value = "证书号", order = 0) private String certificateReportCode; @ApiModelProperty(value = "证书报告名称", dataType = "String") + @ExcelProperty(value = "证书名称", order = 1) private String certificateReportName; @ApiModelProperty(value = "样品编号", dataType = "String") + @ExcelProperty(value = "样品编号", order = 2) private String sampleNo; + @ApiModelProperty(value = "样品名称", dataType = "String") + @ExcelProperty(value = "样品名称", order = 3) private String sampleName; + @ApiModelProperty(value = "型号", dataType = "String") + @ExcelProperty(value = "型号", order = 4) private String sampleModel; + @ApiModelProperty(value = "出厂编号", dataType = "String") + @ExcelProperty(value = "出厂编号", order = 5) private String manufacturingNo; + @ApiModelProperty(value = "委托书编号", dataType = "String") + @ExcelProperty(value = "委托书编号", order = 6) private String orderCode; @ApiModelProperty(value = "检校专业", dataType = "String") @DictCodeField(message = "检校专业不合法", cacheName = MeterDictCode.CALIBRATION_MAJOR) private String calibrationMajor; -// @ApiModelProperty(value = "出具日期", dataType = "String") -// private String issuanceDate; -// -// -// @ApiModelProperty(value = "证书有效期", dataType = "String") -// private String expirationDate; -// -// @ApiModelProperty(value = "检定结果", dataType = "String") -// private String measureResult; -// -// -// @ApiModelProperty(value = "原始记录id", dataType = "Long") -// private Long originalRecordId; -// -// -// @ApiModelProperty(value = "可打印状态", dataType = "String") -// private String printStatus; -// -// -// @ApiModelProperty(value = "打印次数", dataType = "Integer") -// private Integer printNum; - - - @ApiModelProperty(value = "检定人员", dataType = "String") + @ApiModelProperty(value = "检定人员id", dataType = "String") private String measurePersonId; @ApiModelProperty(value = "检定人员名称", dataType = "String") + @ExcelProperty(value = "检定人员", order = 8) private String measurePersonName; @ApiModelProperty(value = "审批状态", dataType = "String") @DictCodeField(message = "审批状态不合法", cacheName = MeterDictCode.APPROVAL_STATUS) private String approvalStatus; -// @ApiModelProperty(value = "备注", dataType = "String") -// private String remark; -// -// private Long createUser; -// @ApiModelProperty(value = "创建时间", dataType = "String") + @ExcelProperty(value = "创建时间", order = 10) private String createTime; -// @ApiModelProperty(value = "检校专业名称", dataType = "String") -// private String calibrationMajorName; - @ApiModelProperty(value = "审批状态名称", dataType = "String") + @ExcelProperty(value = "审批状态", order = 9) private String approvalStatusName; /** @@ -120,6 +104,7 @@ private String measureCategory; @ApiModelProperty(value = "校验类别名称", dataType = "String") + @ExcelProperty(value = "校验类别", order = 7) private String measureCategoryName; diff --git a/casic-metering-model/src/main/java/com/casic/missiles/dto/business/originRecord/OriginRecordRequest.java b/casic-metering-model/src/main/java/com/casic/missiles/dto/business/originRecord/OriginRecordRequest.java index d2c2ec7..d2687bf 100644 --- a/casic-metering-model/src/main/java/com/casic/missiles/dto/business/originRecord/OriginRecordRequest.java +++ b/casic-metering-model/src/main/java/com/casic/missiles/dto/business/originRecord/OriginRecordRequest.java @@ -31,7 +31,7 @@ @ApiModelProperty(value = "创建人", dataType = "String") private String createUser; - @ApiModelProperty(value = "原始记录单id", dataType = "Long") + @ApiModelProperty(value = "委托书id", dataType = "Long") private Long id; @ApiModelProperty(value = "导出ids(查询不用传)", dataType = "List") diff --git a/casic-metering-api/src/main/java/com/casic/missiles/controller/business/BusinessCertificateReportController.java b/casic-metering-api/src/main/java/com/casic/missiles/controller/business/BusinessCertificateReportController.java index c440253..408b580 100644 --- a/casic-metering-api/src/main/java/com/casic/missiles/controller/business/BusinessCertificateReportController.java +++ b/casic-metering-api/src/main/java/com/casic/missiles/controller/business/BusinessCertificateReportController.java @@ -9,17 +9,13 @@ import com.casic.missiles.dto.business.certificate.CertificateReportApprovalRequest; import com.casic.missiles.dto.business.certificate.CertificateReportResponse; import com.casic.missiles.dto.flowable.ApprovalDeleteRequest; -import com.casic.missiles.dto.meter.TraceSupplierListRequest; import com.casic.missiles.enums.BusinessExceptionEnum; import com.casic.missiles.exception.BusinessException; import com.casic.missiles.model.business.BusinessCertificateReport; import com.casic.missiles.model.exception.enums.CoreExceptionEnum; -import com.casic.missiles.model.meter.MeterTraceSupplier; import com.casic.missiles.service.business.IBusinessCertificateReportService; -import com.casic.missiles.service.meter.IMeterTraceSupplierService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.util.CollectionUtils; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.*; @@ -45,28 +41,7 @@ public class BusinessCertificateReportController extends ExportController { @Resource private IBusinessCertificateReportService certificateReportService; - @Autowired - private IMeterTraceSupplierService traceSupplierService; - @ApiOperation("证书报告列表(分页)") - @PostMapping("/listPage") - @ResponseBody - public ReturnDTO> supplierListPage(@RequestBody @Valid TraceSupplierListRequest request, BindingResult bindingResult) { - if (bindingResult.hasErrors()) { - throw new BusinessException(CoreExceptionEnum.REQUEST_NULL.getCode(), bindingResult.getFieldError().getDefaultMessage()); - } - Page page = PageFactory.defaultPage(); - return ReturnUtil.success(super.packForBT(traceSupplierService.listPage(page, request))); - } - @ApiOperation("证书报告列表") - @PostMapping("/list") - @ResponseBody - public ReturnDTO> supplierList(@RequestBody @Valid TraceSupplierListRequest request, BindingResult bindingResult) { - if (bindingResult.hasErrors()) { - throw new BusinessException(CoreExceptionEnum.REQUEST_NULL.getCode(), bindingResult.getFieldError().getDefaultMessage()); - } - return ReturnUtil.success(traceSupplierService.list(request)); - } @ApiOperation("证书报告记录导出") @PostMapping("/listExport") @@ -113,18 +88,6 @@ return certificateReportService.submitCertificateReport(request); } - @ApiOperation("证书报告更新(审批通过后还能更新??暂时保留。。)") - @PostMapping("/update") - @ResponseBody - public ReturnDTO supplierUpdate(@RequestBody @Valid MeterTraceSupplier traceSupplier, BindingResult bindingResult) { - Assert.isFalse(Objects.isNull(traceSupplier.getId()), () -> { - throw new BusinessException(BusinessExceptionEnum.ID_NULL); - }); - Assert.isFalse(bindingResult.hasErrors(), () -> { - throw new BusinessException(CoreExceptionEnum.REQUEST_NULL.getCode(), bindingResult.getFieldError().getDefaultMessage()); - }); - return traceSupplierService.updateTraceSupplier(traceSupplier); - } @ApiOperation("证书报告批量删除") @PostMapping("/batchDelete") diff --git a/casic-metering-api/src/main/java/com/casic/missiles/controller/system/PoiController.java b/casic-metering-api/src/main/java/com/casic/missiles/controller/system/PoiController.java index 021eaa8..9848e68 100644 --- a/casic-metering-api/src/main/java/com/casic/missiles/controller/system/PoiController.java +++ b/casic-metering-api/src/main/java/com/casic/missiles/controller/system/PoiController.java @@ -3,12 +3,14 @@ import cn.afterturn.easypoi.entity.ImageEntity; import com.casic.missiles.utils.PdfUtil; +import com.casic.missiles.utils.StampUtils; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.stereotype.Controller; import org.springframework.util.Assert; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpServletResponse; import java.io.*; @@ -23,7 +25,51 @@ private String filepath="C:\\upload"; @ApiOperation("word转pdf") + @PostMapping(value = "/convertWordToPdf1") + @ResponseBody + public void convertWordToPdf1() throws Exception { + File uploadFile = new File(filepath); + String wordDir = ""; + if (!uploadFile.exists()) { + uploadFile.mkdirs(); + } + if (!filepath.endsWith("/")) { + wordDir = filepath + File.separator + "word"; + } + File tf = new File(wordDir + File.separator + "tem.docx"); + File tf_pic = new File(wordDir + File.separator + "logo.jpg"); + String pic_url = tf_pic.getCanonicalPath(); + Calendar now = Calendar.getInstance(); + Map params = new HashMap<>(); + List> dataList=new ArrayList<>(); + for (int i = 0; i < 5; i++) { + Map param = new HashMap<>(); + param.put("name", "彭于晏"+i); + param.put("sex", "男"+i); + param.put("address", "中国"+i); + ImageEntity image = new ImageEntity(); + image.setHeight(100); + image.setWidth(100); + image.setUrl(pic_url); + image.setData(PdfUtil.getImageBase64(pic_url)); + param.put("image", image); + dataList.add(param); + } + + params.put("dataList",dataList); + params.put("y", now.get(Calendar.YEAR)); + params.put("m", (now.get(Calendar.MONTH) + 1)); + params.put("d", now.get(Calendar.DAY_OF_MONTH)); + + String fileName = "wordExport.docx"; + String word = StampUtils.exportWord(tf.getPath(), wordDir, fileName, params); + System.out.println("****新模板"+word); + + } + + @ApiOperation("word转pdf") @PostMapping(value = "/convertWordToPdf") + @ResponseBody public void convertWordToPdf(HttpServletResponse response) throws Exception { File uploadFile = new File(filepath); String wordDir = ""; @@ -117,4 +163,5 @@ } } } + } diff --git a/casic-metering-common/pom.xml b/casic-metering-common/pom.xml index bb00ab9..e028713 100644 --- a/casic-metering-common/pom.xml +++ b/casic-metering-common/pom.xml @@ -11,6 +11,7 @@ casic-metering-common + @@ -171,6 +172,14 @@ 4.1.2 + + + + e-iceblue + spire.office.free + 5.3.1 + + com.google.zxing diff --git a/casic-metering-common/src/main/java/com/casic/missiles/utils/CustomXWPFDocumentUtil.java b/casic-metering-common/src/main/java/com/casic/missiles/utils/CustomXWPFDocumentUtil.java deleted file mode 100644 index 9e7ed3f..0000000 --- a/casic-metering-common/src/main/java/com/casic/missiles/utils/CustomXWPFDocumentUtil.java +++ /dev/null @@ -1,309 +0,0 @@ -package com.casic.missiles.utils; - -import java.io.*; -import java.util.*; -import java.util.Map.Entry; - -import cn.afterturn.easypoi.entity.ImageEntity; -import org.apache.commons.lang3.StringUtils; -import org.apache.poi.ooxml.POIXMLDocument; -import org.apache.poi.openxml4j.exceptions.InvalidFormatException; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.util.Units; -import org.apache.poi.xwpf.usermodel.*; -import org.apache.xmlbeans.XmlException; -import org.apache.xmlbeans.XmlToken; -import org.openxmlformats.schemas.drawingml.x2006.main.CTGraphicalObject; -import org.openxmlformats.schemas.drawingml.x2006.main.CTNonVisualDrawingProps; -import org.openxmlformats.schemas.drawingml.x2006.main.CTPositiveSize2D; -import org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.CTAnchor; -import org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.CTInline; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTDrawing; - -public class CustomXWPFDocumentUtil extends XWPFDocument { - - public CustomXWPFDocumentUtil(InputStream in) throws IOException { - super(in); - } - - public CustomXWPFDocumentUtil() { - super(); - } - - public CustomXWPFDocumentUtil(OPCPackage pkg) throws IOException { - super(pkg); - } - - /** - * 根据指定的参数值、模板,生成 word 文档 - * - * @param param 需要替换的变量 - * @param template 模板 - */ - public static XWPFDocument generateWord(Map param, String template) { - XWPFDocument doc = null; - try { - OPCPackage pack = POIXMLDocument.openPackage(template); - doc = new CustomXWPFDocumentUtil(pack); - if (param != null && param.size() > 0) { - - //处理段落 - List paragraphList = doc.getParagraphs(); - processParagraphs(paragraphList, param, doc); - - //处理表格 - Iterator it = doc.getTablesIterator(); - while (it.hasNext()) { - XWPFTable table = it.next(); - List rows = table.getRows(); - for (XWPFTableRow row : rows) { - List cells = row.getTableCells(); - for (XWPFTableCell cell : cells) { - List paragraphListTable = cell.getParagraphs(); - processParagraphs(paragraphListTable, param, doc); - } - } - } - } - } catch (IOException e) { - e.printStackTrace(); - } catch (Exception e) { - e.printStackTrace(); - } - return doc; - } - - /** - * 处理段落 - * - * @param paragraphList - * @param - * @throws FileNotFoundException - * @throws InvalidFormatException - */ - public static void processParagraphs(List paragraphList, Map param, XWPFDocument doc) throws InvalidFormatException, FileNotFoundException { - if (paragraphList != null && paragraphList.size() > 0) { - for (XWPFParagraph paragraph : paragraphList) { - List runs = paragraph.getRuns(); - for (XWPFRun run : runs) { - String text = run.getText(0); - //System.out.println("text=="+text); - if (text != null) { - boolean isSetText = false; - for (Entry entry : param.entrySet()) { - String key = entry.getKey(); - if (text.indexOf(key) != -1) { - isSetText = true; - Object value = entry.getValue(); - if (value instanceof String) {//文本替换 - //System.out.println("key=="+key); - text = text.replace(key, value.toString()); - } else if (value instanceof Map) { //图片替换 - text = text.replace(text, ""); - Map pic = (Map) value; - int width = Integer.parseInt(pic.get("width").toString()); - int height = Integer.parseInt(pic.get("height").toString()); - int picType = getPictureType(pic.get("type").toString()); - String picPath = (String) pic.get("picPath"); - CTInline inline = run.getCTR().addNewDrawing().addNewInline(); - insertPicture(doc, picPath, inline, width, height); - CTDrawing drawing = run.getCTR().getDrawingArray(0); - CTGraphicalObject graphicalobject = drawing.getInlineArray(0).getGraphic(); - //拿到新插入的图片替换添加CTAnchor 设置浮动属性 删除inline属性 - CTAnchor anchor = getAnchorWithGraphic(graphicalobject, "11", - Units.toEMU(width), Units.toEMU(height),//图片大小 - Units.toEMU(0), Units.toEMU(0));//相对当前段落位置的偏移位置,左右偏移:负数向左,正数向右,上下偏移:负数向上,正数向下 - drawing.setAnchorArray(new CTAnchor[]{anchor});//添加浮动属性 - drawing.removeInline(0);//删除行内属性 - } - } - } - if (isSetText) { - run.setText(text, 0); - } - } - } - } - } - } - - /** - * 根据图片类型,取得对应的图片类型代码 - * - * @param picType - * @return int - */ - private static int getPictureType(String picType) { - int res = CustomXWPFDocumentUtil.PICTURE_TYPE_PICT; - if (picType != null) { - if (picType.equalsIgnoreCase("png")) { - res = CustomXWPFDocumentUtil.PICTURE_TYPE_PNG; - } else if (picType.equalsIgnoreCase("dib")) { - res = CustomXWPFDocumentUtil.PICTURE_TYPE_DIB; - } else if (picType.equalsIgnoreCase("emf")) { - res = CustomXWPFDocumentUtil.PICTURE_TYPE_EMF; - } else if (picType.equalsIgnoreCase("jpg") || picType.equalsIgnoreCase("jpeg")) { - res = CustomXWPFDocumentUtil.PICTURE_TYPE_JPEG; - } else if (picType.equalsIgnoreCase("wmf")) { - res = CustomXWPFDocumentUtil.PICTURE_TYPE_WMF; - } - } - return res; - } - - /** - * insert Picture - * - * @param document - * @param filePath - * @param inline - * @param width - * @param height - * @throws InvalidFormatException - * @throws FileNotFoundException - */ - private static void insertPicture(XWPFDocument document, String filePath, - CTInline inline, int width, - int height) throws InvalidFormatException, - FileNotFoundException { - document.addPictureData(new FileInputStream(filePath), XWPFDocument.PICTURE_TYPE_PNG); - int id = document.getAllPictures().size() - 1; - final int EMU = 9525; - width *= EMU; - height *= EMU; - String blipId = - document.getAllPictures().get(id).getRelationId(document); - String picXml = getPicXml(blipId, width, height); - XmlToken xmlToken = null; - try { - xmlToken = XmlToken.Factory.parse(picXml); - } catch (XmlException xe) { - xe.printStackTrace(); - } - inline.set(xmlToken); - inline.setDistT(0); - inline.setDistB(0); - inline.setDistL(0); - inline.setDistR(0); - CTPositiveSize2D extent = inline.addNewExtent(); - extent.setCx(width); - extent.setCy(height); - CTNonVisualDrawingProps docPr = inline.addNewDocPr(); - docPr.setId(id); - docPr.setName("IMG_" + id); - docPr.setDescr("IMG_" + id); - } - - /** - * get the xml of the picture - * - * @param blipId - * @param width - * @param height - * @return - */ - private static String getPicXml(String blipId, int width, int height) { - String picXml = - "" + "" + - " " + - " " + - " " + " " + " " + - " " + " " + - " " + - " " + " " + - " " + " " + - " " + " " + - " " + - " " + " " + - " " + - " " + " " + - " " + " " + - " " + ""; - return picXml; - } - - /** - * @param ctGraphicalObject 图片数据 - * @param deskFileName 图片描述 - * @param width 宽 - * @param height 高 - * @param leftOffset 水平偏移:负数向左,正数向右 - * @param topOffset 垂直偏移:负数向上,正数向下 - * @return CTAnchor - * @throws Exception - */ - public static CTAnchor getAnchorWithGraphic(CTGraphicalObject ctGraphicalObject, - String deskFileName, int width, int height, - int leftOffset, int topOffset) { - //浮在文字上的设置主要是anchor标签下的behindDoc属性设为0,同时添加一个的空标签。 - if (StringUtils.isBlank(deskFileName)) { - deskFileName = new Random().nextInt(999) + "";//描述不能为空,赋值一个随机数 - } - String anchorXML = - "" - + "" - + "" - + "" + leftOffset + "" - + "" - + "" - + "" + topOffset + "" + - "" - + "" - + "" - + "" - + "" - + ""; - CTDrawing drawing = null; - try { - drawing = CTDrawing.Factory.parse(anchorXML); - } catch (XmlException e) { - e.printStackTrace(); - } - CTAnchor anchor = drawing.getAnchorArray(0); - anchor.setGraphic(ctGraphicalObject); - return anchor; - } - public static void main(String[] args) throws IOException{ - Map params = new HashMap<>(); - List> dataList=new ArrayList<>(); - for (int i = 0; i < 5; i++) { - Map param = new HashMap<>(); - param.put("name", "彭于晏"+i); - param.put("sex", "男"+i); - param.put("address", "中国"+i); - ImageEntity image = new ImageEntity(); - image.setHeight(100); - image.setWidth(100); - image.setUrl("C:\\upload\\word\\"); - image.setData(PdfUtil.getImageBase64("C:\\upload\\word\\logo.jpg")); - param.put("image", image); - dataList.add(param); - } - Calendar now = Calendar.getInstance(); - params.put("dataList",dataList); - params.put("y", now.get(Calendar.YEAR)+""); - params.put("m", (now.get(Calendar.MONTH) + 1)+""); - params.put("d", now.get(Calendar.DAY_OF_MONTH)+""); - String template="C:\\upload\\word\\tem.docx"; - ByteArrayOutputStream baos = null; - try { - XWPFDocument document = generateWord(params, template); - baos = new ByteArrayOutputStream(); - document.write(baos);//临时存储流到内存 - baos.flush(); - } catch (Exception e) { - e.printStackTrace(); - }finally{ - if(baos != null){ - baos.close(); - } - } - - - } - -} diff --git a/casic-metering-common/src/main/java/com/casic/missiles/utils/PdfUtil.java b/casic-metering-common/src/main/java/com/casic/missiles/utils/PdfUtil.java index 3d80a8e..3e4f58b 100644 --- a/casic-metering-common/src/main/java/com/casic/missiles/utils/PdfUtil.java +++ b/casic-metering-common/src/main/java/com/casic/missiles/utils/PdfUtil.java @@ -23,12 +23,12 @@ public class PdfUtil { /** - * 生成word 只支持docx + * 按照模板 填充数据生成word 只支持docx * * @param templatePath 模板文件路径 - * @param temDir 生成文件的目录 - * @param fileName 生成文件名 - * @param params 参数 + * @param temDir 生成文件的目录 + * @param fileName 生成文件名 + * @param params 参数 */ public static String exportWord(String templatePath, String temDir, String fileName, Map params) { Assert.notNull(templatePath, "模板路径不能为空"); @@ -39,8 +39,9 @@ temDir = temDir + File.separator; } File dir = new File(temDir); - if (!dir.exists()) { - dir.mkdirs(); + if (!dir.getParentFile().exists()) { + // 新建文件夹 + dir.getParentFile().mkdirs(); } String tmpPath = ""; try { @@ -51,13 +52,13 @@ fos.flush(); fos.close(); } catch (Exception e) { - //e.printStackTrace(); + e.printStackTrace(); } return tmpPath; } - public static String convertDocx2Pdf(String wordPath,String pdfPath) { + public static String convertDocx2Pdf(String wordPath, String pdfPath) { OutputStream os = null; InputStream is = null; try { diff --git a/casic-metering-common/src/main/java/com/casic/missiles/utils/PictureUtil.java b/casic-metering-common/src/main/java/com/casic/missiles/utils/PictureUtil.java deleted file mode 100644 index 4baa893..0000000 --- a/casic-metering-common/src/main/java/com/casic/missiles/utils/PictureUtil.java +++ /dev/null @@ -1,184 +0,0 @@ -//package com.casic.missiles.utils; -// -//import cn.hutool.core.codec.Base64; -//import com.alibaba.fastjson.JSONObject; -//import com.google.common.collect.Lists; -//import org.apache.poi.xwpf.usermodel.*; -//import org.apache.xmlbeans.XmlException; -//import org.openxmlformats.schemas.drawingml.x2006.main.CTGraphicalObject; -//import org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.CTAnchor; -//import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTDrawing; -// -//import java.io.*; -//import java.util.List; -//import java.util.Map; -//import java.util.Set; -// -//public class PictureUtil { -// public void create(String filePath, JSONObject jsonObject) { -// try { -// FileInputStream template = new FileInputStream(new File(filePath)); -// //获取docx解析对象 -// XWPFDocument document = new XWPFDocument(template); -// List tableList = Lists.newArrayList(); -// -// //解析替换表格对象 -// List tables = document.getTables(); -// for (int i = 0; i < tables.size(); i++) { -// //只处理行数大于等于2的表格,且不循环表头 -// XWPFTable table = tables.get(i); -// if (table.getRows().size() > 1) { -// //判断表格是需要替换还是需要插入,判断逻辑有$为替换,表格无$为插入 -// if (WordUtil.checkText(table.getText())) { -// List rows = table.getRows(); -// //遍历表格,并替换模板 -// eachTable(rows, jsonObject); -// } -// } -// } -// -// // workBook写入输出流 -// ByteArrayOutputStream baos = new ByteArrayOutputStream(); -// document.write(baos); -// baos.flush(); -// } catch (Exception e) { -// e.printStackTrace(); -// } -// } -// /** -// * 遍历表格 -// * -// * @param rows 表格行对象 -// * @param textMap 需要替换的信息集合 -// */ -// public static void eachTable(List rows, JSONObject textMap) { -// for (XWPFTableRow row : rows) { -// List cells = row.getTableCells(); -// for (XWPFTableCell cell : cells) { -// //判断单元格是否需要替换 -// if (checkText(cell.getText())) { -// List paragraphs = cell.getParagraphs(); -// for (XWPFParagraph paragraph : paragraphs) { -// List runs = paragraph.getRuns(); -// for (XWPFRun run : runs) { -//// run.setText(changeValue(run.toString(), textMap), 0); -// //新增制证照片单独处理 -// if (run.toString().indexOf("${jpeg}") != -1 && textMap.containsKey("jpeg")){ -// addPic(run,textMap, 1188000, 1728000,0, 0); -// break; -// } -// String value = changeValue(run.toString(), textMap); -// setWrap(value, run); -// } -// } -// } -// } -// } -// } -// -// /** -// * 匹配传入信息集合与模板 -// * -// * @param value 模板需要替换的区域 -// * @param textMap 传入信息集合 -// * @return 模板需要替换区域信息集合对应值 -// */ -// public static String changeValue(String value, JSONObject textMap) { -// -// boolean flag = false; -// Set> textSets = textMap.entrySet(); -// for (Map.Entry textSet : textSets) { -// //匹配模板与替换值 格式${key} -// String key = "${" + textSet.getKey() + "}"; -// if (value.indexOf(key) != -1) { -// value = textSet.getValue() == null ? "" : ("" + textSet.getValue()); -// flag = true; -// break; -// } -// } -// //模板未匹配到区域替换为空 -// if (checkText(value)) { -// value = ""; -// } -// return value; -// } -// public static void setWrap(String value, XWPFRun run) { -// if ( value.indexOf("\n") > 0) { -// //设置换行 -// String[] text = value.split("\n"); -// for (int f = 0; f < text.length; f++) { -// if (f == 0) { -// run.setText(text[f].trim(),0); -// } else { -//// run.addCarriageReturn();//硬回车 -// // 换行 -// run.addBreak(); -// run.setText(text[f]); -// } -// } -// } else { -// run.setText((String) value,0); -// } -// } -// -// /** -// * @param ctGraphicalObject 图片数据 -// * @param deskFileName 图片描述 -// * @param width 宽 -// * @param height 高 -// * @param leftOffset 水平偏移 left -// * @param topOffset 垂直偏移 top -// * @param behind 文字上方,文字下方 -// * @return -// * @throws Exception -// */ -// public static CTAnchor getAnchorWithGraphic(CTGraphicalObject ctGraphicalObject, String deskFileName, int width, int height, int leftOffset, int topOffset, boolean behind) { -// String anchorXML ="" -// +"" -// +" " -// +" " -// +" "+ leftOffset + "" -// +" " -// +" " -// +" "+ topOffset +"" -// +" " -// +" " -// +" " -// +" " -// +" " -// +""; -// try { -// CTDrawing drawing = CTDrawing.Factory.parse(anchorXML); -// CTAnchor anchor = drawing.getAnchorArray(0); -// anchor.setGraphic(ctGraphicalObject); -// return anchor; -// } catch (XmlException e) { -// e.printStackTrace(); -// return null; -// } -// } -// -// /** -// * 新增制证照片单独处理 -// * @param run -// * @param textMap -// */ -// public static void addPic(XWPFRun run, JSONObject textMap, int width, int height, int leftOffset, int topOffset){ -// String runText = run.toString().trim(); -// byte[] zjzp = Base64.decode(textMap.getString("jpeg")); -// try(ByteArrayInputStream byteInputStream = new ByteArrayInputStream(zjzp)) { -// //1、添加图片 -// run.addPicture(byteInputStream,XWPFDocument.PICTURE_TYPE_JPEG,"照片", width, height); -// //2、获取图片 -// CTDrawing cTDrawing = run.getCTR().getDrawingArray(0); -// CTGraphicalObject cTGraphicalObject = cTDrawing.getInlineArray(0).getGraphic(); -// //3、设置属性 -// CTAnchor ctAnchor = getAnchorWithGraphic(cTGraphicalObject,"照片", width, height,leftOffset, topOffset,false); -// cTDrawing.setAnchorArray(new CTAnchor[]{ctAnchor}); -// cTDrawing.removeInline(0); -// run.setText(runText.replace("${jpeg}",""), 0); -// }catch (Exception e){ -// e.printStackTrace(); -// } -// } -//} diff --git a/casic-metering-common/src/main/java/com/casic/missiles/utils/StampUtils.java b/casic-metering-common/src/main/java/com/casic/missiles/utils/StampUtils.java new file mode 100644 index 0000000..fb6d4cf --- /dev/null +++ b/casic-metering-common/src/main/java/com/casic/missiles/utils/StampUtils.java @@ -0,0 +1,482 @@ +package com.casic.missiles.utils; + + +import cn.afterturn.easypoi.word.WordExportUtil; +import cn.hutool.core.lang.Assert; +import com.baomidou.mybatisplus.core.toolkit.ObjectUtils; +import com.spire.doc.*; +import com.spire.doc.documents.*; +import com.spire.doc.fields.DocPicture; +import com.spire.doc.fields.TextRange; +import org.apache.commons.lang3.StringUtils; +import org.apache.poi.xwpf.usermodel.XWPFDocument; + +import javax.imageio.ImageIO; +import java.awt.*; +import java.awt.image.BufferedImage; +import java.io.*; +import java.util.Map; + +/** + * @Author:zt + * @Create:2023/3/7/9:30 + * @Description:TODO Word文件操作工具类 + * @Version:1.0 + */ + +public class StampUtils { + + //关键字索引 (-1) + private final static Integer keyWordIndex = -1; + // 电子印章水平位置 + private final static float horizontal = 300f; + // 电子印章垂直位置 + private final static float vertical = -55f; + // 电子印章宽度 + private final static float stampWidth = 120; + // 电子印章高度 + private final static float stampHeight = 120; + //照片透明度设置 + private final static int alpha = 150; + + + /** + * 1、自定义位置添加电子印章 + * 2、替换书签名位置文本内容 bookmarkName传参为null,则不进行书签替换操作 + * + * @param wordOldUrl word文件路径 + * @param wordNewUrl 新word文件路径 + * @param stampImgUrl 电子印章图片路径 + * @param horizontal 电子印章水平位置 (当前文件推荐260f) + * @param vertical 电子印章垂直位置 (当前推荐455f) + * @param stampWidth 电子印章宽度(推荐120) + * @param stampHeight 电子印章高度(推荐120) + * @param bookmarkName 书签名,通过名称寻找书签文本所在位置 + * @param newBookmarkText 替换的文本新内容 + */ + public void addStamp(String wordOldUrl, String wordNewUrl, String stampImgUrl, + Float horizontal, Float vertical, Float stampWidth, + Float stampHeight, String bookmarkName, String newBookmarkText) { + // 加载文档 + Document document = new Document(); + document.loadFromFile(wordOldUrl); + +// 获取指定段落 + Section section = document.getSections().get(0); +// 获取段落总数 + int count = section.getParagraphs().getCount(); +// log.info("获取文档内容段落总数{}",count); + Paragraph paragraph = section.getParagraphs().get(0); + + // 判断是否需要替换书签位置文本内容 + if (StringUtils.isNotEmpty(bookmarkName)) { + replaceBookmarkContent(document, bookmarkName, newBookmarkText); + } + +// 添加电子印章 + DocPicture docPicture = paragraph.appendPicture(stampImgUrl); + +// 指定电子章位置 +// 水平位置 + docPicture.setHorizontalPosition(horizontal); +// 垂直位置 + docPicture.setVerticalPosition(vertical); + +// 设置电子章大小 + docPicture.setWidth(stampWidth); + docPicture.setHeight(stampHeight); + +// 设置图片位于文字顶层 + docPicture.setTextWrappingStyle(TextWrappingStyle.In_Front_Of_Text); + + // 保存添加电子章的Word文档 + document.saveToFile(wordNewUrl); + document.dispose(); +// log.info("文档添加电子印章结束,新WORD文档地址:{}",wordNewUrl); + + } + + /** + * 1、根据关键词位置添加电子印章 + * 2、替换书签名位置文本内容 bookmarkName传参为null,则不进行书签替换操作 + * + * @param wordOldUrl word文件路径 + * @param wordNewUrl 新word文件路径 + * @param stampImgUrl 电子印章图片路径 + * @param keyWord 关键字 (自定义) + * @param keyWordIndex 关键字索引 (-1) + * @param horizontal 电子印章水平位置 (260f) + * @param vertical 电子印章垂直位置 (-55f) + * @param stampWidth 电子印章宽度 (推荐120) + * @param stampHeight 电子印章高度(推荐120) + */ + public static void addKeyWordStamp(String wordOldUrl, String wordNewUrl, String stampImgUrl, String stampImgUrl1, + String keyWord, Integer keyWordIndex, Float horizontal, + Float vertical, Float stampWidth, Float stampHeight) { + // 加载文档 + Document document = new Document(); + document.loadFromFile(wordOldUrl); + //获取关键字位置 + TextSelection[] textSelections = document.findAllString(keyWord, false, false); + //加签章照片 + if (ObjectUtils.isNotEmpty(textSelections) && StringUtils.isNotEmpty(stampImgUrl)) { + Paragraph paragraph = textSelections[keyWordIndex > -1 ? 0 : textSelections.length - 1].getAsOneRange().getOwnerParagraph(); + //添加公司印章 + DocPicture docPicture = paragraph.appendPicture(stampImgUrl); + + //设置图片位于文字顶层 + docPicture.setTextWrappingStyle(TextWrappingStyle.In_Front_Of_Text); + + //指定电子章位置 + //水平位置 + docPicture.setHorizontalPosition(horizontal); + //垂直位置 + docPicture.setVerticalPosition(vertical); + //设置电子章大小 + docPicture.setWidth(stampWidth); + docPicture.setHeight(stampHeight); + } + + //加签名照片 + if (ObjectUtils.isNotEmpty(textSelections) && StringUtils.isNotEmpty(stampImgUrl1)) { + Paragraph paragraph = textSelections[keyWordIndex > -1 ? 0 : textSelections.length - 1].getAsOneRange().getOwnerParagraph(); + // 添加电子印章 + DocPicture docPicture = paragraph.appendPicture(stampImgUrl1); + //设置图片位于文字顶层 + docPicture.setTextWrappingStyle(TextWrappingStyle.In_Front_Of_Text); + + //指定电子章位置 + //水平位置 + docPicture.setHorizontalPosition(horizontal); + //垂直位置 + docPicture.setVerticalPosition(vertical); + //设置电子章大小 + docPicture.setWidth(stampWidth); + docPicture.setHeight(stampHeight); + } + + //保存添加电子章的Word文档 + document.saveToFile(wordNewUrl); + document.dispose(); + } + + /** + * 替换书签名位置文本内容 + * + * @param document word文档对象 + * @param bookmarkName 书签名 + * @param newBookmarkText 新文本内容 + */ + public void replaceBookmarkContent(Document document, String bookmarkName, String newBookmarkText) { + //定位到指定书签位置 + BookmarksNavigator bookmarksNavigator = new BookmarksNavigator(document); + bookmarksNavigator.moveToBookmark(bookmarkName); + //用文本内容替换原有书签位置的文本,新替换的内容与原文格式一致 + bookmarksNavigator.replaceBookmarkContent(newBookmarkText, true); + } + + /** + * 替换书签名位置文本内容为图片 + * + * @param document word文档对象 + * @param bookmarkName 书签名 + * @param newImgUrl 图片地址 + */ + public void replaceBookmarkContentToImg(Document document, String bookmarkName, String newImgUrl) { + //定位到指定书签位置 + BookmarksNavigator bookmarksNavigator = new BookmarksNavigator(document); + bookmarksNavigator.moveToBookmark(bookmarkName); + //添加图片,替换原有书签内容 + Paragraph para = new Paragraph(document); + para.appendPicture(newImgUrl); + TextBodyPart bodyPart = new TextBodyPart(document); + bodyPart.getBodyItems().add(para); + bookmarksNavigator.replaceBookmarkContent(bodyPart); + } + + /** + * 替换书签名位置文本内容为表格 + * + * @param document word文档对象 + * @param bookmarkName 书签名 + */ + public void replaceBookmarkContentToTable(Document document, String bookmarkName) { + //声明数组内容 + String[][] data = + { + new String[]{"分类", "等级", "编号"}, + new String[]{"A", "一级", "01A"}, + new String[]{"B", "二级", "02B"}, + new String[]{"C", "三级", "03C"}, + }; + + //创建表格 + Table table = new Table(document, true); + table.resetCells(4, 3); + for (int i = 0; i < data.length; i++) { + TableRow dataRow = table.getRows().get(i); + for (int j = 0; j < data[i].length; j++) { + TextRange range = dataRow.getCells().get(j).addParagraph().appendText(data[i][j]); + range.getOwnerParagraph().getFormat().setHorizontalAlignment(HorizontalAlignment.Center); + range.getCharacterFormat().setFontName("楷体"); + dataRow.getRowFormat().setHorizontalAlignment(RowAlignment.Center); + dataRow.getCells().get(j).getCellFormat().setVerticalAlignment(VerticalAlignment.Middle); + } + } + + //创建TextBodyPart对象 + TextBodyPart bodyPart = new TextBodyPart(document); + bodyPart.getBodyItems().add(table); + + //定位到指定书签位置 + BookmarksNavigator bookmarkNavigator = new BookmarksNavigator(document); + bookmarkNavigator.moveToBookmark(bookmarkName); + + //使用表格替换原书签的内容 + bookmarkNavigator.replaceBookmarkContent(bodyPart); + } + + /** + * 文件转流 + * + * @param wordNewUrl + * @return + */ + public byte[] getBytesByFile(String wordNewUrl) { + try { +// byte[] bytes = Files.readAllBytes(Paths.get(wordNewUrl)); + File file = new File(wordNewUrl); + FileInputStream fis = new FileInputStream(file); + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + byte[] b = new byte[1024]; + int len = -1; + while ((len = fis.read(b)) != -1) { + bos.write(b, 0, len); + } + fis.close(); + bos.close(); + byte[] bytes = bos.toByteArray(); + System.out.println("successful..."); + return bytes; + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + /** + * 流转文件 + * + * @param buf 流字节数组 + * @param filePath 新文件路径 + * @param fileName 新文件名称 + */ + public void byte2File(byte[] buf, String filePath, String fileName) { + BufferedOutputStream bos = null; + FileOutputStream fos = null; + File file = null; + try { + File dir = new File(filePath); + if (!dir.exists() && dir.isDirectory()) { + dir.mkdirs(); + } + file = new File(filePath + File.separator + fileName); + fos = new FileOutputStream(file); + bos = new BufferedOutputStream(fos); + bos.write(buf); + } catch (Exception e) { + e.printStackTrace(); + } finally { + if (bos != null) { + try { + bos.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + if (fos != null) { + try { + fos.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + } + + /** + * word转PDF + * + * @param wordNewUrl word文件路径 + * @param pdfNewUrl 存储新PDF文件路径 + */ + public static void wordToPdf(String wordNewUrl, String pdfNewUrl) { +// 将新Word文档转换为PDF文件 + Document document = new Document(); + document.loadFromFile(wordNewUrl); + document.saveToFile(pdfNewUrl, FileFormat.PDF); + document.dispose(); +// log.info("文档转换结束,新PDF文档地址:{}",pdfNewUrl); + } + + + /** + * 图片透明背景转换 + * + * @param imgsrc + * @param alpha + * @return + */ + public static BufferedImage img_alpha(BufferedImage imgsrc, int alpha) { + try { + //创建一个包含透明度的图片,半透明效果必须要存储为png合适才行,存储为jpg,底色为黑色 + BufferedImage back = new BufferedImage(imgsrc.getWidth(), imgsrc.getHeight(), BufferedImage.TYPE_INT_ARGB); + int width = imgsrc.getWidth(); + int height = imgsrc.getHeight(); + for (int j = 0; j < height; j++) { + for (int i = 0; i < width; i++) { + int rgb = imgsrc.getRGB(i, j); + Color color = new Color(rgb); + Color newcolor = new Color(color.getRed(), color.getGreen(), color.getBlue(), alpha); + back.setRGB(i, j, newcolor.getRGB()); + } + } + return back; + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + //读取图片 + public static BufferedImage file2img(String imgpath) { + try { + BufferedImage bufferedImage = ImageIO.read(new File(imgpath)); + return bufferedImage; + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + //保存图片,extent为格式,"jpg"、"png"等 + public static void img2file(BufferedImage img, String extent, String newfile) { + try { + ImageIO.write(img, extent, new File(newfile)); + } catch (Exception e) { + e.printStackTrace(); + } + } + + + /** + * 按照模板 填充数据生成word 只支持docx + * + * @param templatePath 模板文件路径 + * @param temDir 生成文件的目录 + * @param fileName 生成文件名 + * @param params 参数 + */ + public static String exportWord(String templatePath, String temDir, String fileName, Map params) { + Assert.notNull(templatePath, "模板路径不能为空"); + Assert.notNull(temDir, "临时文件路径不能为空"); + Assert.notNull(fileName, "导出文件名不能为空"); + Assert.isTrue(fileName.endsWith(".docx"), "word导出请使用docx格式"); + if (!temDir.endsWith("/")) { + temDir = temDir + File.separator; + } + File dir = new File(temDir); + if (!dir.getParentFile().exists()) { + // 新建文件夹 + dir.getParentFile().mkdirs(); + } + String tmpPath = ""; + try { + XWPFDocument doc = WordExportUtil.exportWord07(templatePath, params); + tmpPath = temDir + fileName; + FileOutputStream fos = new FileOutputStream(tmpPath); + doc.write(fos); + fos.flush(); + fos.close(); + } catch (Exception e) { + e.printStackTrace(); + } + return tmpPath; + } + + /** + * 按照模板 填充数据生成word 只支持docx + * + * @param templatePath 模板文件路径 + * @param temDir 生成文件的目录 + * @param fileName 生成文件名 + * @param params 填充参数 + */ + public static void generateReport(String templatePath, String temDir, + String fileName, Map params, + String stampImgUrl, String stampImgUrl1, + String wordNewUrl, String keyWord, + Integer keyWordIndex, Float horizontal, + Float vertical, Float stampWidth, + Float stampHeight, String pdfNewUrl) { + //1、按照模板填充数据,并导出word + String wordOldUrl = exportWord(templatePath, temDir, fileName, params); + //2、照片背景透明设置 + //2.1签章背景透明设置 + BufferedImage bi = file2img(stampImgUrl); + BufferedImage bii = img_alpha(bi, alpha); + String newPngPath = stampImgUrl.substring(0, stampImgUrl.length() - 4) + "1.png"; + img2file(bii, "PNG", newPngPath); + //2.2签名背景透明设置 + BufferedImage b = file2img(stampImgUrl1); + BufferedImage b0 = img_alpha(b, alpha); + String newPngPath1 = stampImgUrl.substring(0, stampImgUrl1.length() - 4) + "1.png"; + img2file(b0, "PNG", newPngPath1); + + //3、添加签章和签名 + addKeyWordStamp(wordOldUrl, wordNewUrl, newPngPath, newPngPath1, keyWord, keyWordIndex, + horizontal, vertical, stampWidth, stampHeight); + // 4、将新word转化为pdf文件 + wordToPdf(wordNewUrl, pdfNewUrl); + } + + + public static void main(String[] args) { + + //文件与BufferedImage间的转换 + //读取图片 + BufferedImage bi = file2img("C:\\upload\\word\\sign.png"); + BufferedImage bii = img_alpha(bi, alpha); + //生成透明背景图片 + img2file(bii, "PNG", "C:\\upload\\word\\sign1.png"); + + //文件与BufferedImage间的转换 + //读取图片 + BufferedImage b = file2img("C:\\upload\\word\\name.png"); + BufferedImage b0 = img_alpha(b, alpha); + //生成透明背景图片 + img2file(b0, "PNG", "C:\\upload\\word\\name1.png"); + + // 目标文件地址 + String wordOldUrl = "C:\\upload\\word\\wordExport.docx"; + // 添加电子印章后文件存放地址 + String wordNewUrl = "C:\\upload\\word\\tem2.docx"; + //WORD转PDF存放位置 + String pdfNewUrl = "C:\\upload\\word\\tem2.pdf"; + //电子印章图片地址 + String stampImgUrl = "C:\\upload\\word\\sign1.png"; + //电子签名图片地址 + String stampImgUrl1 = "C:\\upload\\word\\name1.png"; + // word文档内容关键字 + String keyWord = "盖章"; + StampUtils addStampUtils = new StampUtils(); + //获取关键字位置并加盖印章并替换书签名位置文本内容 + addStampUtils.addKeyWordStamp(wordOldUrl, wordNewUrl, + stampImgUrl, stampImgUrl1, + keyWord, keyWordIndex, + horizontal, vertical, + stampWidth, stampHeight); + // 将新word转化为pdf文件 + addStampUtils.wordToPdf(wordNewUrl, pdfNewUrl); + } +} \ No newline at end of file diff --git a/casic-metering-model/src/main/java/com/casic/missiles/dto/business/certificate/CertificateReportResponse.java b/casic-metering-model/src/main/java/com/casic/missiles/dto/business/certificate/CertificateReportResponse.java index b43617c..4581acf 100644 --- a/casic-metering-model/src/main/java/com/casic/missiles/dto/business/certificate/CertificateReportResponse.java +++ b/casic-metering-model/src/main/java/com/casic/missiles/dto/business/certificate/CertificateReportResponse.java @@ -1,6 +1,7 @@ package com.casic.missiles.dto.business.certificate; import com.alibaba.excel.annotation.ExcelIgnoreUnannotated; +import com.alibaba.excel.annotation.ExcelProperty; import com.alibaba.excel.annotation.write.style.ColumnWidth; import com.alibaba.excel.annotation.write.style.ContentRowHeight; import com.alibaba.excel.annotation.write.style.ContentStyle; @@ -28,73 +29,56 @@ private Long id; @ApiModelProperty(value = "证书报告编号", dataType = "String") + @ExcelProperty(value = "证书号", order = 0) private String certificateReportCode; @ApiModelProperty(value = "证书报告名称", dataType = "String") + @ExcelProperty(value = "证书名称", order = 1) private String certificateReportName; @ApiModelProperty(value = "样品编号", dataType = "String") + @ExcelProperty(value = "样品编号", order = 2) private String sampleNo; + @ApiModelProperty(value = "样品名称", dataType = "String") + @ExcelProperty(value = "样品名称", order = 3) private String sampleName; + @ApiModelProperty(value = "型号", dataType = "String") + @ExcelProperty(value = "型号", order = 4) private String sampleModel; + @ApiModelProperty(value = "出厂编号", dataType = "String") + @ExcelProperty(value = "出厂编号", order = 5) private String manufacturingNo; + @ApiModelProperty(value = "委托书编号", dataType = "String") + @ExcelProperty(value = "委托书编号", order = 6) private String orderCode; @ApiModelProperty(value = "检校专业", dataType = "String") @DictCodeField(message = "检校专业不合法", cacheName = MeterDictCode.CALIBRATION_MAJOR) private String calibrationMajor; -// @ApiModelProperty(value = "出具日期", dataType = "String") -// private String issuanceDate; -// -// -// @ApiModelProperty(value = "证书有效期", dataType = "String") -// private String expirationDate; -// -// @ApiModelProperty(value = "检定结果", dataType = "String") -// private String measureResult; -// -// -// @ApiModelProperty(value = "原始记录id", dataType = "Long") -// private Long originalRecordId; -// -// -// @ApiModelProperty(value = "可打印状态", dataType = "String") -// private String printStatus; -// -// -// @ApiModelProperty(value = "打印次数", dataType = "Integer") -// private Integer printNum; - - - @ApiModelProperty(value = "检定人员", dataType = "String") + @ApiModelProperty(value = "检定人员id", dataType = "String") private String measurePersonId; @ApiModelProperty(value = "检定人员名称", dataType = "String") + @ExcelProperty(value = "检定人员", order = 8) private String measurePersonName; @ApiModelProperty(value = "审批状态", dataType = "String") @DictCodeField(message = "审批状态不合法", cacheName = MeterDictCode.APPROVAL_STATUS) private String approvalStatus; -// @ApiModelProperty(value = "备注", dataType = "String") -// private String remark; -// -// private Long createUser; -// @ApiModelProperty(value = "创建时间", dataType = "String") + @ExcelProperty(value = "创建时间", order = 10) private String createTime; -// @ApiModelProperty(value = "检校专业名称", dataType = "String") -// private String calibrationMajorName; - @ApiModelProperty(value = "审批状态名称", dataType = "String") + @ExcelProperty(value = "审批状态", order = 9) private String approvalStatusName; /** @@ -120,6 +104,7 @@ private String measureCategory; @ApiModelProperty(value = "校验类别名称", dataType = "String") + @ExcelProperty(value = "校验类别", order = 7) private String measureCategoryName; diff --git a/casic-metering-model/src/main/java/com/casic/missiles/dto/business/originRecord/OriginRecordRequest.java b/casic-metering-model/src/main/java/com/casic/missiles/dto/business/originRecord/OriginRecordRequest.java index d2c2ec7..d2687bf 100644 --- a/casic-metering-model/src/main/java/com/casic/missiles/dto/business/originRecord/OriginRecordRequest.java +++ b/casic-metering-model/src/main/java/com/casic/missiles/dto/business/originRecord/OriginRecordRequest.java @@ -31,7 +31,7 @@ @ApiModelProperty(value = "创建人", dataType = "String") private String createUser; - @ApiModelProperty(value = "原始记录单id", dataType = "Long") + @ApiModelProperty(value = "委托书id", dataType = "Long") private Long id; @ApiModelProperty(value = "导出ids(查询不用传)", dataType = "List") diff --git a/casic-metering-service/src/main/java/com/casic/missiles/service/Impl/business/BusinessCertificateReportServiceImpl.java b/casic-metering-service/src/main/java/com/casic/missiles/service/Impl/business/BusinessCertificateReportServiceImpl.java index d03ab22..aabfac2 100644 --- a/casic-metering-service/src/main/java/com/casic/missiles/service/Impl/business/BusinessCertificateReportServiceImpl.java +++ b/casic-metering-service/src/main/java/com/casic/missiles/service/Impl/business/BusinessCertificateReportServiceImpl.java @@ -26,8 +26,6 @@ import com.casic.missiles.service.business.IBusinessCertificateReportService; import com.casic.missiles.service.business.IBusinessOriginalRecordService; import com.casic.missiles.service.flowable.ApprovalOperateService; -import com.casic.missiles.utils.ConvertUtils; -import com.casic.missiles.utils.DictCodeUtils; import com.casic.missiles.utils.NumberGeneratorUtil; import org.flowable.engine.RuntimeService; import org.flowable.engine.TaskService; @@ -68,8 +66,10 @@ private RuntimeService runtimeService; @Resource private IBaseExportService iBaseExportService; + /** * 保存证书报告信息 + * * @param certificateReport * @return */ @@ -77,7 +77,7 @@ public ReturnDTO saveCertificateReport(BusinessCertificateReport certificateReport) { initCertificateReport(certificateReport); - if(this.baseMapper.insert(certificateReport)>0) + if (this.baseMapper.insert(certificateReport) > 0) return ReturnUtil.success(); throw new BusinessException(BusinessExceptionEnum.HANDLE_FAILED); } @@ -90,9 +90,9 @@ @Override public ReturnDTO approvalDelete(ApprovalDeleteRequest request) { ReturnDTO returnDTO = approvalOperateService.delete(request); - if(ResponseData.DEFAULT_SUCCESS_CODE == returnDTO.getCode()){ + if (ResponseData.DEFAULT_SUCCESS_CODE == returnDTO.getCode()) { //删除数据库记录 - if(this.baseMapper.deleteById(request.getId()) > 0){ + if (this.baseMapper.deleteById(request.getId()) > 0) { return ReturnUtil.success(); } } @@ -101,7 +101,7 @@ @Override public ReturnDTO draftUpdate(BusinessCertificateReport certificateReport) { - if(this.baseMapper.updateById(certificateReport)>0){ + if (this.baseMapper.updateById(certificateReport) > 0) { return ReturnUtil.success(); } throw new BusinessException(BusinessExceptionEnum.HANDLE_FAILED); @@ -109,25 +109,27 @@ /** * 批量删除 + * * @param ids * @return */ @Override public ReturnDTO deleteBatchTraceSupplier(List ids) { - return baseMapper.deleteBatchIds(ids) > 0?ReturnUtil.success(): + return baseMapper.deleteBatchIds(ids) > 0 ? ReturnUtil.success() : ReturnUtil.failed("删除失败"); } /** * 证书报告详情 + * * @param id * @return */ @Override public BusinessCertificateReport certificateReportDetail(Long id) { BusinessCertificateReport certificateReport = this.baseMapper.selectById(id); - if(certificateReport.getOriginalRecordId()!=null){ + if (certificateReport.getOriginalRecordId() != null) { try { certificateReport.setBusinessOriginalRecord(originalRecordService.originalDetail(certificateReport.getOriginalRecordId())); } catch (Exception e) { @@ -139,6 +141,7 @@ /** * 提交证书报告 + * * @param request * @return */ @@ -148,10 +151,10 @@ String formId = request.getFormId(); //2.根据流程定义id启动流程实例 ReturnDTO returnDTO = baseApprovalService.processSubmit(formId, request.getId()); - if(ResponseData.DEFAULT_SUCCESS_CODE != returnDTO.getCode()){ + if (ResponseData.DEFAULT_SUCCESS_CODE != returnDTO.getCode()) { return returnDTO; } - ProcessInstance processInstance = (ProcessInstance)returnDTO.getData(); + ProcessInstance processInstance = (ProcessInstance) returnDTO.getData(); BusinessCertificateReport certificateReport = new BusinessCertificateReport(); certificateReport.setId(request.getId()); certificateReport.setApprovalStatus(ApprovalStatusEnum.UN_DRAFT); //非草稿状态 @@ -165,6 +168,7 @@ /** * 审批状态列表查询 + * * @param page * @param request * @return @@ -182,6 +186,7 @@ /** * 驳回后更新 + * * @param certificateReport * @return */ @@ -208,13 +213,14 @@ @Override public void originExport(CertificateReportApprovalRequest request, HttpServletResponse response) { try { - //toDo: -// List certificateReportResponses = this.certificateReport(request); -// for (OriginRecordResponse originRecordResponse : originExportList) { -// //字典值转换 -// DictCodeUtils.convertDictCodeToName(originRecordResponse); -// } -// iBaseExportService.exportExcel(response, CertificateReportResponse.class, originExportList, ExportEnum.CERTIFICATE_REPORT.getSheetName()); + //登录用户 + AuthUser user = ShiroKit.getUser(); + Assert.isFalse(Objects.isNull(user), () -> { + throw new BusinessException(BusinessExceptionEnum.LOGIN_USER_ACQUIRE_FAILED); + }); + request.setCreateUserId(user.getId()); + List reportResponseList= handleApprovalStatus(null, request); + iBaseExportService.exportExcel(response, CertificateReportResponse.class, reportResponseList, ExportEnum.CERTIFICATE_REPORT.getSheetName()); } catch (Exception e) { log.error("证书报告导出出现异常,异常信息为{}", e); } @@ -231,15 +237,15 @@ //待审批,该状态维护在flowable中 case ApprovalStatusEnum.TO_BE_APPROVED: List toBeApprovedList = baseApprovalService.getToBeApprovedList(request.getFormId()); - if(!CollectionUtils.isEmpty(toBeApprovedList)){ + if (!CollectionUtils.isEmpty(toBeApprovedList)) { businessKeys = toBeApprovedList.stream().map(ToBeApprovedDTO::getBusinessKey).distinct().collect(Collectors.toList()); } - if(!CollectionUtils.isEmpty(businessKeys)){ + if (!CollectionUtils.isEmpty(businessKeys)) { approvalList = handleApprovalListResponse(this.baseMapper.selectBatchForApproval(page, request, businessKeys), ApprovalStatusEnum.TO_BE_APPROVED); //DTO根据业务主键补全taskId approvalList.forEach(approval -> { toBeApprovedList.forEach(toBeApprovedDTO -> { - if(String.valueOf(approval.getId()).equals(toBeApprovedDTO.getBusinessKey())){ + if (String.valueOf(approval.getId()).equals(toBeApprovedDTO.getBusinessKey())) { approval.setTaskId(toBeApprovedDTO.getTaskId()); //补全可选决策项 approval.setDecisionItem(toBeApprovedDTO.getDecisionItem()); @@ -251,27 +257,27 @@ //审批中,该状态维护在flowable中 case ApprovalStatusEnum.IN_APPROVED: businessKeys = baseApprovalService.getInApprovedList(request.getFormId()); - if(!CollectionUtils.isEmpty(businessKeys)){ + if (!CollectionUtils.isEmpty(businessKeys)) { approvalList = handleApprovalListResponse(this.baseMapper.selectBatchForApproval(page, request, businessKeys), ApprovalStatusEnum.IN_APPROVED); } break; //已通过,该状态维护在flowable case ApprovalStatusEnum.PASSED: businessKeys = baseApprovalService.getPassedList(request.getFormId()); - if(!CollectionUtils.isEmpty(businessKeys)){ - approvalList = handleApprovalListResponse( this.baseMapper.selectBatchForApproval(page, request, businessKeys), ApprovalStatusEnum.PASSED); + if (!CollectionUtils.isEmpty(businessKeys)) { + approvalList = handleApprovalListResponse(this.baseMapper.selectBatchForApproval(page, request, businessKeys), ApprovalStatusEnum.PASSED); } break; //未通过(包括拒绝、驳回,拒绝为直接删除实例,驳回为驳回到起点),该状态维护在flowable case ApprovalStatusEnum.FAILED: businessKeys = baseApprovalService.getFailedList(request.getFormId()); //未通过-拒绝 List rejectBusinessKey = baseApprovalService.getFailedRejectList(request.getFormId()); //未通过-驳回 - if(!CollectionUtils.isEmpty(businessKeys)){ + if (!CollectionUtils.isEmpty(businessKeys)) { approvalList = handleApprovalListResponse(this.baseMapper.selectBatchForApproval(page, request, businessKeys), ApprovalStatusEnum.FAILED); } List rejectApprovalList = new ArrayList<>(); - if(!CollectionUtils.isEmpty(rejectBusinessKey)){ - rejectApprovalList = handleApprovalListResponse( this.baseMapper.selectBatchForApproval(page, request, rejectBusinessKey), ApprovalStatusEnum.FAILED_REJECT); + if (!CollectionUtils.isEmpty(rejectBusinessKey)) { + rejectApprovalList = handleApprovalListResponse(this.baseMapper.selectBatchForApproval(page, request, rejectBusinessKey), ApprovalStatusEnum.FAILED_REJECT); } //合并未通过-拒绝和未通过-驳回 approvalList.addAll(rejectApprovalList); @@ -279,7 +285,7 @@ //已取消(直接删除实例),该状态维护在flowable case ApprovalStatusEnum.CANCELED: businessKeys = baseApprovalService.getCanceledList(request.getFormId()); - if(!CollectionUtils.isEmpty(businessKeys)){ + if (!CollectionUtils.isEmpty(businessKeys)) { approvalList = handleApprovalListResponse(this.baseMapper.selectBatchForApproval(page, request, businessKeys), ApprovalStatusEnum.CANCELED); } break; @@ -288,10 +294,10 @@ //普通用户获取自己发起的(审批中、已通过、未通过、已取消),管理员获取全部(审批中、已通过、未通过、已取消) case ApprovalStatusEnum.ALL: List AllApproveList = baseApprovalService.getAllList(request.getFormId()); - if(!CollectionUtils.isEmpty(AllApproveList)){ + if (!CollectionUtils.isEmpty(AllApproveList)) { businessKeys = AllApproveList.stream().map(AllApproveDTO::getBusinessKey).collect(Collectors.toList()); } - if(!CollectionUtils.isEmpty(businessKeys)){ + if (!CollectionUtils.isEmpty(businessKeys)) { approvalList = handleAllApprovalListResponse(this.baseMapper.selectBatchForApproval(page, request, businessKeys), AllApproveList); } break; @@ -299,9 +305,11 @@ return approvalList; } - private List handleAllApprovalListResponse(List approvalList, List allApproveList) { - Map taskMap = new HashMap<>(); - allApproveList.forEach(allApprove -> {taskMap.put(allApprove.getBusinessKey(),allApprove.getStatus());}); + private List handleAllApprovalListResponse(List approvalList, List allApproveList) { + Map taskMap = new HashMap<>(); + allApproveList.forEach(allApprove -> { + taskMap.put(allApprove.getBusinessKey(), allApprove.getStatus()); + }); //状态补全 approvalList.forEach(approval -> { approval.setApprovalStatusName(dictService.getDictNameByCode(MeterDictEnum.APPROVAL_STATUS, taskMap.get(String.valueOf(approval.getId())))); @@ -313,7 +321,7 @@ return approvalList.stream().sorted(Comparator.comparing(CertificateReportResponse::getCreateTime).reversed()).collect(Collectors.toList()); } - private List handleApprovalListResponse(List approvalList, String status){ + private List handleApprovalListResponse(List approvalList, String status) { approvalList.stream().forEach(result -> { //审批状态两种获取方式:1、在此处设置,2、在flowable中设置业务状态,暂采取1 result.setApprovalStatusName(dictService.getDictNameByCode(MeterDictEnum.APPROVAL_STATUS, status)); @@ -324,14 +332,14 @@ private void initCertificateReport(BusinessCertificateReport certificateReport) { String prefix = MonitorCodeEnum.getByCode(certificateReport.getCalibrationMajor()).getValue() - +DateUtil.format(new Date(),"YYYYMM"); + + DateUtil.format(new Date(), "YYYYMM"); Long maxNo = this.baseMapper.selectMaxCode(prefix); //生成证书编号 - String certificateReportNo =NumberGeneratorUtil.getCode( - MonitorCodeEnum.getByCode(certificateReport.getCalibrationMajor()).getValue(),maxNo); + String certificateReportNo = NumberGeneratorUtil.getCode( + MonitorCodeEnum.getByCode(certificateReport.getCalibrationMajor()).getValue(), maxNo); AuthUser authUser = ShiroKit.getUser(); certificateReport.setCreateUser(authUser.getId()); - certificateReport.setMeasurePersonId(authUser.getId()+""); + certificateReport.setMeasurePersonId(authUser.getId() + ""); certificateReport.setMeasureDeptId(authUser.getDeptId()); certificateReport.setCertificateReportCode(certificateReportNo); } diff --git a/casic-metering-api/src/main/java/com/casic/missiles/controller/business/BusinessCertificateReportController.java b/casic-metering-api/src/main/java/com/casic/missiles/controller/business/BusinessCertificateReportController.java index c440253..408b580 100644 --- a/casic-metering-api/src/main/java/com/casic/missiles/controller/business/BusinessCertificateReportController.java +++ b/casic-metering-api/src/main/java/com/casic/missiles/controller/business/BusinessCertificateReportController.java @@ -9,17 +9,13 @@ import com.casic.missiles.dto.business.certificate.CertificateReportApprovalRequest; import com.casic.missiles.dto.business.certificate.CertificateReportResponse; import com.casic.missiles.dto.flowable.ApprovalDeleteRequest; -import com.casic.missiles.dto.meter.TraceSupplierListRequest; import com.casic.missiles.enums.BusinessExceptionEnum; import com.casic.missiles.exception.BusinessException; import com.casic.missiles.model.business.BusinessCertificateReport; import com.casic.missiles.model.exception.enums.CoreExceptionEnum; -import com.casic.missiles.model.meter.MeterTraceSupplier; import com.casic.missiles.service.business.IBusinessCertificateReportService; -import com.casic.missiles.service.meter.IMeterTraceSupplierService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.util.CollectionUtils; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.*; @@ -45,28 +41,7 @@ public class BusinessCertificateReportController extends ExportController { @Resource private IBusinessCertificateReportService certificateReportService; - @Autowired - private IMeterTraceSupplierService traceSupplierService; - @ApiOperation("证书报告列表(分页)") - @PostMapping("/listPage") - @ResponseBody - public ReturnDTO> supplierListPage(@RequestBody @Valid TraceSupplierListRequest request, BindingResult bindingResult) { - if (bindingResult.hasErrors()) { - throw new BusinessException(CoreExceptionEnum.REQUEST_NULL.getCode(), bindingResult.getFieldError().getDefaultMessage()); - } - Page page = PageFactory.defaultPage(); - return ReturnUtil.success(super.packForBT(traceSupplierService.listPage(page, request))); - } - @ApiOperation("证书报告列表") - @PostMapping("/list") - @ResponseBody - public ReturnDTO> supplierList(@RequestBody @Valid TraceSupplierListRequest request, BindingResult bindingResult) { - if (bindingResult.hasErrors()) { - throw new BusinessException(CoreExceptionEnum.REQUEST_NULL.getCode(), bindingResult.getFieldError().getDefaultMessage()); - } - return ReturnUtil.success(traceSupplierService.list(request)); - } @ApiOperation("证书报告记录导出") @PostMapping("/listExport") @@ -113,18 +88,6 @@ return certificateReportService.submitCertificateReport(request); } - @ApiOperation("证书报告更新(审批通过后还能更新??暂时保留。。)") - @PostMapping("/update") - @ResponseBody - public ReturnDTO supplierUpdate(@RequestBody @Valid MeterTraceSupplier traceSupplier, BindingResult bindingResult) { - Assert.isFalse(Objects.isNull(traceSupplier.getId()), () -> { - throw new BusinessException(BusinessExceptionEnum.ID_NULL); - }); - Assert.isFalse(bindingResult.hasErrors(), () -> { - throw new BusinessException(CoreExceptionEnum.REQUEST_NULL.getCode(), bindingResult.getFieldError().getDefaultMessage()); - }); - return traceSupplierService.updateTraceSupplier(traceSupplier); - } @ApiOperation("证书报告批量删除") @PostMapping("/batchDelete") diff --git a/casic-metering-api/src/main/java/com/casic/missiles/controller/system/PoiController.java b/casic-metering-api/src/main/java/com/casic/missiles/controller/system/PoiController.java index 021eaa8..9848e68 100644 --- a/casic-metering-api/src/main/java/com/casic/missiles/controller/system/PoiController.java +++ b/casic-metering-api/src/main/java/com/casic/missiles/controller/system/PoiController.java @@ -3,12 +3,14 @@ import cn.afterturn.easypoi.entity.ImageEntity; import com.casic.missiles.utils.PdfUtil; +import com.casic.missiles.utils.StampUtils; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.stereotype.Controller; import org.springframework.util.Assert; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpServletResponse; import java.io.*; @@ -23,7 +25,51 @@ private String filepath="C:\\upload"; @ApiOperation("word转pdf") + @PostMapping(value = "/convertWordToPdf1") + @ResponseBody + public void convertWordToPdf1() throws Exception { + File uploadFile = new File(filepath); + String wordDir = ""; + if (!uploadFile.exists()) { + uploadFile.mkdirs(); + } + if (!filepath.endsWith("/")) { + wordDir = filepath + File.separator + "word"; + } + File tf = new File(wordDir + File.separator + "tem.docx"); + File tf_pic = new File(wordDir + File.separator + "logo.jpg"); + String pic_url = tf_pic.getCanonicalPath(); + Calendar now = Calendar.getInstance(); + Map params = new HashMap<>(); + List> dataList=new ArrayList<>(); + for (int i = 0; i < 5; i++) { + Map param = new HashMap<>(); + param.put("name", "彭于晏"+i); + param.put("sex", "男"+i); + param.put("address", "中国"+i); + ImageEntity image = new ImageEntity(); + image.setHeight(100); + image.setWidth(100); + image.setUrl(pic_url); + image.setData(PdfUtil.getImageBase64(pic_url)); + param.put("image", image); + dataList.add(param); + } + + params.put("dataList",dataList); + params.put("y", now.get(Calendar.YEAR)); + params.put("m", (now.get(Calendar.MONTH) + 1)); + params.put("d", now.get(Calendar.DAY_OF_MONTH)); + + String fileName = "wordExport.docx"; + String word = StampUtils.exportWord(tf.getPath(), wordDir, fileName, params); + System.out.println("****新模板"+word); + + } + + @ApiOperation("word转pdf") @PostMapping(value = "/convertWordToPdf") + @ResponseBody public void convertWordToPdf(HttpServletResponse response) throws Exception { File uploadFile = new File(filepath); String wordDir = ""; @@ -117,4 +163,5 @@ } } } + } diff --git a/casic-metering-common/pom.xml b/casic-metering-common/pom.xml index bb00ab9..e028713 100644 --- a/casic-metering-common/pom.xml +++ b/casic-metering-common/pom.xml @@ -11,6 +11,7 @@ casic-metering-common + @@ -171,6 +172,14 @@ 4.1.2 + + + + e-iceblue + spire.office.free + 5.3.1 + + com.google.zxing diff --git a/casic-metering-common/src/main/java/com/casic/missiles/utils/CustomXWPFDocumentUtil.java b/casic-metering-common/src/main/java/com/casic/missiles/utils/CustomXWPFDocumentUtil.java deleted file mode 100644 index 9e7ed3f..0000000 --- a/casic-metering-common/src/main/java/com/casic/missiles/utils/CustomXWPFDocumentUtil.java +++ /dev/null @@ -1,309 +0,0 @@ -package com.casic.missiles.utils; - -import java.io.*; -import java.util.*; -import java.util.Map.Entry; - -import cn.afterturn.easypoi.entity.ImageEntity; -import org.apache.commons.lang3.StringUtils; -import org.apache.poi.ooxml.POIXMLDocument; -import org.apache.poi.openxml4j.exceptions.InvalidFormatException; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.util.Units; -import org.apache.poi.xwpf.usermodel.*; -import org.apache.xmlbeans.XmlException; -import org.apache.xmlbeans.XmlToken; -import org.openxmlformats.schemas.drawingml.x2006.main.CTGraphicalObject; -import org.openxmlformats.schemas.drawingml.x2006.main.CTNonVisualDrawingProps; -import org.openxmlformats.schemas.drawingml.x2006.main.CTPositiveSize2D; -import org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.CTAnchor; -import org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.CTInline; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTDrawing; - -public class CustomXWPFDocumentUtil extends XWPFDocument { - - public CustomXWPFDocumentUtil(InputStream in) throws IOException { - super(in); - } - - public CustomXWPFDocumentUtil() { - super(); - } - - public CustomXWPFDocumentUtil(OPCPackage pkg) throws IOException { - super(pkg); - } - - /** - * 根据指定的参数值、模板,生成 word 文档 - * - * @param param 需要替换的变量 - * @param template 模板 - */ - public static XWPFDocument generateWord(Map param, String template) { - XWPFDocument doc = null; - try { - OPCPackage pack = POIXMLDocument.openPackage(template); - doc = new CustomXWPFDocumentUtil(pack); - if (param != null && param.size() > 0) { - - //处理段落 - List paragraphList = doc.getParagraphs(); - processParagraphs(paragraphList, param, doc); - - //处理表格 - Iterator it = doc.getTablesIterator(); - while (it.hasNext()) { - XWPFTable table = it.next(); - List rows = table.getRows(); - for (XWPFTableRow row : rows) { - List cells = row.getTableCells(); - for (XWPFTableCell cell : cells) { - List paragraphListTable = cell.getParagraphs(); - processParagraphs(paragraphListTable, param, doc); - } - } - } - } - } catch (IOException e) { - e.printStackTrace(); - } catch (Exception e) { - e.printStackTrace(); - } - return doc; - } - - /** - * 处理段落 - * - * @param paragraphList - * @param - * @throws FileNotFoundException - * @throws InvalidFormatException - */ - public static void processParagraphs(List paragraphList, Map param, XWPFDocument doc) throws InvalidFormatException, FileNotFoundException { - if (paragraphList != null && paragraphList.size() > 0) { - for (XWPFParagraph paragraph : paragraphList) { - List runs = paragraph.getRuns(); - for (XWPFRun run : runs) { - String text = run.getText(0); - //System.out.println("text=="+text); - if (text != null) { - boolean isSetText = false; - for (Entry entry : param.entrySet()) { - String key = entry.getKey(); - if (text.indexOf(key) != -1) { - isSetText = true; - Object value = entry.getValue(); - if (value instanceof String) {//文本替换 - //System.out.println("key=="+key); - text = text.replace(key, value.toString()); - } else if (value instanceof Map) { //图片替换 - text = text.replace(text, ""); - Map pic = (Map) value; - int width = Integer.parseInt(pic.get("width").toString()); - int height = Integer.parseInt(pic.get("height").toString()); - int picType = getPictureType(pic.get("type").toString()); - String picPath = (String) pic.get("picPath"); - CTInline inline = run.getCTR().addNewDrawing().addNewInline(); - insertPicture(doc, picPath, inline, width, height); - CTDrawing drawing = run.getCTR().getDrawingArray(0); - CTGraphicalObject graphicalobject = drawing.getInlineArray(0).getGraphic(); - //拿到新插入的图片替换添加CTAnchor 设置浮动属性 删除inline属性 - CTAnchor anchor = getAnchorWithGraphic(graphicalobject, "11", - Units.toEMU(width), Units.toEMU(height),//图片大小 - Units.toEMU(0), Units.toEMU(0));//相对当前段落位置的偏移位置,左右偏移:负数向左,正数向右,上下偏移:负数向上,正数向下 - drawing.setAnchorArray(new CTAnchor[]{anchor});//添加浮动属性 - drawing.removeInline(0);//删除行内属性 - } - } - } - if (isSetText) { - run.setText(text, 0); - } - } - } - } - } - } - - /** - * 根据图片类型,取得对应的图片类型代码 - * - * @param picType - * @return int - */ - private static int getPictureType(String picType) { - int res = CustomXWPFDocumentUtil.PICTURE_TYPE_PICT; - if (picType != null) { - if (picType.equalsIgnoreCase("png")) { - res = CustomXWPFDocumentUtil.PICTURE_TYPE_PNG; - } else if (picType.equalsIgnoreCase("dib")) { - res = CustomXWPFDocumentUtil.PICTURE_TYPE_DIB; - } else if (picType.equalsIgnoreCase("emf")) { - res = CustomXWPFDocumentUtil.PICTURE_TYPE_EMF; - } else if (picType.equalsIgnoreCase("jpg") || picType.equalsIgnoreCase("jpeg")) { - res = CustomXWPFDocumentUtil.PICTURE_TYPE_JPEG; - } else if (picType.equalsIgnoreCase("wmf")) { - res = CustomXWPFDocumentUtil.PICTURE_TYPE_WMF; - } - } - return res; - } - - /** - * insert Picture - * - * @param document - * @param filePath - * @param inline - * @param width - * @param height - * @throws InvalidFormatException - * @throws FileNotFoundException - */ - private static void insertPicture(XWPFDocument document, String filePath, - CTInline inline, int width, - int height) throws InvalidFormatException, - FileNotFoundException { - document.addPictureData(new FileInputStream(filePath), XWPFDocument.PICTURE_TYPE_PNG); - int id = document.getAllPictures().size() - 1; - final int EMU = 9525; - width *= EMU; - height *= EMU; - String blipId = - document.getAllPictures().get(id).getRelationId(document); - String picXml = getPicXml(blipId, width, height); - XmlToken xmlToken = null; - try { - xmlToken = XmlToken.Factory.parse(picXml); - } catch (XmlException xe) { - xe.printStackTrace(); - } - inline.set(xmlToken); - inline.setDistT(0); - inline.setDistB(0); - inline.setDistL(0); - inline.setDistR(0); - CTPositiveSize2D extent = inline.addNewExtent(); - extent.setCx(width); - extent.setCy(height); - CTNonVisualDrawingProps docPr = inline.addNewDocPr(); - docPr.setId(id); - docPr.setName("IMG_" + id); - docPr.setDescr("IMG_" + id); - } - - /** - * get the xml of the picture - * - * @param blipId - * @param width - * @param height - * @return - */ - private static String getPicXml(String blipId, int width, int height) { - String picXml = - "" + "" + - " " + - " " + - " " + " " + " " + - " " + " " + - " " + - " " + " " + - " " + " " + - " " + " " + - " " + - " " + " " + - " " + - " " + " " + - " " + " " + - " " + ""; - return picXml; - } - - /** - * @param ctGraphicalObject 图片数据 - * @param deskFileName 图片描述 - * @param width 宽 - * @param height 高 - * @param leftOffset 水平偏移:负数向左,正数向右 - * @param topOffset 垂直偏移:负数向上,正数向下 - * @return CTAnchor - * @throws Exception - */ - public static CTAnchor getAnchorWithGraphic(CTGraphicalObject ctGraphicalObject, - String deskFileName, int width, int height, - int leftOffset, int topOffset) { - //浮在文字上的设置主要是anchor标签下的behindDoc属性设为0,同时添加一个的空标签。 - if (StringUtils.isBlank(deskFileName)) { - deskFileName = new Random().nextInt(999) + "";//描述不能为空,赋值一个随机数 - } - String anchorXML = - "" - + "" - + "" - + "" + leftOffset + "" - + "" - + "" - + "" + topOffset + "" + - "" - + "" - + "" - + "" - + "" - + ""; - CTDrawing drawing = null; - try { - drawing = CTDrawing.Factory.parse(anchorXML); - } catch (XmlException e) { - e.printStackTrace(); - } - CTAnchor anchor = drawing.getAnchorArray(0); - anchor.setGraphic(ctGraphicalObject); - return anchor; - } - public static void main(String[] args) throws IOException{ - Map params = new HashMap<>(); - List> dataList=new ArrayList<>(); - for (int i = 0; i < 5; i++) { - Map param = new HashMap<>(); - param.put("name", "彭于晏"+i); - param.put("sex", "男"+i); - param.put("address", "中国"+i); - ImageEntity image = new ImageEntity(); - image.setHeight(100); - image.setWidth(100); - image.setUrl("C:\\upload\\word\\"); - image.setData(PdfUtil.getImageBase64("C:\\upload\\word\\logo.jpg")); - param.put("image", image); - dataList.add(param); - } - Calendar now = Calendar.getInstance(); - params.put("dataList",dataList); - params.put("y", now.get(Calendar.YEAR)+""); - params.put("m", (now.get(Calendar.MONTH) + 1)+""); - params.put("d", now.get(Calendar.DAY_OF_MONTH)+""); - String template="C:\\upload\\word\\tem.docx"; - ByteArrayOutputStream baos = null; - try { - XWPFDocument document = generateWord(params, template); - baos = new ByteArrayOutputStream(); - document.write(baos);//临时存储流到内存 - baos.flush(); - } catch (Exception e) { - e.printStackTrace(); - }finally{ - if(baos != null){ - baos.close(); - } - } - - - } - -} diff --git a/casic-metering-common/src/main/java/com/casic/missiles/utils/PdfUtil.java b/casic-metering-common/src/main/java/com/casic/missiles/utils/PdfUtil.java index 3d80a8e..3e4f58b 100644 --- a/casic-metering-common/src/main/java/com/casic/missiles/utils/PdfUtil.java +++ b/casic-metering-common/src/main/java/com/casic/missiles/utils/PdfUtil.java @@ -23,12 +23,12 @@ public class PdfUtil { /** - * 生成word 只支持docx + * 按照模板 填充数据生成word 只支持docx * * @param templatePath 模板文件路径 - * @param temDir 生成文件的目录 - * @param fileName 生成文件名 - * @param params 参数 + * @param temDir 生成文件的目录 + * @param fileName 生成文件名 + * @param params 参数 */ public static String exportWord(String templatePath, String temDir, String fileName, Map params) { Assert.notNull(templatePath, "模板路径不能为空"); @@ -39,8 +39,9 @@ temDir = temDir + File.separator; } File dir = new File(temDir); - if (!dir.exists()) { - dir.mkdirs(); + if (!dir.getParentFile().exists()) { + // 新建文件夹 + dir.getParentFile().mkdirs(); } String tmpPath = ""; try { @@ -51,13 +52,13 @@ fos.flush(); fos.close(); } catch (Exception e) { - //e.printStackTrace(); + e.printStackTrace(); } return tmpPath; } - public static String convertDocx2Pdf(String wordPath,String pdfPath) { + public static String convertDocx2Pdf(String wordPath, String pdfPath) { OutputStream os = null; InputStream is = null; try { diff --git a/casic-metering-common/src/main/java/com/casic/missiles/utils/PictureUtil.java b/casic-metering-common/src/main/java/com/casic/missiles/utils/PictureUtil.java deleted file mode 100644 index 4baa893..0000000 --- a/casic-metering-common/src/main/java/com/casic/missiles/utils/PictureUtil.java +++ /dev/null @@ -1,184 +0,0 @@ -//package com.casic.missiles.utils; -// -//import cn.hutool.core.codec.Base64; -//import com.alibaba.fastjson.JSONObject; -//import com.google.common.collect.Lists; -//import org.apache.poi.xwpf.usermodel.*; -//import org.apache.xmlbeans.XmlException; -//import org.openxmlformats.schemas.drawingml.x2006.main.CTGraphicalObject; -//import org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.CTAnchor; -//import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTDrawing; -// -//import java.io.*; -//import java.util.List; -//import java.util.Map; -//import java.util.Set; -// -//public class PictureUtil { -// public void create(String filePath, JSONObject jsonObject) { -// try { -// FileInputStream template = new FileInputStream(new File(filePath)); -// //获取docx解析对象 -// XWPFDocument document = new XWPFDocument(template); -// List tableList = Lists.newArrayList(); -// -// //解析替换表格对象 -// List tables = document.getTables(); -// for (int i = 0; i < tables.size(); i++) { -// //只处理行数大于等于2的表格,且不循环表头 -// XWPFTable table = tables.get(i); -// if (table.getRows().size() > 1) { -// //判断表格是需要替换还是需要插入,判断逻辑有$为替换,表格无$为插入 -// if (WordUtil.checkText(table.getText())) { -// List rows = table.getRows(); -// //遍历表格,并替换模板 -// eachTable(rows, jsonObject); -// } -// } -// } -// -// // workBook写入输出流 -// ByteArrayOutputStream baos = new ByteArrayOutputStream(); -// document.write(baos); -// baos.flush(); -// } catch (Exception e) { -// e.printStackTrace(); -// } -// } -// /** -// * 遍历表格 -// * -// * @param rows 表格行对象 -// * @param textMap 需要替换的信息集合 -// */ -// public static void eachTable(List rows, JSONObject textMap) { -// for (XWPFTableRow row : rows) { -// List cells = row.getTableCells(); -// for (XWPFTableCell cell : cells) { -// //判断单元格是否需要替换 -// if (checkText(cell.getText())) { -// List paragraphs = cell.getParagraphs(); -// for (XWPFParagraph paragraph : paragraphs) { -// List runs = paragraph.getRuns(); -// for (XWPFRun run : runs) { -//// run.setText(changeValue(run.toString(), textMap), 0); -// //新增制证照片单独处理 -// if (run.toString().indexOf("${jpeg}") != -1 && textMap.containsKey("jpeg")){ -// addPic(run,textMap, 1188000, 1728000,0, 0); -// break; -// } -// String value = changeValue(run.toString(), textMap); -// setWrap(value, run); -// } -// } -// } -// } -// } -// } -// -// /** -// * 匹配传入信息集合与模板 -// * -// * @param value 模板需要替换的区域 -// * @param textMap 传入信息集合 -// * @return 模板需要替换区域信息集合对应值 -// */ -// public static String changeValue(String value, JSONObject textMap) { -// -// boolean flag = false; -// Set> textSets = textMap.entrySet(); -// for (Map.Entry textSet : textSets) { -// //匹配模板与替换值 格式${key} -// String key = "${" + textSet.getKey() + "}"; -// if (value.indexOf(key) != -1) { -// value = textSet.getValue() == null ? "" : ("" + textSet.getValue()); -// flag = true; -// break; -// } -// } -// //模板未匹配到区域替换为空 -// if (checkText(value)) { -// value = ""; -// } -// return value; -// } -// public static void setWrap(String value, XWPFRun run) { -// if ( value.indexOf("\n") > 0) { -// //设置换行 -// String[] text = value.split("\n"); -// for (int f = 0; f < text.length; f++) { -// if (f == 0) { -// run.setText(text[f].trim(),0); -// } else { -//// run.addCarriageReturn();//硬回车 -// // 换行 -// run.addBreak(); -// run.setText(text[f]); -// } -// } -// } else { -// run.setText((String) value,0); -// } -// } -// -// /** -// * @param ctGraphicalObject 图片数据 -// * @param deskFileName 图片描述 -// * @param width 宽 -// * @param height 高 -// * @param leftOffset 水平偏移 left -// * @param topOffset 垂直偏移 top -// * @param behind 文字上方,文字下方 -// * @return -// * @throws Exception -// */ -// public static CTAnchor getAnchorWithGraphic(CTGraphicalObject ctGraphicalObject, String deskFileName, int width, int height, int leftOffset, int topOffset, boolean behind) { -// String anchorXML ="" -// +"" -// +" " -// +" " -// +" "+ leftOffset + "" -// +" " -// +" " -// +" "+ topOffset +"" -// +" " -// +" " -// +" " -// +" " -// +" " -// +""; -// try { -// CTDrawing drawing = CTDrawing.Factory.parse(anchorXML); -// CTAnchor anchor = drawing.getAnchorArray(0); -// anchor.setGraphic(ctGraphicalObject); -// return anchor; -// } catch (XmlException e) { -// e.printStackTrace(); -// return null; -// } -// } -// -// /** -// * 新增制证照片单独处理 -// * @param run -// * @param textMap -// */ -// public static void addPic(XWPFRun run, JSONObject textMap, int width, int height, int leftOffset, int topOffset){ -// String runText = run.toString().trim(); -// byte[] zjzp = Base64.decode(textMap.getString("jpeg")); -// try(ByteArrayInputStream byteInputStream = new ByteArrayInputStream(zjzp)) { -// //1、添加图片 -// run.addPicture(byteInputStream,XWPFDocument.PICTURE_TYPE_JPEG,"照片", width, height); -// //2、获取图片 -// CTDrawing cTDrawing = run.getCTR().getDrawingArray(0); -// CTGraphicalObject cTGraphicalObject = cTDrawing.getInlineArray(0).getGraphic(); -// //3、设置属性 -// CTAnchor ctAnchor = getAnchorWithGraphic(cTGraphicalObject,"照片", width, height,leftOffset, topOffset,false); -// cTDrawing.setAnchorArray(new CTAnchor[]{ctAnchor}); -// cTDrawing.removeInline(0); -// run.setText(runText.replace("${jpeg}",""), 0); -// }catch (Exception e){ -// e.printStackTrace(); -// } -// } -//} diff --git a/casic-metering-common/src/main/java/com/casic/missiles/utils/StampUtils.java b/casic-metering-common/src/main/java/com/casic/missiles/utils/StampUtils.java new file mode 100644 index 0000000..fb6d4cf --- /dev/null +++ b/casic-metering-common/src/main/java/com/casic/missiles/utils/StampUtils.java @@ -0,0 +1,482 @@ +package com.casic.missiles.utils; + + +import cn.afterturn.easypoi.word.WordExportUtil; +import cn.hutool.core.lang.Assert; +import com.baomidou.mybatisplus.core.toolkit.ObjectUtils; +import com.spire.doc.*; +import com.spire.doc.documents.*; +import com.spire.doc.fields.DocPicture; +import com.spire.doc.fields.TextRange; +import org.apache.commons.lang3.StringUtils; +import org.apache.poi.xwpf.usermodel.XWPFDocument; + +import javax.imageio.ImageIO; +import java.awt.*; +import java.awt.image.BufferedImage; +import java.io.*; +import java.util.Map; + +/** + * @Author:zt + * @Create:2023/3/7/9:30 + * @Description:TODO Word文件操作工具类 + * @Version:1.0 + */ + +public class StampUtils { + + //关键字索引 (-1) + private final static Integer keyWordIndex = -1; + // 电子印章水平位置 + private final static float horizontal = 300f; + // 电子印章垂直位置 + private final static float vertical = -55f; + // 电子印章宽度 + private final static float stampWidth = 120; + // 电子印章高度 + private final static float stampHeight = 120; + //照片透明度设置 + private final static int alpha = 150; + + + /** + * 1、自定义位置添加电子印章 + * 2、替换书签名位置文本内容 bookmarkName传参为null,则不进行书签替换操作 + * + * @param wordOldUrl word文件路径 + * @param wordNewUrl 新word文件路径 + * @param stampImgUrl 电子印章图片路径 + * @param horizontal 电子印章水平位置 (当前文件推荐260f) + * @param vertical 电子印章垂直位置 (当前推荐455f) + * @param stampWidth 电子印章宽度(推荐120) + * @param stampHeight 电子印章高度(推荐120) + * @param bookmarkName 书签名,通过名称寻找书签文本所在位置 + * @param newBookmarkText 替换的文本新内容 + */ + public void addStamp(String wordOldUrl, String wordNewUrl, String stampImgUrl, + Float horizontal, Float vertical, Float stampWidth, + Float stampHeight, String bookmarkName, String newBookmarkText) { + // 加载文档 + Document document = new Document(); + document.loadFromFile(wordOldUrl); + +// 获取指定段落 + Section section = document.getSections().get(0); +// 获取段落总数 + int count = section.getParagraphs().getCount(); +// log.info("获取文档内容段落总数{}",count); + Paragraph paragraph = section.getParagraphs().get(0); + + // 判断是否需要替换书签位置文本内容 + if (StringUtils.isNotEmpty(bookmarkName)) { + replaceBookmarkContent(document, bookmarkName, newBookmarkText); + } + +// 添加电子印章 + DocPicture docPicture = paragraph.appendPicture(stampImgUrl); + +// 指定电子章位置 +// 水平位置 + docPicture.setHorizontalPosition(horizontal); +// 垂直位置 + docPicture.setVerticalPosition(vertical); + +// 设置电子章大小 + docPicture.setWidth(stampWidth); + docPicture.setHeight(stampHeight); + +// 设置图片位于文字顶层 + docPicture.setTextWrappingStyle(TextWrappingStyle.In_Front_Of_Text); + + // 保存添加电子章的Word文档 + document.saveToFile(wordNewUrl); + document.dispose(); +// log.info("文档添加电子印章结束,新WORD文档地址:{}",wordNewUrl); + + } + + /** + * 1、根据关键词位置添加电子印章 + * 2、替换书签名位置文本内容 bookmarkName传参为null,则不进行书签替换操作 + * + * @param wordOldUrl word文件路径 + * @param wordNewUrl 新word文件路径 + * @param stampImgUrl 电子印章图片路径 + * @param keyWord 关键字 (自定义) + * @param keyWordIndex 关键字索引 (-1) + * @param horizontal 电子印章水平位置 (260f) + * @param vertical 电子印章垂直位置 (-55f) + * @param stampWidth 电子印章宽度 (推荐120) + * @param stampHeight 电子印章高度(推荐120) + */ + public static void addKeyWordStamp(String wordOldUrl, String wordNewUrl, String stampImgUrl, String stampImgUrl1, + String keyWord, Integer keyWordIndex, Float horizontal, + Float vertical, Float stampWidth, Float stampHeight) { + // 加载文档 + Document document = new Document(); + document.loadFromFile(wordOldUrl); + //获取关键字位置 + TextSelection[] textSelections = document.findAllString(keyWord, false, false); + //加签章照片 + if (ObjectUtils.isNotEmpty(textSelections) && StringUtils.isNotEmpty(stampImgUrl)) { + Paragraph paragraph = textSelections[keyWordIndex > -1 ? 0 : textSelections.length - 1].getAsOneRange().getOwnerParagraph(); + //添加公司印章 + DocPicture docPicture = paragraph.appendPicture(stampImgUrl); + + //设置图片位于文字顶层 + docPicture.setTextWrappingStyle(TextWrappingStyle.In_Front_Of_Text); + + //指定电子章位置 + //水平位置 + docPicture.setHorizontalPosition(horizontal); + //垂直位置 + docPicture.setVerticalPosition(vertical); + //设置电子章大小 + docPicture.setWidth(stampWidth); + docPicture.setHeight(stampHeight); + } + + //加签名照片 + if (ObjectUtils.isNotEmpty(textSelections) && StringUtils.isNotEmpty(stampImgUrl1)) { + Paragraph paragraph = textSelections[keyWordIndex > -1 ? 0 : textSelections.length - 1].getAsOneRange().getOwnerParagraph(); + // 添加电子印章 + DocPicture docPicture = paragraph.appendPicture(stampImgUrl1); + //设置图片位于文字顶层 + docPicture.setTextWrappingStyle(TextWrappingStyle.In_Front_Of_Text); + + //指定电子章位置 + //水平位置 + docPicture.setHorizontalPosition(horizontal); + //垂直位置 + docPicture.setVerticalPosition(vertical); + //设置电子章大小 + docPicture.setWidth(stampWidth); + docPicture.setHeight(stampHeight); + } + + //保存添加电子章的Word文档 + document.saveToFile(wordNewUrl); + document.dispose(); + } + + /** + * 替换书签名位置文本内容 + * + * @param document word文档对象 + * @param bookmarkName 书签名 + * @param newBookmarkText 新文本内容 + */ + public void replaceBookmarkContent(Document document, String bookmarkName, String newBookmarkText) { + //定位到指定书签位置 + BookmarksNavigator bookmarksNavigator = new BookmarksNavigator(document); + bookmarksNavigator.moveToBookmark(bookmarkName); + //用文本内容替换原有书签位置的文本,新替换的内容与原文格式一致 + bookmarksNavigator.replaceBookmarkContent(newBookmarkText, true); + } + + /** + * 替换书签名位置文本内容为图片 + * + * @param document word文档对象 + * @param bookmarkName 书签名 + * @param newImgUrl 图片地址 + */ + public void replaceBookmarkContentToImg(Document document, String bookmarkName, String newImgUrl) { + //定位到指定书签位置 + BookmarksNavigator bookmarksNavigator = new BookmarksNavigator(document); + bookmarksNavigator.moveToBookmark(bookmarkName); + //添加图片,替换原有书签内容 + Paragraph para = new Paragraph(document); + para.appendPicture(newImgUrl); + TextBodyPart bodyPart = new TextBodyPart(document); + bodyPart.getBodyItems().add(para); + bookmarksNavigator.replaceBookmarkContent(bodyPart); + } + + /** + * 替换书签名位置文本内容为表格 + * + * @param document word文档对象 + * @param bookmarkName 书签名 + */ + public void replaceBookmarkContentToTable(Document document, String bookmarkName) { + //声明数组内容 + String[][] data = + { + new String[]{"分类", "等级", "编号"}, + new String[]{"A", "一级", "01A"}, + new String[]{"B", "二级", "02B"}, + new String[]{"C", "三级", "03C"}, + }; + + //创建表格 + Table table = new Table(document, true); + table.resetCells(4, 3); + for (int i = 0; i < data.length; i++) { + TableRow dataRow = table.getRows().get(i); + for (int j = 0; j < data[i].length; j++) { + TextRange range = dataRow.getCells().get(j).addParagraph().appendText(data[i][j]); + range.getOwnerParagraph().getFormat().setHorizontalAlignment(HorizontalAlignment.Center); + range.getCharacterFormat().setFontName("楷体"); + dataRow.getRowFormat().setHorizontalAlignment(RowAlignment.Center); + dataRow.getCells().get(j).getCellFormat().setVerticalAlignment(VerticalAlignment.Middle); + } + } + + //创建TextBodyPart对象 + TextBodyPart bodyPart = new TextBodyPart(document); + bodyPart.getBodyItems().add(table); + + //定位到指定书签位置 + BookmarksNavigator bookmarkNavigator = new BookmarksNavigator(document); + bookmarkNavigator.moveToBookmark(bookmarkName); + + //使用表格替换原书签的内容 + bookmarkNavigator.replaceBookmarkContent(bodyPart); + } + + /** + * 文件转流 + * + * @param wordNewUrl + * @return + */ + public byte[] getBytesByFile(String wordNewUrl) { + try { +// byte[] bytes = Files.readAllBytes(Paths.get(wordNewUrl)); + File file = new File(wordNewUrl); + FileInputStream fis = new FileInputStream(file); + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + byte[] b = new byte[1024]; + int len = -1; + while ((len = fis.read(b)) != -1) { + bos.write(b, 0, len); + } + fis.close(); + bos.close(); + byte[] bytes = bos.toByteArray(); + System.out.println("successful..."); + return bytes; + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + /** + * 流转文件 + * + * @param buf 流字节数组 + * @param filePath 新文件路径 + * @param fileName 新文件名称 + */ + public void byte2File(byte[] buf, String filePath, String fileName) { + BufferedOutputStream bos = null; + FileOutputStream fos = null; + File file = null; + try { + File dir = new File(filePath); + if (!dir.exists() && dir.isDirectory()) { + dir.mkdirs(); + } + file = new File(filePath + File.separator + fileName); + fos = new FileOutputStream(file); + bos = new BufferedOutputStream(fos); + bos.write(buf); + } catch (Exception e) { + e.printStackTrace(); + } finally { + if (bos != null) { + try { + bos.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + if (fos != null) { + try { + fos.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + } + + /** + * word转PDF + * + * @param wordNewUrl word文件路径 + * @param pdfNewUrl 存储新PDF文件路径 + */ + public static void wordToPdf(String wordNewUrl, String pdfNewUrl) { +// 将新Word文档转换为PDF文件 + Document document = new Document(); + document.loadFromFile(wordNewUrl); + document.saveToFile(pdfNewUrl, FileFormat.PDF); + document.dispose(); +// log.info("文档转换结束,新PDF文档地址:{}",pdfNewUrl); + } + + + /** + * 图片透明背景转换 + * + * @param imgsrc + * @param alpha + * @return + */ + public static BufferedImage img_alpha(BufferedImage imgsrc, int alpha) { + try { + //创建一个包含透明度的图片,半透明效果必须要存储为png合适才行,存储为jpg,底色为黑色 + BufferedImage back = new BufferedImage(imgsrc.getWidth(), imgsrc.getHeight(), BufferedImage.TYPE_INT_ARGB); + int width = imgsrc.getWidth(); + int height = imgsrc.getHeight(); + for (int j = 0; j < height; j++) { + for (int i = 0; i < width; i++) { + int rgb = imgsrc.getRGB(i, j); + Color color = new Color(rgb); + Color newcolor = new Color(color.getRed(), color.getGreen(), color.getBlue(), alpha); + back.setRGB(i, j, newcolor.getRGB()); + } + } + return back; + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + //读取图片 + public static BufferedImage file2img(String imgpath) { + try { + BufferedImage bufferedImage = ImageIO.read(new File(imgpath)); + return bufferedImage; + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + //保存图片,extent为格式,"jpg"、"png"等 + public static void img2file(BufferedImage img, String extent, String newfile) { + try { + ImageIO.write(img, extent, new File(newfile)); + } catch (Exception e) { + e.printStackTrace(); + } + } + + + /** + * 按照模板 填充数据生成word 只支持docx + * + * @param templatePath 模板文件路径 + * @param temDir 生成文件的目录 + * @param fileName 生成文件名 + * @param params 参数 + */ + public static String exportWord(String templatePath, String temDir, String fileName, Map params) { + Assert.notNull(templatePath, "模板路径不能为空"); + Assert.notNull(temDir, "临时文件路径不能为空"); + Assert.notNull(fileName, "导出文件名不能为空"); + Assert.isTrue(fileName.endsWith(".docx"), "word导出请使用docx格式"); + if (!temDir.endsWith("/")) { + temDir = temDir + File.separator; + } + File dir = new File(temDir); + if (!dir.getParentFile().exists()) { + // 新建文件夹 + dir.getParentFile().mkdirs(); + } + String tmpPath = ""; + try { + XWPFDocument doc = WordExportUtil.exportWord07(templatePath, params); + tmpPath = temDir + fileName; + FileOutputStream fos = new FileOutputStream(tmpPath); + doc.write(fos); + fos.flush(); + fos.close(); + } catch (Exception e) { + e.printStackTrace(); + } + return tmpPath; + } + + /** + * 按照模板 填充数据生成word 只支持docx + * + * @param templatePath 模板文件路径 + * @param temDir 生成文件的目录 + * @param fileName 生成文件名 + * @param params 填充参数 + */ + public static void generateReport(String templatePath, String temDir, + String fileName, Map params, + String stampImgUrl, String stampImgUrl1, + String wordNewUrl, String keyWord, + Integer keyWordIndex, Float horizontal, + Float vertical, Float stampWidth, + Float stampHeight, String pdfNewUrl) { + //1、按照模板填充数据,并导出word + String wordOldUrl = exportWord(templatePath, temDir, fileName, params); + //2、照片背景透明设置 + //2.1签章背景透明设置 + BufferedImage bi = file2img(stampImgUrl); + BufferedImage bii = img_alpha(bi, alpha); + String newPngPath = stampImgUrl.substring(0, stampImgUrl.length() - 4) + "1.png"; + img2file(bii, "PNG", newPngPath); + //2.2签名背景透明设置 + BufferedImage b = file2img(stampImgUrl1); + BufferedImage b0 = img_alpha(b, alpha); + String newPngPath1 = stampImgUrl.substring(0, stampImgUrl1.length() - 4) + "1.png"; + img2file(b0, "PNG", newPngPath1); + + //3、添加签章和签名 + addKeyWordStamp(wordOldUrl, wordNewUrl, newPngPath, newPngPath1, keyWord, keyWordIndex, + horizontal, vertical, stampWidth, stampHeight); + // 4、将新word转化为pdf文件 + wordToPdf(wordNewUrl, pdfNewUrl); + } + + + public static void main(String[] args) { + + //文件与BufferedImage间的转换 + //读取图片 + BufferedImage bi = file2img("C:\\upload\\word\\sign.png"); + BufferedImage bii = img_alpha(bi, alpha); + //生成透明背景图片 + img2file(bii, "PNG", "C:\\upload\\word\\sign1.png"); + + //文件与BufferedImage间的转换 + //读取图片 + BufferedImage b = file2img("C:\\upload\\word\\name.png"); + BufferedImage b0 = img_alpha(b, alpha); + //生成透明背景图片 + img2file(b0, "PNG", "C:\\upload\\word\\name1.png"); + + // 目标文件地址 + String wordOldUrl = "C:\\upload\\word\\wordExport.docx"; + // 添加电子印章后文件存放地址 + String wordNewUrl = "C:\\upload\\word\\tem2.docx"; + //WORD转PDF存放位置 + String pdfNewUrl = "C:\\upload\\word\\tem2.pdf"; + //电子印章图片地址 + String stampImgUrl = "C:\\upload\\word\\sign1.png"; + //电子签名图片地址 + String stampImgUrl1 = "C:\\upload\\word\\name1.png"; + // word文档内容关键字 + String keyWord = "盖章"; + StampUtils addStampUtils = new StampUtils(); + //获取关键字位置并加盖印章并替换书签名位置文本内容 + addStampUtils.addKeyWordStamp(wordOldUrl, wordNewUrl, + stampImgUrl, stampImgUrl1, + keyWord, keyWordIndex, + horizontal, vertical, + stampWidth, stampHeight); + // 将新word转化为pdf文件 + addStampUtils.wordToPdf(wordNewUrl, pdfNewUrl); + } +} \ No newline at end of file diff --git a/casic-metering-model/src/main/java/com/casic/missiles/dto/business/certificate/CertificateReportResponse.java b/casic-metering-model/src/main/java/com/casic/missiles/dto/business/certificate/CertificateReportResponse.java index b43617c..4581acf 100644 --- a/casic-metering-model/src/main/java/com/casic/missiles/dto/business/certificate/CertificateReportResponse.java +++ b/casic-metering-model/src/main/java/com/casic/missiles/dto/business/certificate/CertificateReportResponse.java @@ -1,6 +1,7 @@ package com.casic.missiles.dto.business.certificate; import com.alibaba.excel.annotation.ExcelIgnoreUnannotated; +import com.alibaba.excel.annotation.ExcelProperty; import com.alibaba.excel.annotation.write.style.ColumnWidth; import com.alibaba.excel.annotation.write.style.ContentRowHeight; import com.alibaba.excel.annotation.write.style.ContentStyle; @@ -28,73 +29,56 @@ private Long id; @ApiModelProperty(value = "证书报告编号", dataType = "String") + @ExcelProperty(value = "证书号", order = 0) private String certificateReportCode; @ApiModelProperty(value = "证书报告名称", dataType = "String") + @ExcelProperty(value = "证书名称", order = 1) private String certificateReportName; @ApiModelProperty(value = "样品编号", dataType = "String") + @ExcelProperty(value = "样品编号", order = 2) private String sampleNo; + @ApiModelProperty(value = "样品名称", dataType = "String") + @ExcelProperty(value = "样品名称", order = 3) private String sampleName; + @ApiModelProperty(value = "型号", dataType = "String") + @ExcelProperty(value = "型号", order = 4) private String sampleModel; + @ApiModelProperty(value = "出厂编号", dataType = "String") + @ExcelProperty(value = "出厂编号", order = 5) private String manufacturingNo; + @ApiModelProperty(value = "委托书编号", dataType = "String") + @ExcelProperty(value = "委托书编号", order = 6) private String orderCode; @ApiModelProperty(value = "检校专业", dataType = "String") @DictCodeField(message = "检校专业不合法", cacheName = MeterDictCode.CALIBRATION_MAJOR) private String calibrationMajor; -// @ApiModelProperty(value = "出具日期", dataType = "String") -// private String issuanceDate; -// -// -// @ApiModelProperty(value = "证书有效期", dataType = "String") -// private String expirationDate; -// -// @ApiModelProperty(value = "检定结果", dataType = "String") -// private String measureResult; -// -// -// @ApiModelProperty(value = "原始记录id", dataType = "Long") -// private Long originalRecordId; -// -// -// @ApiModelProperty(value = "可打印状态", dataType = "String") -// private String printStatus; -// -// -// @ApiModelProperty(value = "打印次数", dataType = "Integer") -// private Integer printNum; - - - @ApiModelProperty(value = "检定人员", dataType = "String") + @ApiModelProperty(value = "检定人员id", dataType = "String") private String measurePersonId; @ApiModelProperty(value = "检定人员名称", dataType = "String") + @ExcelProperty(value = "检定人员", order = 8) private String measurePersonName; @ApiModelProperty(value = "审批状态", dataType = "String") @DictCodeField(message = "审批状态不合法", cacheName = MeterDictCode.APPROVAL_STATUS) private String approvalStatus; -// @ApiModelProperty(value = "备注", dataType = "String") -// private String remark; -// -// private Long createUser; -// @ApiModelProperty(value = "创建时间", dataType = "String") + @ExcelProperty(value = "创建时间", order = 10) private String createTime; -// @ApiModelProperty(value = "检校专业名称", dataType = "String") -// private String calibrationMajorName; - @ApiModelProperty(value = "审批状态名称", dataType = "String") + @ExcelProperty(value = "审批状态", order = 9) private String approvalStatusName; /** @@ -120,6 +104,7 @@ private String measureCategory; @ApiModelProperty(value = "校验类别名称", dataType = "String") + @ExcelProperty(value = "校验类别", order = 7) private String measureCategoryName; diff --git a/casic-metering-model/src/main/java/com/casic/missiles/dto/business/originRecord/OriginRecordRequest.java b/casic-metering-model/src/main/java/com/casic/missiles/dto/business/originRecord/OriginRecordRequest.java index d2c2ec7..d2687bf 100644 --- a/casic-metering-model/src/main/java/com/casic/missiles/dto/business/originRecord/OriginRecordRequest.java +++ b/casic-metering-model/src/main/java/com/casic/missiles/dto/business/originRecord/OriginRecordRequest.java @@ -31,7 +31,7 @@ @ApiModelProperty(value = "创建人", dataType = "String") private String createUser; - @ApiModelProperty(value = "原始记录单id", dataType = "Long") + @ApiModelProperty(value = "委托书id", dataType = "Long") private Long id; @ApiModelProperty(value = "导出ids(查询不用传)", dataType = "List") diff --git a/casic-metering-service/src/main/java/com/casic/missiles/service/Impl/business/BusinessCertificateReportServiceImpl.java b/casic-metering-service/src/main/java/com/casic/missiles/service/Impl/business/BusinessCertificateReportServiceImpl.java index d03ab22..aabfac2 100644 --- a/casic-metering-service/src/main/java/com/casic/missiles/service/Impl/business/BusinessCertificateReportServiceImpl.java +++ b/casic-metering-service/src/main/java/com/casic/missiles/service/Impl/business/BusinessCertificateReportServiceImpl.java @@ -26,8 +26,6 @@ import com.casic.missiles.service.business.IBusinessCertificateReportService; import com.casic.missiles.service.business.IBusinessOriginalRecordService; import com.casic.missiles.service.flowable.ApprovalOperateService; -import com.casic.missiles.utils.ConvertUtils; -import com.casic.missiles.utils.DictCodeUtils; import com.casic.missiles.utils.NumberGeneratorUtil; import org.flowable.engine.RuntimeService; import org.flowable.engine.TaskService; @@ -68,8 +66,10 @@ private RuntimeService runtimeService; @Resource private IBaseExportService iBaseExportService; + /** * 保存证书报告信息 + * * @param certificateReport * @return */ @@ -77,7 +77,7 @@ public ReturnDTO saveCertificateReport(BusinessCertificateReport certificateReport) { initCertificateReport(certificateReport); - if(this.baseMapper.insert(certificateReport)>0) + if (this.baseMapper.insert(certificateReport) > 0) return ReturnUtil.success(); throw new BusinessException(BusinessExceptionEnum.HANDLE_FAILED); } @@ -90,9 +90,9 @@ @Override public ReturnDTO approvalDelete(ApprovalDeleteRequest request) { ReturnDTO returnDTO = approvalOperateService.delete(request); - if(ResponseData.DEFAULT_SUCCESS_CODE == returnDTO.getCode()){ + if (ResponseData.DEFAULT_SUCCESS_CODE == returnDTO.getCode()) { //删除数据库记录 - if(this.baseMapper.deleteById(request.getId()) > 0){ + if (this.baseMapper.deleteById(request.getId()) > 0) { return ReturnUtil.success(); } } @@ -101,7 +101,7 @@ @Override public ReturnDTO draftUpdate(BusinessCertificateReport certificateReport) { - if(this.baseMapper.updateById(certificateReport)>0){ + if (this.baseMapper.updateById(certificateReport) > 0) { return ReturnUtil.success(); } throw new BusinessException(BusinessExceptionEnum.HANDLE_FAILED); @@ -109,25 +109,27 @@ /** * 批量删除 + * * @param ids * @return */ @Override public ReturnDTO deleteBatchTraceSupplier(List ids) { - return baseMapper.deleteBatchIds(ids) > 0?ReturnUtil.success(): + return baseMapper.deleteBatchIds(ids) > 0 ? ReturnUtil.success() : ReturnUtil.failed("删除失败"); } /** * 证书报告详情 + * * @param id * @return */ @Override public BusinessCertificateReport certificateReportDetail(Long id) { BusinessCertificateReport certificateReport = this.baseMapper.selectById(id); - if(certificateReport.getOriginalRecordId()!=null){ + if (certificateReport.getOriginalRecordId() != null) { try { certificateReport.setBusinessOriginalRecord(originalRecordService.originalDetail(certificateReport.getOriginalRecordId())); } catch (Exception e) { @@ -139,6 +141,7 @@ /** * 提交证书报告 + * * @param request * @return */ @@ -148,10 +151,10 @@ String formId = request.getFormId(); //2.根据流程定义id启动流程实例 ReturnDTO returnDTO = baseApprovalService.processSubmit(formId, request.getId()); - if(ResponseData.DEFAULT_SUCCESS_CODE != returnDTO.getCode()){ + if (ResponseData.DEFAULT_SUCCESS_CODE != returnDTO.getCode()) { return returnDTO; } - ProcessInstance processInstance = (ProcessInstance)returnDTO.getData(); + ProcessInstance processInstance = (ProcessInstance) returnDTO.getData(); BusinessCertificateReport certificateReport = new BusinessCertificateReport(); certificateReport.setId(request.getId()); certificateReport.setApprovalStatus(ApprovalStatusEnum.UN_DRAFT); //非草稿状态 @@ -165,6 +168,7 @@ /** * 审批状态列表查询 + * * @param page * @param request * @return @@ -182,6 +186,7 @@ /** * 驳回后更新 + * * @param certificateReport * @return */ @@ -208,13 +213,14 @@ @Override public void originExport(CertificateReportApprovalRequest request, HttpServletResponse response) { try { - //toDo: -// List certificateReportResponses = this.certificateReport(request); -// for (OriginRecordResponse originRecordResponse : originExportList) { -// //字典值转换 -// DictCodeUtils.convertDictCodeToName(originRecordResponse); -// } -// iBaseExportService.exportExcel(response, CertificateReportResponse.class, originExportList, ExportEnum.CERTIFICATE_REPORT.getSheetName()); + //登录用户 + AuthUser user = ShiroKit.getUser(); + Assert.isFalse(Objects.isNull(user), () -> { + throw new BusinessException(BusinessExceptionEnum.LOGIN_USER_ACQUIRE_FAILED); + }); + request.setCreateUserId(user.getId()); + List reportResponseList= handleApprovalStatus(null, request); + iBaseExportService.exportExcel(response, CertificateReportResponse.class, reportResponseList, ExportEnum.CERTIFICATE_REPORT.getSheetName()); } catch (Exception e) { log.error("证书报告导出出现异常,异常信息为{}", e); } @@ -231,15 +237,15 @@ //待审批,该状态维护在flowable中 case ApprovalStatusEnum.TO_BE_APPROVED: List toBeApprovedList = baseApprovalService.getToBeApprovedList(request.getFormId()); - if(!CollectionUtils.isEmpty(toBeApprovedList)){ + if (!CollectionUtils.isEmpty(toBeApprovedList)) { businessKeys = toBeApprovedList.stream().map(ToBeApprovedDTO::getBusinessKey).distinct().collect(Collectors.toList()); } - if(!CollectionUtils.isEmpty(businessKeys)){ + if (!CollectionUtils.isEmpty(businessKeys)) { approvalList = handleApprovalListResponse(this.baseMapper.selectBatchForApproval(page, request, businessKeys), ApprovalStatusEnum.TO_BE_APPROVED); //DTO根据业务主键补全taskId approvalList.forEach(approval -> { toBeApprovedList.forEach(toBeApprovedDTO -> { - if(String.valueOf(approval.getId()).equals(toBeApprovedDTO.getBusinessKey())){ + if (String.valueOf(approval.getId()).equals(toBeApprovedDTO.getBusinessKey())) { approval.setTaskId(toBeApprovedDTO.getTaskId()); //补全可选决策项 approval.setDecisionItem(toBeApprovedDTO.getDecisionItem()); @@ -251,27 +257,27 @@ //审批中,该状态维护在flowable中 case ApprovalStatusEnum.IN_APPROVED: businessKeys = baseApprovalService.getInApprovedList(request.getFormId()); - if(!CollectionUtils.isEmpty(businessKeys)){ + if (!CollectionUtils.isEmpty(businessKeys)) { approvalList = handleApprovalListResponse(this.baseMapper.selectBatchForApproval(page, request, businessKeys), ApprovalStatusEnum.IN_APPROVED); } break; //已通过,该状态维护在flowable case ApprovalStatusEnum.PASSED: businessKeys = baseApprovalService.getPassedList(request.getFormId()); - if(!CollectionUtils.isEmpty(businessKeys)){ - approvalList = handleApprovalListResponse( this.baseMapper.selectBatchForApproval(page, request, businessKeys), ApprovalStatusEnum.PASSED); + if (!CollectionUtils.isEmpty(businessKeys)) { + approvalList = handleApprovalListResponse(this.baseMapper.selectBatchForApproval(page, request, businessKeys), ApprovalStatusEnum.PASSED); } break; //未通过(包括拒绝、驳回,拒绝为直接删除实例,驳回为驳回到起点),该状态维护在flowable case ApprovalStatusEnum.FAILED: businessKeys = baseApprovalService.getFailedList(request.getFormId()); //未通过-拒绝 List rejectBusinessKey = baseApprovalService.getFailedRejectList(request.getFormId()); //未通过-驳回 - if(!CollectionUtils.isEmpty(businessKeys)){ + if (!CollectionUtils.isEmpty(businessKeys)) { approvalList = handleApprovalListResponse(this.baseMapper.selectBatchForApproval(page, request, businessKeys), ApprovalStatusEnum.FAILED); } List rejectApprovalList = new ArrayList<>(); - if(!CollectionUtils.isEmpty(rejectBusinessKey)){ - rejectApprovalList = handleApprovalListResponse( this.baseMapper.selectBatchForApproval(page, request, rejectBusinessKey), ApprovalStatusEnum.FAILED_REJECT); + if (!CollectionUtils.isEmpty(rejectBusinessKey)) { + rejectApprovalList = handleApprovalListResponse(this.baseMapper.selectBatchForApproval(page, request, rejectBusinessKey), ApprovalStatusEnum.FAILED_REJECT); } //合并未通过-拒绝和未通过-驳回 approvalList.addAll(rejectApprovalList); @@ -279,7 +285,7 @@ //已取消(直接删除实例),该状态维护在flowable case ApprovalStatusEnum.CANCELED: businessKeys = baseApprovalService.getCanceledList(request.getFormId()); - if(!CollectionUtils.isEmpty(businessKeys)){ + if (!CollectionUtils.isEmpty(businessKeys)) { approvalList = handleApprovalListResponse(this.baseMapper.selectBatchForApproval(page, request, businessKeys), ApprovalStatusEnum.CANCELED); } break; @@ -288,10 +294,10 @@ //普通用户获取自己发起的(审批中、已通过、未通过、已取消),管理员获取全部(审批中、已通过、未通过、已取消) case ApprovalStatusEnum.ALL: List AllApproveList = baseApprovalService.getAllList(request.getFormId()); - if(!CollectionUtils.isEmpty(AllApproveList)){ + if (!CollectionUtils.isEmpty(AllApproveList)) { businessKeys = AllApproveList.stream().map(AllApproveDTO::getBusinessKey).collect(Collectors.toList()); } - if(!CollectionUtils.isEmpty(businessKeys)){ + if (!CollectionUtils.isEmpty(businessKeys)) { approvalList = handleAllApprovalListResponse(this.baseMapper.selectBatchForApproval(page, request, businessKeys), AllApproveList); } break; @@ -299,9 +305,11 @@ return approvalList; } - private List handleAllApprovalListResponse(List approvalList, List allApproveList) { - Map taskMap = new HashMap<>(); - allApproveList.forEach(allApprove -> {taskMap.put(allApprove.getBusinessKey(),allApprove.getStatus());}); + private List handleAllApprovalListResponse(List approvalList, List allApproveList) { + Map taskMap = new HashMap<>(); + allApproveList.forEach(allApprove -> { + taskMap.put(allApprove.getBusinessKey(), allApprove.getStatus()); + }); //状态补全 approvalList.forEach(approval -> { approval.setApprovalStatusName(dictService.getDictNameByCode(MeterDictEnum.APPROVAL_STATUS, taskMap.get(String.valueOf(approval.getId())))); @@ -313,7 +321,7 @@ return approvalList.stream().sorted(Comparator.comparing(CertificateReportResponse::getCreateTime).reversed()).collect(Collectors.toList()); } - private List handleApprovalListResponse(List approvalList, String status){ + private List handleApprovalListResponse(List approvalList, String status) { approvalList.stream().forEach(result -> { //审批状态两种获取方式:1、在此处设置,2、在flowable中设置业务状态,暂采取1 result.setApprovalStatusName(dictService.getDictNameByCode(MeterDictEnum.APPROVAL_STATUS, status)); @@ -324,14 +332,14 @@ private void initCertificateReport(BusinessCertificateReport certificateReport) { String prefix = MonitorCodeEnum.getByCode(certificateReport.getCalibrationMajor()).getValue() - +DateUtil.format(new Date(),"YYYYMM"); + + DateUtil.format(new Date(), "YYYYMM"); Long maxNo = this.baseMapper.selectMaxCode(prefix); //生成证书编号 - String certificateReportNo =NumberGeneratorUtil.getCode( - MonitorCodeEnum.getByCode(certificateReport.getCalibrationMajor()).getValue(),maxNo); + String certificateReportNo = NumberGeneratorUtil.getCode( + MonitorCodeEnum.getByCode(certificateReport.getCalibrationMajor()).getValue(), maxNo); AuthUser authUser = ShiroKit.getUser(); certificateReport.setCreateUser(authUser.getId()); - certificateReport.setMeasurePersonId(authUser.getId()+""); + certificateReport.setMeasurePersonId(authUser.getId() + ""); certificateReport.setMeasureDeptId(authUser.getDeptId()); certificateReport.setCertificateReportCode(certificateReportNo); } diff --git a/casic-metering-service/src/main/java/com/casic/missiles/service/Impl/business/BusinessOrderServiceImpl.java b/casic-metering-service/src/main/java/com/casic/missiles/service/Impl/business/BusinessOrderServiceImpl.java index f5c6f61..21ab8b6 100644 --- a/casic-metering-service/src/main/java/com/casic/missiles/service/Impl/business/BusinessOrderServiceImpl.java +++ b/casic-metering-service/src/main/java/com/casic/missiles/service/Impl/business/BusinessOrderServiceImpl.java @@ -90,8 +90,10 @@ List customerSampleList = new ArrayList<>(); for (BusinessOrderSampleRelation orderSample : orderSampleList) { CustomerSampleInfo customerSampleInfo = customerSampleService.sampleDetail(orderSample.getSampleId()); - customerSampleInfo.setIsExistSample("1"); - customerSampleList.add(customerSampleInfo); + if (null != customerSampleInfo) { + customerSampleInfo.setIsExistSample("1"); + customerSampleList.add(customerSampleInfo); + } } businessOrder.setCustomerSampleInfoList(customerSampleList); return businessOrder; diff --git a/casic-metering-api/src/main/java/com/casic/missiles/controller/business/BusinessCertificateReportController.java b/casic-metering-api/src/main/java/com/casic/missiles/controller/business/BusinessCertificateReportController.java index c440253..408b580 100644 --- a/casic-metering-api/src/main/java/com/casic/missiles/controller/business/BusinessCertificateReportController.java +++ b/casic-metering-api/src/main/java/com/casic/missiles/controller/business/BusinessCertificateReportController.java @@ -9,17 +9,13 @@ import com.casic.missiles.dto.business.certificate.CertificateReportApprovalRequest; import com.casic.missiles.dto.business.certificate.CertificateReportResponse; import com.casic.missiles.dto.flowable.ApprovalDeleteRequest; -import com.casic.missiles.dto.meter.TraceSupplierListRequest; import com.casic.missiles.enums.BusinessExceptionEnum; import com.casic.missiles.exception.BusinessException; import com.casic.missiles.model.business.BusinessCertificateReport; import com.casic.missiles.model.exception.enums.CoreExceptionEnum; -import com.casic.missiles.model.meter.MeterTraceSupplier; import com.casic.missiles.service.business.IBusinessCertificateReportService; -import com.casic.missiles.service.meter.IMeterTraceSupplierService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.util.CollectionUtils; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.*; @@ -45,28 +41,7 @@ public class BusinessCertificateReportController extends ExportController { @Resource private IBusinessCertificateReportService certificateReportService; - @Autowired - private IMeterTraceSupplierService traceSupplierService; - @ApiOperation("证书报告列表(分页)") - @PostMapping("/listPage") - @ResponseBody - public ReturnDTO> supplierListPage(@RequestBody @Valid TraceSupplierListRequest request, BindingResult bindingResult) { - if (bindingResult.hasErrors()) { - throw new BusinessException(CoreExceptionEnum.REQUEST_NULL.getCode(), bindingResult.getFieldError().getDefaultMessage()); - } - Page page = PageFactory.defaultPage(); - return ReturnUtil.success(super.packForBT(traceSupplierService.listPage(page, request))); - } - @ApiOperation("证书报告列表") - @PostMapping("/list") - @ResponseBody - public ReturnDTO> supplierList(@RequestBody @Valid TraceSupplierListRequest request, BindingResult bindingResult) { - if (bindingResult.hasErrors()) { - throw new BusinessException(CoreExceptionEnum.REQUEST_NULL.getCode(), bindingResult.getFieldError().getDefaultMessage()); - } - return ReturnUtil.success(traceSupplierService.list(request)); - } @ApiOperation("证书报告记录导出") @PostMapping("/listExport") @@ -113,18 +88,6 @@ return certificateReportService.submitCertificateReport(request); } - @ApiOperation("证书报告更新(审批通过后还能更新??暂时保留。。)") - @PostMapping("/update") - @ResponseBody - public ReturnDTO supplierUpdate(@RequestBody @Valid MeterTraceSupplier traceSupplier, BindingResult bindingResult) { - Assert.isFalse(Objects.isNull(traceSupplier.getId()), () -> { - throw new BusinessException(BusinessExceptionEnum.ID_NULL); - }); - Assert.isFalse(bindingResult.hasErrors(), () -> { - throw new BusinessException(CoreExceptionEnum.REQUEST_NULL.getCode(), bindingResult.getFieldError().getDefaultMessage()); - }); - return traceSupplierService.updateTraceSupplier(traceSupplier); - } @ApiOperation("证书报告批量删除") @PostMapping("/batchDelete") diff --git a/casic-metering-api/src/main/java/com/casic/missiles/controller/system/PoiController.java b/casic-metering-api/src/main/java/com/casic/missiles/controller/system/PoiController.java index 021eaa8..9848e68 100644 --- a/casic-metering-api/src/main/java/com/casic/missiles/controller/system/PoiController.java +++ b/casic-metering-api/src/main/java/com/casic/missiles/controller/system/PoiController.java @@ -3,12 +3,14 @@ import cn.afterturn.easypoi.entity.ImageEntity; import com.casic.missiles.utils.PdfUtil; +import com.casic.missiles.utils.StampUtils; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.stereotype.Controller; import org.springframework.util.Assert; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpServletResponse; import java.io.*; @@ -23,7 +25,51 @@ private String filepath="C:\\upload"; @ApiOperation("word转pdf") + @PostMapping(value = "/convertWordToPdf1") + @ResponseBody + public void convertWordToPdf1() throws Exception { + File uploadFile = new File(filepath); + String wordDir = ""; + if (!uploadFile.exists()) { + uploadFile.mkdirs(); + } + if (!filepath.endsWith("/")) { + wordDir = filepath + File.separator + "word"; + } + File tf = new File(wordDir + File.separator + "tem.docx"); + File tf_pic = new File(wordDir + File.separator + "logo.jpg"); + String pic_url = tf_pic.getCanonicalPath(); + Calendar now = Calendar.getInstance(); + Map params = new HashMap<>(); + List> dataList=new ArrayList<>(); + for (int i = 0; i < 5; i++) { + Map param = new HashMap<>(); + param.put("name", "彭于晏"+i); + param.put("sex", "男"+i); + param.put("address", "中国"+i); + ImageEntity image = new ImageEntity(); + image.setHeight(100); + image.setWidth(100); + image.setUrl(pic_url); + image.setData(PdfUtil.getImageBase64(pic_url)); + param.put("image", image); + dataList.add(param); + } + + params.put("dataList",dataList); + params.put("y", now.get(Calendar.YEAR)); + params.put("m", (now.get(Calendar.MONTH) + 1)); + params.put("d", now.get(Calendar.DAY_OF_MONTH)); + + String fileName = "wordExport.docx"; + String word = StampUtils.exportWord(tf.getPath(), wordDir, fileName, params); + System.out.println("****新模板"+word); + + } + + @ApiOperation("word转pdf") @PostMapping(value = "/convertWordToPdf") + @ResponseBody public void convertWordToPdf(HttpServletResponse response) throws Exception { File uploadFile = new File(filepath); String wordDir = ""; @@ -117,4 +163,5 @@ } } } + } diff --git a/casic-metering-common/pom.xml b/casic-metering-common/pom.xml index bb00ab9..e028713 100644 --- a/casic-metering-common/pom.xml +++ b/casic-metering-common/pom.xml @@ -11,6 +11,7 @@ casic-metering-common + @@ -171,6 +172,14 @@ 4.1.2 + + + + e-iceblue + spire.office.free + 5.3.1 + + com.google.zxing diff --git a/casic-metering-common/src/main/java/com/casic/missiles/utils/CustomXWPFDocumentUtil.java b/casic-metering-common/src/main/java/com/casic/missiles/utils/CustomXWPFDocumentUtil.java deleted file mode 100644 index 9e7ed3f..0000000 --- a/casic-metering-common/src/main/java/com/casic/missiles/utils/CustomXWPFDocumentUtil.java +++ /dev/null @@ -1,309 +0,0 @@ -package com.casic.missiles.utils; - -import java.io.*; -import java.util.*; -import java.util.Map.Entry; - -import cn.afterturn.easypoi.entity.ImageEntity; -import org.apache.commons.lang3.StringUtils; -import org.apache.poi.ooxml.POIXMLDocument; -import org.apache.poi.openxml4j.exceptions.InvalidFormatException; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.util.Units; -import org.apache.poi.xwpf.usermodel.*; -import org.apache.xmlbeans.XmlException; -import org.apache.xmlbeans.XmlToken; -import org.openxmlformats.schemas.drawingml.x2006.main.CTGraphicalObject; -import org.openxmlformats.schemas.drawingml.x2006.main.CTNonVisualDrawingProps; -import org.openxmlformats.schemas.drawingml.x2006.main.CTPositiveSize2D; -import org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.CTAnchor; -import org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.CTInline; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTDrawing; - -public class CustomXWPFDocumentUtil extends XWPFDocument { - - public CustomXWPFDocumentUtil(InputStream in) throws IOException { - super(in); - } - - public CustomXWPFDocumentUtil() { - super(); - } - - public CustomXWPFDocumentUtil(OPCPackage pkg) throws IOException { - super(pkg); - } - - /** - * 根据指定的参数值、模板,生成 word 文档 - * - * @param param 需要替换的变量 - * @param template 模板 - */ - public static XWPFDocument generateWord(Map param, String template) { - XWPFDocument doc = null; - try { - OPCPackage pack = POIXMLDocument.openPackage(template); - doc = new CustomXWPFDocumentUtil(pack); - if (param != null && param.size() > 0) { - - //处理段落 - List paragraphList = doc.getParagraphs(); - processParagraphs(paragraphList, param, doc); - - //处理表格 - Iterator it = doc.getTablesIterator(); - while (it.hasNext()) { - XWPFTable table = it.next(); - List rows = table.getRows(); - for (XWPFTableRow row : rows) { - List cells = row.getTableCells(); - for (XWPFTableCell cell : cells) { - List paragraphListTable = cell.getParagraphs(); - processParagraphs(paragraphListTable, param, doc); - } - } - } - } - } catch (IOException e) { - e.printStackTrace(); - } catch (Exception e) { - e.printStackTrace(); - } - return doc; - } - - /** - * 处理段落 - * - * @param paragraphList - * @param - * @throws FileNotFoundException - * @throws InvalidFormatException - */ - public static void processParagraphs(List paragraphList, Map param, XWPFDocument doc) throws InvalidFormatException, FileNotFoundException { - if (paragraphList != null && paragraphList.size() > 0) { - for (XWPFParagraph paragraph : paragraphList) { - List runs = paragraph.getRuns(); - for (XWPFRun run : runs) { - String text = run.getText(0); - //System.out.println("text=="+text); - if (text != null) { - boolean isSetText = false; - for (Entry entry : param.entrySet()) { - String key = entry.getKey(); - if (text.indexOf(key) != -1) { - isSetText = true; - Object value = entry.getValue(); - if (value instanceof String) {//文本替换 - //System.out.println("key=="+key); - text = text.replace(key, value.toString()); - } else if (value instanceof Map) { //图片替换 - text = text.replace(text, ""); - Map pic = (Map) value; - int width = Integer.parseInt(pic.get("width").toString()); - int height = Integer.parseInt(pic.get("height").toString()); - int picType = getPictureType(pic.get("type").toString()); - String picPath = (String) pic.get("picPath"); - CTInline inline = run.getCTR().addNewDrawing().addNewInline(); - insertPicture(doc, picPath, inline, width, height); - CTDrawing drawing = run.getCTR().getDrawingArray(0); - CTGraphicalObject graphicalobject = drawing.getInlineArray(0).getGraphic(); - //拿到新插入的图片替换添加CTAnchor 设置浮动属性 删除inline属性 - CTAnchor anchor = getAnchorWithGraphic(graphicalobject, "11", - Units.toEMU(width), Units.toEMU(height),//图片大小 - Units.toEMU(0), Units.toEMU(0));//相对当前段落位置的偏移位置,左右偏移:负数向左,正数向右,上下偏移:负数向上,正数向下 - drawing.setAnchorArray(new CTAnchor[]{anchor});//添加浮动属性 - drawing.removeInline(0);//删除行内属性 - } - } - } - if (isSetText) { - run.setText(text, 0); - } - } - } - } - } - } - - /** - * 根据图片类型,取得对应的图片类型代码 - * - * @param picType - * @return int - */ - private static int getPictureType(String picType) { - int res = CustomXWPFDocumentUtil.PICTURE_TYPE_PICT; - if (picType != null) { - if (picType.equalsIgnoreCase("png")) { - res = CustomXWPFDocumentUtil.PICTURE_TYPE_PNG; - } else if (picType.equalsIgnoreCase("dib")) { - res = CustomXWPFDocumentUtil.PICTURE_TYPE_DIB; - } else if (picType.equalsIgnoreCase("emf")) { - res = CustomXWPFDocumentUtil.PICTURE_TYPE_EMF; - } else if (picType.equalsIgnoreCase("jpg") || picType.equalsIgnoreCase("jpeg")) { - res = CustomXWPFDocumentUtil.PICTURE_TYPE_JPEG; - } else if (picType.equalsIgnoreCase("wmf")) { - res = CustomXWPFDocumentUtil.PICTURE_TYPE_WMF; - } - } - return res; - } - - /** - * insert Picture - * - * @param document - * @param filePath - * @param inline - * @param width - * @param height - * @throws InvalidFormatException - * @throws FileNotFoundException - */ - private static void insertPicture(XWPFDocument document, String filePath, - CTInline inline, int width, - int height) throws InvalidFormatException, - FileNotFoundException { - document.addPictureData(new FileInputStream(filePath), XWPFDocument.PICTURE_TYPE_PNG); - int id = document.getAllPictures().size() - 1; - final int EMU = 9525; - width *= EMU; - height *= EMU; - String blipId = - document.getAllPictures().get(id).getRelationId(document); - String picXml = getPicXml(blipId, width, height); - XmlToken xmlToken = null; - try { - xmlToken = XmlToken.Factory.parse(picXml); - } catch (XmlException xe) { - xe.printStackTrace(); - } - inline.set(xmlToken); - inline.setDistT(0); - inline.setDistB(0); - inline.setDistL(0); - inline.setDistR(0); - CTPositiveSize2D extent = inline.addNewExtent(); - extent.setCx(width); - extent.setCy(height); - CTNonVisualDrawingProps docPr = inline.addNewDocPr(); - docPr.setId(id); - docPr.setName("IMG_" + id); - docPr.setDescr("IMG_" + id); - } - - /** - * get the xml of the picture - * - * @param blipId - * @param width - * @param height - * @return - */ - private static String getPicXml(String blipId, int width, int height) { - String picXml = - "" + "" + - " " + - " " + - " " + " " + " " + - " " + " " + - " " + - " " + " " + - " " + " " + - " " + " " + - " " + - " " + " " + - " " + - " " + " " + - " " + " " + - " " + ""; - return picXml; - } - - /** - * @param ctGraphicalObject 图片数据 - * @param deskFileName 图片描述 - * @param width 宽 - * @param height 高 - * @param leftOffset 水平偏移:负数向左,正数向右 - * @param topOffset 垂直偏移:负数向上,正数向下 - * @return CTAnchor - * @throws Exception - */ - public static CTAnchor getAnchorWithGraphic(CTGraphicalObject ctGraphicalObject, - String deskFileName, int width, int height, - int leftOffset, int topOffset) { - //浮在文字上的设置主要是anchor标签下的behindDoc属性设为0,同时添加一个的空标签。 - if (StringUtils.isBlank(deskFileName)) { - deskFileName = new Random().nextInt(999) + "";//描述不能为空,赋值一个随机数 - } - String anchorXML = - "" - + "" - + "" - + "" + leftOffset + "" - + "" - + "" - + "" + topOffset + "" + - "" - + "" - + "" - + "" - + "" - + ""; - CTDrawing drawing = null; - try { - drawing = CTDrawing.Factory.parse(anchorXML); - } catch (XmlException e) { - e.printStackTrace(); - } - CTAnchor anchor = drawing.getAnchorArray(0); - anchor.setGraphic(ctGraphicalObject); - return anchor; - } - public static void main(String[] args) throws IOException{ - Map params = new HashMap<>(); - List> dataList=new ArrayList<>(); - for (int i = 0; i < 5; i++) { - Map param = new HashMap<>(); - param.put("name", "彭于晏"+i); - param.put("sex", "男"+i); - param.put("address", "中国"+i); - ImageEntity image = new ImageEntity(); - image.setHeight(100); - image.setWidth(100); - image.setUrl("C:\\upload\\word\\"); - image.setData(PdfUtil.getImageBase64("C:\\upload\\word\\logo.jpg")); - param.put("image", image); - dataList.add(param); - } - Calendar now = Calendar.getInstance(); - params.put("dataList",dataList); - params.put("y", now.get(Calendar.YEAR)+""); - params.put("m", (now.get(Calendar.MONTH) + 1)+""); - params.put("d", now.get(Calendar.DAY_OF_MONTH)+""); - String template="C:\\upload\\word\\tem.docx"; - ByteArrayOutputStream baos = null; - try { - XWPFDocument document = generateWord(params, template); - baos = new ByteArrayOutputStream(); - document.write(baos);//临时存储流到内存 - baos.flush(); - } catch (Exception e) { - e.printStackTrace(); - }finally{ - if(baos != null){ - baos.close(); - } - } - - - } - -} diff --git a/casic-metering-common/src/main/java/com/casic/missiles/utils/PdfUtil.java b/casic-metering-common/src/main/java/com/casic/missiles/utils/PdfUtil.java index 3d80a8e..3e4f58b 100644 --- a/casic-metering-common/src/main/java/com/casic/missiles/utils/PdfUtil.java +++ b/casic-metering-common/src/main/java/com/casic/missiles/utils/PdfUtil.java @@ -23,12 +23,12 @@ public class PdfUtil { /** - * 生成word 只支持docx + * 按照模板 填充数据生成word 只支持docx * * @param templatePath 模板文件路径 - * @param temDir 生成文件的目录 - * @param fileName 生成文件名 - * @param params 参数 + * @param temDir 生成文件的目录 + * @param fileName 生成文件名 + * @param params 参数 */ public static String exportWord(String templatePath, String temDir, String fileName, Map params) { Assert.notNull(templatePath, "模板路径不能为空"); @@ -39,8 +39,9 @@ temDir = temDir + File.separator; } File dir = new File(temDir); - if (!dir.exists()) { - dir.mkdirs(); + if (!dir.getParentFile().exists()) { + // 新建文件夹 + dir.getParentFile().mkdirs(); } String tmpPath = ""; try { @@ -51,13 +52,13 @@ fos.flush(); fos.close(); } catch (Exception e) { - //e.printStackTrace(); + e.printStackTrace(); } return tmpPath; } - public static String convertDocx2Pdf(String wordPath,String pdfPath) { + public static String convertDocx2Pdf(String wordPath, String pdfPath) { OutputStream os = null; InputStream is = null; try { diff --git a/casic-metering-common/src/main/java/com/casic/missiles/utils/PictureUtil.java b/casic-metering-common/src/main/java/com/casic/missiles/utils/PictureUtil.java deleted file mode 100644 index 4baa893..0000000 --- a/casic-metering-common/src/main/java/com/casic/missiles/utils/PictureUtil.java +++ /dev/null @@ -1,184 +0,0 @@ -//package com.casic.missiles.utils; -// -//import cn.hutool.core.codec.Base64; -//import com.alibaba.fastjson.JSONObject; -//import com.google.common.collect.Lists; -//import org.apache.poi.xwpf.usermodel.*; -//import org.apache.xmlbeans.XmlException; -//import org.openxmlformats.schemas.drawingml.x2006.main.CTGraphicalObject; -//import org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.CTAnchor; -//import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTDrawing; -// -//import java.io.*; -//import java.util.List; -//import java.util.Map; -//import java.util.Set; -// -//public class PictureUtil { -// public void create(String filePath, JSONObject jsonObject) { -// try { -// FileInputStream template = new FileInputStream(new File(filePath)); -// //获取docx解析对象 -// XWPFDocument document = new XWPFDocument(template); -// List tableList = Lists.newArrayList(); -// -// //解析替换表格对象 -// List tables = document.getTables(); -// for (int i = 0; i < tables.size(); i++) { -// //只处理行数大于等于2的表格,且不循环表头 -// XWPFTable table = tables.get(i); -// if (table.getRows().size() > 1) { -// //判断表格是需要替换还是需要插入,判断逻辑有$为替换,表格无$为插入 -// if (WordUtil.checkText(table.getText())) { -// List rows = table.getRows(); -// //遍历表格,并替换模板 -// eachTable(rows, jsonObject); -// } -// } -// } -// -// // workBook写入输出流 -// ByteArrayOutputStream baos = new ByteArrayOutputStream(); -// document.write(baos); -// baos.flush(); -// } catch (Exception e) { -// e.printStackTrace(); -// } -// } -// /** -// * 遍历表格 -// * -// * @param rows 表格行对象 -// * @param textMap 需要替换的信息集合 -// */ -// public static void eachTable(List rows, JSONObject textMap) { -// for (XWPFTableRow row : rows) { -// List cells = row.getTableCells(); -// for (XWPFTableCell cell : cells) { -// //判断单元格是否需要替换 -// if (checkText(cell.getText())) { -// List paragraphs = cell.getParagraphs(); -// for (XWPFParagraph paragraph : paragraphs) { -// List runs = paragraph.getRuns(); -// for (XWPFRun run : runs) { -//// run.setText(changeValue(run.toString(), textMap), 0); -// //新增制证照片单独处理 -// if (run.toString().indexOf("${jpeg}") != -1 && textMap.containsKey("jpeg")){ -// addPic(run,textMap, 1188000, 1728000,0, 0); -// break; -// } -// String value = changeValue(run.toString(), textMap); -// setWrap(value, run); -// } -// } -// } -// } -// } -// } -// -// /** -// * 匹配传入信息集合与模板 -// * -// * @param value 模板需要替换的区域 -// * @param textMap 传入信息集合 -// * @return 模板需要替换区域信息集合对应值 -// */ -// public static String changeValue(String value, JSONObject textMap) { -// -// boolean flag = false; -// Set> textSets = textMap.entrySet(); -// for (Map.Entry textSet : textSets) { -// //匹配模板与替换值 格式${key} -// String key = "${" + textSet.getKey() + "}"; -// if (value.indexOf(key) != -1) { -// value = textSet.getValue() == null ? "" : ("" + textSet.getValue()); -// flag = true; -// break; -// } -// } -// //模板未匹配到区域替换为空 -// if (checkText(value)) { -// value = ""; -// } -// return value; -// } -// public static void setWrap(String value, XWPFRun run) { -// if ( value.indexOf("\n") > 0) { -// //设置换行 -// String[] text = value.split("\n"); -// for (int f = 0; f < text.length; f++) { -// if (f == 0) { -// run.setText(text[f].trim(),0); -// } else { -//// run.addCarriageReturn();//硬回车 -// // 换行 -// run.addBreak(); -// run.setText(text[f]); -// } -// } -// } else { -// run.setText((String) value,0); -// } -// } -// -// /** -// * @param ctGraphicalObject 图片数据 -// * @param deskFileName 图片描述 -// * @param width 宽 -// * @param height 高 -// * @param leftOffset 水平偏移 left -// * @param topOffset 垂直偏移 top -// * @param behind 文字上方,文字下方 -// * @return -// * @throws Exception -// */ -// public static CTAnchor getAnchorWithGraphic(CTGraphicalObject ctGraphicalObject, String deskFileName, int width, int height, int leftOffset, int topOffset, boolean behind) { -// String anchorXML ="" -// +"" -// +" " -// +" " -// +" "+ leftOffset + "" -// +" " -// +" " -// +" "+ topOffset +"" -// +" " -// +" " -// +" " -// +" " -// +" " -// +""; -// try { -// CTDrawing drawing = CTDrawing.Factory.parse(anchorXML); -// CTAnchor anchor = drawing.getAnchorArray(0); -// anchor.setGraphic(ctGraphicalObject); -// return anchor; -// } catch (XmlException e) { -// e.printStackTrace(); -// return null; -// } -// } -// -// /** -// * 新增制证照片单独处理 -// * @param run -// * @param textMap -// */ -// public static void addPic(XWPFRun run, JSONObject textMap, int width, int height, int leftOffset, int topOffset){ -// String runText = run.toString().trim(); -// byte[] zjzp = Base64.decode(textMap.getString("jpeg")); -// try(ByteArrayInputStream byteInputStream = new ByteArrayInputStream(zjzp)) { -// //1、添加图片 -// run.addPicture(byteInputStream,XWPFDocument.PICTURE_TYPE_JPEG,"照片", width, height); -// //2、获取图片 -// CTDrawing cTDrawing = run.getCTR().getDrawingArray(0); -// CTGraphicalObject cTGraphicalObject = cTDrawing.getInlineArray(0).getGraphic(); -// //3、设置属性 -// CTAnchor ctAnchor = getAnchorWithGraphic(cTGraphicalObject,"照片", width, height,leftOffset, topOffset,false); -// cTDrawing.setAnchorArray(new CTAnchor[]{ctAnchor}); -// cTDrawing.removeInline(0); -// run.setText(runText.replace("${jpeg}",""), 0); -// }catch (Exception e){ -// e.printStackTrace(); -// } -// } -//} diff --git a/casic-metering-common/src/main/java/com/casic/missiles/utils/StampUtils.java b/casic-metering-common/src/main/java/com/casic/missiles/utils/StampUtils.java new file mode 100644 index 0000000..fb6d4cf --- /dev/null +++ b/casic-metering-common/src/main/java/com/casic/missiles/utils/StampUtils.java @@ -0,0 +1,482 @@ +package com.casic.missiles.utils; + + +import cn.afterturn.easypoi.word.WordExportUtil; +import cn.hutool.core.lang.Assert; +import com.baomidou.mybatisplus.core.toolkit.ObjectUtils; +import com.spire.doc.*; +import com.spire.doc.documents.*; +import com.spire.doc.fields.DocPicture; +import com.spire.doc.fields.TextRange; +import org.apache.commons.lang3.StringUtils; +import org.apache.poi.xwpf.usermodel.XWPFDocument; + +import javax.imageio.ImageIO; +import java.awt.*; +import java.awt.image.BufferedImage; +import java.io.*; +import java.util.Map; + +/** + * @Author:zt + * @Create:2023/3/7/9:30 + * @Description:TODO Word文件操作工具类 + * @Version:1.0 + */ + +public class StampUtils { + + //关键字索引 (-1) + private final static Integer keyWordIndex = -1; + // 电子印章水平位置 + private final static float horizontal = 300f; + // 电子印章垂直位置 + private final static float vertical = -55f; + // 电子印章宽度 + private final static float stampWidth = 120; + // 电子印章高度 + private final static float stampHeight = 120; + //照片透明度设置 + private final static int alpha = 150; + + + /** + * 1、自定义位置添加电子印章 + * 2、替换书签名位置文本内容 bookmarkName传参为null,则不进行书签替换操作 + * + * @param wordOldUrl word文件路径 + * @param wordNewUrl 新word文件路径 + * @param stampImgUrl 电子印章图片路径 + * @param horizontal 电子印章水平位置 (当前文件推荐260f) + * @param vertical 电子印章垂直位置 (当前推荐455f) + * @param stampWidth 电子印章宽度(推荐120) + * @param stampHeight 电子印章高度(推荐120) + * @param bookmarkName 书签名,通过名称寻找书签文本所在位置 + * @param newBookmarkText 替换的文本新内容 + */ + public void addStamp(String wordOldUrl, String wordNewUrl, String stampImgUrl, + Float horizontal, Float vertical, Float stampWidth, + Float stampHeight, String bookmarkName, String newBookmarkText) { + // 加载文档 + Document document = new Document(); + document.loadFromFile(wordOldUrl); + +// 获取指定段落 + Section section = document.getSections().get(0); +// 获取段落总数 + int count = section.getParagraphs().getCount(); +// log.info("获取文档内容段落总数{}",count); + Paragraph paragraph = section.getParagraphs().get(0); + + // 判断是否需要替换书签位置文本内容 + if (StringUtils.isNotEmpty(bookmarkName)) { + replaceBookmarkContent(document, bookmarkName, newBookmarkText); + } + +// 添加电子印章 + DocPicture docPicture = paragraph.appendPicture(stampImgUrl); + +// 指定电子章位置 +// 水平位置 + docPicture.setHorizontalPosition(horizontal); +// 垂直位置 + docPicture.setVerticalPosition(vertical); + +// 设置电子章大小 + docPicture.setWidth(stampWidth); + docPicture.setHeight(stampHeight); + +// 设置图片位于文字顶层 + docPicture.setTextWrappingStyle(TextWrappingStyle.In_Front_Of_Text); + + // 保存添加电子章的Word文档 + document.saveToFile(wordNewUrl); + document.dispose(); +// log.info("文档添加电子印章结束,新WORD文档地址:{}",wordNewUrl); + + } + + /** + * 1、根据关键词位置添加电子印章 + * 2、替换书签名位置文本内容 bookmarkName传参为null,则不进行书签替换操作 + * + * @param wordOldUrl word文件路径 + * @param wordNewUrl 新word文件路径 + * @param stampImgUrl 电子印章图片路径 + * @param keyWord 关键字 (自定义) + * @param keyWordIndex 关键字索引 (-1) + * @param horizontal 电子印章水平位置 (260f) + * @param vertical 电子印章垂直位置 (-55f) + * @param stampWidth 电子印章宽度 (推荐120) + * @param stampHeight 电子印章高度(推荐120) + */ + public static void addKeyWordStamp(String wordOldUrl, String wordNewUrl, String stampImgUrl, String stampImgUrl1, + String keyWord, Integer keyWordIndex, Float horizontal, + Float vertical, Float stampWidth, Float stampHeight) { + // 加载文档 + Document document = new Document(); + document.loadFromFile(wordOldUrl); + //获取关键字位置 + TextSelection[] textSelections = document.findAllString(keyWord, false, false); + //加签章照片 + if (ObjectUtils.isNotEmpty(textSelections) && StringUtils.isNotEmpty(stampImgUrl)) { + Paragraph paragraph = textSelections[keyWordIndex > -1 ? 0 : textSelections.length - 1].getAsOneRange().getOwnerParagraph(); + //添加公司印章 + DocPicture docPicture = paragraph.appendPicture(stampImgUrl); + + //设置图片位于文字顶层 + docPicture.setTextWrappingStyle(TextWrappingStyle.In_Front_Of_Text); + + //指定电子章位置 + //水平位置 + docPicture.setHorizontalPosition(horizontal); + //垂直位置 + docPicture.setVerticalPosition(vertical); + //设置电子章大小 + docPicture.setWidth(stampWidth); + docPicture.setHeight(stampHeight); + } + + //加签名照片 + if (ObjectUtils.isNotEmpty(textSelections) && StringUtils.isNotEmpty(stampImgUrl1)) { + Paragraph paragraph = textSelections[keyWordIndex > -1 ? 0 : textSelections.length - 1].getAsOneRange().getOwnerParagraph(); + // 添加电子印章 + DocPicture docPicture = paragraph.appendPicture(stampImgUrl1); + //设置图片位于文字顶层 + docPicture.setTextWrappingStyle(TextWrappingStyle.In_Front_Of_Text); + + //指定电子章位置 + //水平位置 + docPicture.setHorizontalPosition(horizontal); + //垂直位置 + docPicture.setVerticalPosition(vertical); + //设置电子章大小 + docPicture.setWidth(stampWidth); + docPicture.setHeight(stampHeight); + } + + //保存添加电子章的Word文档 + document.saveToFile(wordNewUrl); + document.dispose(); + } + + /** + * 替换书签名位置文本内容 + * + * @param document word文档对象 + * @param bookmarkName 书签名 + * @param newBookmarkText 新文本内容 + */ + public void replaceBookmarkContent(Document document, String bookmarkName, String newBookmarkText) { + //定位到指定书签位置 + BookmarksNavigator bookmarksNavigator = new BookmarksNavigator(document); + bookmarksNavigator.moveToBookmark(bookmarkName); + //用文本内容替换原有书签位置的文本,新替换的内容与原文格式一致 + bookmarksNavigator.replaceBookmarkContent(newBookmarkText, true); + } + + /** + * 替换书签名位置文本内容为图片 + * + * @param document word文档对象 + * @param bookmarkName 书签名 + * @param newImgUrl 图片地址 + */ + public void replaceBookmarkContentToImg(Document document, String bookmarkName, String newImgUrl) { + //定位到指定书签位置 + BookmarksNavigator bookmarksNavigator = new BookmarksNavigator(document); + bookmarksNavigator.moveToBookmark(bookmarkName); + //添加图片,替换原有书签内容 + Paragraph para = new Paragraph(document); + para.appendPicture(newImgUrl); + TextBodyPart bodyPart = new TextBodyPart(document); + bodyPart.getBodyItems().add(para); + bookmarksNavigator.replaceBookmarkContent(bodyPart); + } + + /** + * 替换书签名位置文本内容为表格 + * + * @param document word文档对象 + * @param bookmarkName 书签名 + */ + public void replaceBookmarkContentToTable(Document document, String bookmarkName) { + //声明数组内容 + String[][] data = + { + new String[]{"分类", "等级", "编号"}, + new String[]{"A", "一级", "01A"}, + new String[]{"B", "二级", "02B"}, + new String[]{"C", "三级", "03C"}, + }; + + //创建表格 + Table table = new Table(document, true); + table.resetCells(4, 3); + for (int i = 0; i < data.length; i++) { + TableRow dataRow = table.getRows().get(i); + for (int j = 0; j < data[i].length; j++) { + TextRange range = dataRow.getCells().get(j).addParagraph().appendText(data[i][j]); + range.getOwnerParagraph().getFormat().setHorizontalAlignment(HorizontalAlignment.Center); + range.getCharacterFormat().setFontName("楷体"); + dataRow.getRowFormat().setHorizontalAlignment(RowAlignment.Center); + dataRow.getCells().get(j).getCellFormat().setVerticalAlignment(VerticalAlignment.Middle); + } + } + + //创建TextBodyPart对象 + TextBodyPart bodyPart = new TextBodyPart(document); + bodyPart.getBodyItems().add(table); + + //定位到指定书签位置 + BookmarksNavigator bookmarkNavigator = new BookmarksNavigator(document); + bookmarkNavigator.moveToBookmark(bookmarkName); + + //使用表格替换原书签的内容 + bookmarkNavigator.replaceBookmarkContent(bodyPart); + } + + /** + * 文件转流 + * + * @param wordNewUrl + * @return + */ + public byte[] getBytesByFile(String wordNewUrl) { + try { +// byte[] bytes = Files.readAllBytes(Paths.get(wordNewUrl)); + File file = new File(wordNewUrl); + FileInputStream fis = new FileInputStream(file); + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + byte[] b = new byte[1024]; + int len = -1; + while ((len = fis.read(b)) != -1) { + bos.write(b, 0, len); + } + fis.close(); + bos.close(); + byte[] bytes = bos.toByteArray(); + System.out.println("successful..."); + return bytes; + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + /** + * 流转文件 + * + * @param buf 流字节数组 + * @param filePath 新文件路径 + * @param fileName 新文件名称 + */ + public void byte2File(byte[] buf, String filePath, String fileName) { + BufferedOutputStream bos = null; + FileOutputStream fos = null; + File file = null; + try { + File dir = new File(filePath); + if (!dir.exists() && dir.isDirectory()) { + dir.mkdirs(); + } + file = new File(filePath + File.separator + fileName); + fos = new FileOutputStream(file); + bos = new BufferedOutputStream(fos); + bos.write(buf); + } catch (Exception e) { + e.printStackTrace(); + } finally { + if (bos != null) { + try { + bos.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + if (fos != null) { + try { + fos.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + } + + /** + * word转PDF + * + * @param wordNewUrl word文件路径 + * @param pdfNewUrl 存储新PDF文件路径 + */ + public static void wordToPdf(String wordNewUrl, String pdfNewUrl) { +// 将新Word文档转换为PDF文件 + Document document = new Document(); + document.loadFromFile(wordNewUrl); + document.saveToFile(pdfNewUrl, FileFormat.PDF); + document.dispose(); +// log.info("文档转换结束,新PDF文档地址:{}",pdfNewUrl); + } + + + /** + * 图片透明背景转换 + * + * @param imgsrc + * @param alpha + * @return + */ + public static BufferedImage img_alpha(BufferedImage imgsrc, int alpha) { + try { + //创建一个包含透明度的图片,半透明效果必须要存储为png合适才行,存储为jpg,底色为黑色 + BufferedImage back = new BufferedImage(imgsrc.getWidth(), imgsrc.getHeight(), BufferedImage.TYPE_INT_ARGB); + int width = imgsrc.getWidth(); + int height = imgsrc.getHeight(); + for (int j = 0; j < height; j++) { + for (int i = 0; i < width; i++) { + int rgb = imgsrc.getRGB(i, j); + Color color = new Color(rgb); + Color newcolor = new Color(color.getRed(), color.getGreen(), color.getBlue(), alpha); + back.setRGB(i, j, newcolor.getRGB()); + } + } + return back; + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + //读取图片 + public static BufferedImage file2img(String imgpath) { + try { + BufferedImage bufferedImage = ImageIO.read(new File(imgpath)); + return bufferedImage; + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + //保存图片,extent为格式,"jpg"、"png"等 + public static void img2file(BufferedImage img, String extent, String newfile) { + try { + ImageIO.write(img, extent, new File(newfile)); + } catch (Exception e) { + e.printStackTrace(); + } + } + + + /** + * 按照模板 填充数据生成word 只支持docx + * + * @param templatePath 模板文件路径 + * @param temDir 生成文件的目录 + * @param fileName 生成文件名 + * @param params 参数 + */ + public static String exportWord(String templatePath, String temDir, String fileName, Map params) { + Assert.notNull(templatePath, "模板路径不能为空"); + Assert.notNull(temDir, "临时文件路径不能为空"); + Assert.notNull(fileName, "导出文件名不能为空"); + Assert.isTrue(fileName.endsWith(".docx"), "word导出请使用docx格式"); + if (!temDir.endsWith("/")) { + temDir = temDir + File.separator; + } + File dir = new File(temDir); + if (!dir.getParentFile().exists()) { + // 新建文件夹 + dir.getParentFile().mkdirs(); + } + String tmpPath = ""; + try { + XWPFDocument doc = WordExportUtil.exportWord07(templatePath, params); + tmpPath = temDir + fileName; + FileOutputStream fos = new FileOutputStream(tmpPath); + doc.write(fos); + fos.flush(); + fos.close(); + } catch (Exception e) { + e.printStackTrace(); + } + return tmpPath; + } + + /** + * 按照模板 填充数据生成word 只支持docx + * + * @param templatePath 模板文件路径 + * @param temDir 生成文件的目录 + * @param fileName 生成文件名 + * @param params 填充参数 + */ + public static void generateReport(String templatePath, String temDir, + String fileName, Map params, + String stampImgUrl, String stampImgUrl1, + String wordNewUrl, String keyWord, + Integer keyWordIndex, Float horizontal, + Float vertical, Float stampWidth, + Float stampHeight, String pdfNewUrl) { + //1、按照模板填充数据,并导出word + String wordOldUrl = exportWord(templatePath, temDir, fileName, params); + //2、照片背景透明设置 + //2.1签章背景透明设置 + BufferedImage bi = file2img(stampImgUrl); + BufferedImage bii = img_alpha(bi, alpha); + String newPngPath = stampImgUrl.substring(0, stampImgUrl.length() - 4) + "1.png"; + img2file(bii, "PNG", newPngPath); + //2.2签名背景透明设置 + BufferedImage b = file2img(stampImgUrl1); + BufferedImage b0 = img_alpha(b, alpha); + String newPngPath1 = stampImgUrl.substring(0, stampImgUrl1.length() - 4) + "1.png"; + img2file(b0, "PNG", newPngPath1); + + //3、添加签章和签名 + addKeyWordStamp(wordOldUrl, wordNewUrl, newPngPath, newPngPath1, keyWord, keyWordIndex, + horizontal, vertical, stampWidth, stampHeight); + // 4、将新word转化为pdf文件 + wordToPdf(wordNewUrl, pdfNewUrl); + } + + + public static void main(String[] args) { + + //文件与BufferedImage间的转换 + //读取图片 + BufferedImage bi = file2img("C:\\upload\\word\\sign.png"); + BufferedImage bii = img_alpha(bi, alpha); + //生成透明背景图片 + img2file(bii, "PNG", "C:\\upload\\word\\sign1.png"); + + //文件与BufferedImage间的转换 + //读取图片 + BufferedImage b = file2img("C:\\upload\\word\\name.png"); + BufferedImage b0 = img_alpha(b, alpha); + //生成透明背景图片 + img2file(b0, "PNG", "C:\\upload\\word\\name1.png"); + + // 目标文件地址 + String wordOldUrl = "C:\\upload\\word\\wordExport.docx"; + // 添加电子印章后文件存放地址 + String wordNewUrl = "C:\\upload\\word\\tem2.docx"; + //WORD转PDF存放位置 + String pdfNewUrl = "C:\\upload\\word\\tem2.pdf"; + //电子印章图片地址 + String stampImgUrl = "C:\\upload\\word\\sign1.png"; + //电子签名图片地址 + String stampImgUrl1 = "C:\\upload\\word\\name1.png"; + // word文档内容关键字 + String keyWord = "盖章"; + StampUtils addStampUtils = new StampUtils(); + //获取关键字位置并加盖印章并替换书签名位置文本内容 + addStampUtils.addKeyWordStamp(wordOldUrl, wordNewUrl, + stampImgUrl, stampImgUrl1, + keyWord, keyWordIndex, + horizontal, vertical, + stampWidth, stampHeight); + // 将新word转化为pdf文件 + addStampUtils.wordToPdf(wordNewUrl, pdfNewUrl); + } +} \ No newline at end of file diff --git a/casic-metering-model/src/main/java/com/casic/missiles/dto/business/certificate/CertificateReportResponse.java b/casic-metering-model/src/main/java/com/casic/missiles/dto/business/certificate/CertificateReportResponse.java index b43617c..4581acf 100644 --- a/casic-metering-model/src/main/java/com/casic/missiles/dto/business/certificate/CertificateReportResponse.java +++ b/casic-metering-model/src/main/java/com/casic/missiles/dto/business/certificate/CertificateReportResponse.java @@ -1,6 +1,7 @@ package com.casic.missiles.dto.business.certificate; import com.alibaba.excel.annotation.ExcelIgnoreUnannotated; +import com.alibaba.excel.annotation.ExcelProperty; import com.alibaba.excel.annotation.write.style.ColumnWidth; import com.alibaba.excel.annotation.write.style.ContentRowHeight; import com.alibaba.excel.annotation.write.style.ContentStyle; @@ -28,73 +29,56 @@ private Long id; @ApiModelProperty(value = "证书报告编号", dataType = "String") + @ExcelProperty(value = "证书号", order = 0) private String certificateReportCode; @ApiModelProperty(value = "证书报告名称", dataType = "String") + @ExcelProperty(value = "证书名称", order = 1) private String certificateReportName; @ApiModelProperty(value = "样品编号", dataType = "String") + @ExcelProperty(value = "样品编号", order = 2) private String sampleNo; + @ApiModelProperty(value = "样品名称", dataType = "String") + @ExcelProperty(value = "样品名称", order = 3) private String sampleName; + @ApiModelProperty(value = "型号", dataType = "String") + @ExcelProperty(value = "型号", order = 4) private String sampleModel; + @ApiModelProperty(value = "出厂编号", dataType = "String") + @ExcelProperty(value = "出厂编号", order = 5) private String manufacturingNo; + @ApiModelProperty(value = "委托书编号", dataType = "String") + @ExcelProperty(value = "委托书编号", order = 6) private String orderCode; @ApiModelProperty(value = "检校专业", dataType = "String") @DictCodeField(message = "检校专业不合法", cacheName = MeterDictCode.CALIBRATION_MAJOR) private String calibrationMajor; -// @ApiModelProperty(value = "出具日期", dataType = "String") -// private String issuanceDate; -// -// -// @ApiModelProperty(value = "证书有效期", dataType = "String") -// private String expirationDate; -// -// @ApiModelProperty(value = "检定结果", dataType = "String") -// private String measureResult; -// -// -// @ApiModelProperty(value = "原始记录id", dataType = "Long") -// private Long originalRecordId; -// -// -// @ApiModelProperty(value = "可打印状态", dataType = "String") -// private String printStatus; -// -// -// @ApiModelProperty(value = "打印次数", dataType = "Integer") -// private Integer printNum; - - - @ApiModelProperty(value = "检定人员", dataType = "String") + @ApiModelProperty(value = "检定人员id", dataType = "String") private String measurePersonId; @ApiModelProperty(value = "检定人员名称", dataType = "String") + @ExcelProperty(value = "检定人员", order = 8) private String measurePersonName; @ApiModelProperty(value = "审批状态", dataType = "String") @DictCodeField(message = "审批状态不合法", cacheName = MeterDictCode.APPROVAL_STATUS) private String approvalStatus; -// @ApiModelProperty(value = "备注", dataType = "String") -// private String remark; -// -// private Long createUser; -// @ApiModelProperty(value = "创建时间", dataType = "String") + @ExcelProperty(value = "创建时间", order = 10) private String createTime; -// @ApiModelProperty(value = "检校专业名称", dataType = "String") -// private String calibrationMajorName; - @ApiModelProperty(value = "审批状态名称", dataType = "String") + @ExcelProperty(value = "审批状态", order = 9) private String approvalStatusName; /** @@ -120,6 +104,7 @@ private String measureCategory; @ApiModelProperty(value = "校验类别名称", dataType = "String") + @ExcelProperty(value = "校验类别", order = 7) private String measureCategoryName; diff --git a/casic-metering-model/src/main/java/com/casic/missiles/dto/business/originRecord/OriginRecordRequest.java b/casic-metering-model/src/main/java/com/casic/missiles/dto/business/originRecord/OriginRecordRequest.java index d2c2ec7..d2687bf 100644 --- a/casic-metering-model/src/main/java/com/casic/missiles/dto/business/originRecord/OriginRecordRequest.java +++ b/casic-metering-model/src/main/java/com/casic/missiles/dto/business/originRecord/OriginRecordRequest.java @@ -31,7 +31,7 @@ @ApiModelProperty(value = "创建人", dataType = "String") private String createUser; - @ApiModelProperty(value = "原始记录单id", dataType = "Long") + @ApiModelProperty(value = "委托书id", dataType = "Long") private Long id; @ApiModelProperty(value = "导出ids(查询不用传)", dataType = "List") diff --git a/casic-metering-service/src/main/java/com/casic/missiles/service/Impl/business/BusinessCertificateReportServiceImpl.java b/casic-metering-service/src/main/java/com/casic/missiles/service/Impl/business/BusinessCertificateReportServiceImpl.java index d03ab22..aabfac2 100644 --- a/casic-metering-service/src/main/java/com/casic/missiles/service/Impl/business/BusinessCertificateReportServiceImpl.java +++ b/casic-metering-service/src/main/java/com/casic/missiles/service/Impl/business/BusinessCertificateReportServiceImpl.java @@ -26,8 +26,6 @@ import com.casic.missiles.service.business.IBusinessCertificateReportService; import com.casic.missiles.service.business.IBusinessOriginalRecordService; import com.casic.missiles.service.flowable.ApprovalOperateService; -import com.casic.missiles.utils.ConvertUtils; -import com.casic.missiles.utils.DictCodeUtils; import com.casic.missiles.utils.NumberGeneratorUtil; import org.flowable.engine.RuntimeService; import org.flowable.engine.TaskService; @@ -68,8 +66,10 @@ private RuntimeService runtimeService; @Resource private IBaseExportService iBaseExportService; + /** * 保存证书报告信息 + * * @param certificateReport * @return */ @@ -77,7 +77,7 @@ public ReturnDTO saveCertificateReport(BusinessCertificateReport certificateReport) { initCertificateReport(certificateReport); - if(this.baseMapper.insert(certificateReport)>0) + if (this.baseMapper.insert(certificateReport) > 0) return ReturnUtil.success(); throw new BusinessException(BusinessExceptionEnum.HANDLE_FAILED); } @@ -90,9 +90,9 @@ @Override public ReturnDTO approvalDelete(ApprovalDeleteRequest request) { ReturnDTO returnDTO = approvalOperateService.delete(request); - if(ResponseData.DEFAULT_SUCCESS_CODE == returnDTO.getCode()){ + if (ResponseData.DEFAULT_SUCCESS_CODE == returnDTO.getCode()) { //删除数据库记录 - if(this.baseMapper.deleteById(request.getId()) > 0){ + if (this.baseMapper.deleteById(request.getId()) > 0) { return ReturnUtil.success(); } } @@ -101,7 +101,7 @@ @Override public ReturnDTO draftUpdate(BusinessCertificateReport certificateReport) { - if(this.baseMapper.updateById(certificateReport)>0){ + if (this.baseMapper.updateById(certificateReport) > 0) { return ReturnUtil.success(); } throw new BusinessException(BusinessExceptionEnum.HANDLE_FAILED); @@ -109,25 +109,27 @@ /** * 批量删除 + * * @param ids * @return */ @Override public ReturnDTO deleteBatchTraceSupplier(List ids) { - return baseMapper.deleteBatchIds(ids) > 0?ReturnUtil.success(): + return baseMapper.deleteBatchIds(ids) > 0 ? ReturnUtil.success() : ReturnUtil.failed("删除失败"); } /** * 证书报告详情 + * * @param id * @return */ @Override public BusinessCertificateReport certificateReportDetail(Long id) { BusinessCertificateReport certificateReport = this.baseMapper.selectById(id); - if(certificateReport.getOriginalRecordId()!=null){ + if (certificateReport.getOriginalRecordId() != null) { try { certificateReport.setBusinessOriginalRecord(originalRecordService.originalDetail(certificateReport.getOriginalRecordId())); } catch (Exception e) { @@ -139,6 +141,7 @@ /** * 提交证书报告 + * * @param request * @return */ @@ -148,10 +151,10 @@ String formId = request.getFormId(); //2.根据流程定义id启动流程实例 ReturnDTO returnDTO = baseApprovalService.processSubmit(formId, request.getId()); - if(ResponseData.DEFAULT_SUCCESS_CODE != returnDTO.getCode()){ + if (ResponseData.DEFAULT_SUCCESS_CODE != returnDTO.getCode()) { return returnDTO; } - ProcessInstance processInstance = (ProcessInstance)returnDTO.getData(); + ProcessInstance processInstance = (ProcessInstance) returnDTO.getData(); BusinessCertificateReport certificateReport = new BusinessCertificateReport(); certificateReport.setId(request.getId()); certificateReport.setApprovalStatus(ApprovalStatusEnum.UN_DRAFT); //非草稿状态 @@ -165,6 +168,7 @@ /** * 审批状态列表查询 + * * @param page * @param request * @return @@ -182,6 +186,7 @@ /** * 驳回后更新 + * * @param certificateReport * @return */ @@ -208,13 +213,14 @@ @Override public void originExport(CertificateReportApprovalRequest request, HttpServletResponse response) { try { - //toDo: -// List certificateReportResponses = this.certificateReport(request); -// for (OriginRecordResponse originRecordResponse : originExportList) { -// //字典值转换 -// DictCodeUtils.convertDictCodeToName(originRecordResponse); -// } -// iBaseExportService.exportExcel(response, CertificateReportResponse.class, originExportList, ExportEnum.CERTIFICATE_REPORT.getSheetName()); + //登录用户 + AuthUser user = ShiroKit.getUser(); + Assert.isFalse(Objects.isNull(user), () -> { + throw new BusinessException(BusinessExceptionEnum.LOGIN_USER_ACQUIRE_FAILED); + }); + request.setCreateUserId(user.getId()); + List reportResponseList= handleApprovalStatus(null, request); + iBaseExportService.exportExcel(response, CertificateReportResponse.class, reportResponseList, ExportEnum.CERTIFICATE_REPORT.getSheetName()); } catch (Exception e) { log.error("证书报告导出出现异常,异常信息为{}", e); } @@ -231,15 +237,15 @@ //待审批,该状态维护在flowable中 case ApprovalStatusEnum.TO_BE_APPROVED: List toBeApprovedList = baseApprovalService.getToBeApprovedList(request.getFormId()); - if(!CollectionUtils.isEmpty(toBeApprovedList)){ + if (!CollectionUtils.isEmpty(toBeApprovedList)) { businessKeys = toBeApprovedList.stream().map(ToBeApprovedDTO::getBusinessKey).distinct().collect(Collectors.toList()); } - if(!CollectionUtils.isEmpty(businessKeys)){ + if (!CollectionUtils.isEmpty(businessKeys)) { approvalList = handleApprovalListResponse(this.baseMapper.selectBatchForApproval(page, request, businessKeys), ApprovalStatusEnum.TO_BE_APPROVED); //DTO根据业务主键补全taskId approvalList.forEach(approval -> { toBeApprovedList.forEach(toBeApprovedDTO -> { - if(String.valueOf(approval.getId()).equals(toBeApprovedDTO.getBusinessKey())){ + if (String.valueOf(approval.getId()).equals(toBeApprovedDTO.getBusinessKey())) { approval.setTaskId(toBeApprovedDTO.getTaskId()); //补全可选决策项 approval.setDecisionItem(toBeApprovedDTO.getDecisionItem()); @@ -251,27 +257,27 @@ //审批中,该状态维护在flowable中 case ApprovalStatusEnum.IN_APPROVED: businessKeys = baseApprovalService.getInApprovedList(request.getFormId()); - if(!CollectionUtils.isEmpty(businessKeys)){ + if (!CollectionUtils.isEmpty(businessKeys)) { approvalList = handleApprovalListResponse(this.baseMapper.selectBatchForApproval(page, request, businessKeys), ApprovalStatusEnum.IN_APPROVED); } break; //已通过,该状态维护在flowable case ApprovalStatusEnum.PASSED: businessKeys = baseApprovalService.getPassedList(request.getFormId()); - if(!CollectionUtils.isEmpty(businessKeys)){ - approvalList = handleApprovalListResponse( this.baseMapper.selectBatchForApproval(page, request, businessKeys), ApprovalStatusEnum.PASSED); + if (!CollectionUtils.isEmpty(businessKeys)) { + approvalList = handleApprovalListResponse(this.baseMapper.selectBatchForApproval(page, request, businessKeys), ApprovalStatusEnum.PASSED); } break; //未通过(包括拒绝、驳回,拒绝为直接删除实例,驳回为驳回到起点),该状态维护在flowable case ApprovalStatusEnum.FAILED: businessKeys = baseApprovalService.getFailedList(request.getFormId()); //未通过-拒绝 List rejectBusinessKey = baseApprovalService.getFailedRejectList(request.getFormId()); //未通过-驳回 - if(!CollectionUtils.isEmpty(businessKeys)){ + if (!CollectionUtils.isEmpty(businessKeys)) { approvalList = handleApprovalListResponse(this.baseMapper.selectBatchForApproval(page, request, businessKeys), ApprovalStatusEnum.FAILED); } List rejectApprovalList = new ArrayList<>(); - if(!CollectionUtils.isEmpty(rejectBusinessKey)){ - rejectApprovalList = handleApprovalListResponse( this.baseMapper.selectBatchForApproval(page, request, rejectBusinessKey), ApprovalStatusEnum.FAILED_REJECT); + if (!CollectionUtils.isEmpty(rejectBusinessKey)) { + rejectApprovalList = handleApprovalListResponse(this.baseMapper.selectBatchForApproval(page, request, rejectBusinessKey), ApprovalStatusEnum.FAILED_REJECT); } //合并未通过-拒绝和未通过-驳回 approvalList.addAll(rejectApprovalList); @@ -279,7 +285,7 @@ //已取消(直接删除实例),该状态维护在flowable case ApprovalStatusEnum.CANCELED: businessKeys = baseApprovalService.getCanceledList(request.getFormId()); - if(!CollectionUtils.isEmpty(businessKeys)){ + if (!CollectionUtils.isEmpty(businessKeys)) { approvalList = handleApprovalListResponse(this.baseMapper.selectBatchForApproval(page, request, businessKeys), ApprovalStatusEnum.CANCELED); } break; @@ -288,10 +294,10 @@ //普通用户获取自己发起的(审批中、已通过、未通过、已取消),管理员获取全部(审批中、已通过、未通过、已取消) case ApprovalStatusEnum.ALL: List AllApproveList = baseApprovalService.getAllList(request.getFormId()); - if(!CollectionUtils.isEmpty(AllApproveList)){ + if (!CollectionUtils.isEmpty(AllApproveList)) { businessKeys = AllApproveList.stream().map(AllApproveDTO::getBusinessKey).collect(Collectors.toList()); } - if(!CollectionUtils.isEmpty(businessKeys)){ + if (!CollectionUtils.isEmpty(businessKeys)) { approvalList = handleAllApprovalListResponse(this.baseMapper.selectBatchForApproval(page, request, businessKeys), AllApproveList); } break; @@ -299,9 +305,11 @@ return approvalList; } - private List handleAllApprovalListResponse(List approvalList, List allApproveList) { - Map taskMap = new HashMap<>(); - allApproveList.forEach(allApprove -> {taskMap.put(allApprove.getBusinessKey(),allApprove.getStatus());}); + private List handleAllApprovalListResponse(List approvalList, List allApproveList) { + Map taskMap = new HashMap<>(); + allApproveList.forEach(allApprove -> { + taskMap.put(allApprove.getBusinessKey(), allApprove.getStatus()); + }); //状态补全 approvalList.forEach(approval -> { approval.setApprovalStatusName(dictService.getDictNameByCode(MeterDictEnum.APPROVAL_STATUS, taskMap.get(String.valueOf(approval.getId())))); @@ -313,7 +321,7 @@ return approvalList.stream().sorted(Comparator.comparing(CertificateReportResponse::getCreateTime).reversed()).collect(Collectors.toList()); } - private List handleApprovalListResponse(List approvalList, String status){ + private List handleApprovalListResponse(List approvalList, String status) { approvalList.stream().forEach(result -> { //审批状态两种获取方式:1、在此处设置,2、在flowable中设置业务状态,暂采取1 result.setApprovalStatusName(dictService.getDictNameByCode(MeterDictEnum.APPROVAL_STATUS, status)); @@ -324,14 +332,14 @@ private void initCertificateReport(BusinessCertificateReport certificateReport) { String prefix = MonitorCodeEnum.getByCode(certificateReport.getCalibrationMajor()).getValue() - +DateUtil.format(new Date(),"YYYYMM"); + + DateUtil.format(new Date(), "YYYYMM"); Long maxNo = this.baseMapper.selectMaxCode(prefix); //生成证书编号 - String certificateReportNo =NumberGeneratorUtil.getCode( - MonitorCodeEnum.getByCode(certificateReport.getCalibrationMajor()).getValue(),maxNo); + String certificateReportNo = NumberGeneratorUtil.getCode( + MonitorCodeEnum.getByCode(certificateReport.getCalibrationMajor()).getValue(), maxNo); AuthUser authUser = ShiroKit.getUser(); certificateReport.setCreateUser(authUser.getId()); - certificateReport.setMeasurePersonId(authUser.getId()+""); + certificateReport.setMeasurePersonId(authUser.getId() + ""); certificateReport.setMeasureDeptId(authUser.getDeptId()); certificateReport.setCertificateReportCode(certificateReportNo); } diff --git a/casic-metering-service/src/main/java/com/casic/missiles/service/Impl/business/BusinessOrderServiceImpl.java b/casic-metering-service/src/main/java/com/casic/missiles/service/Impl/business/BusinessOrderServiceImpl.java index f5c6f61..21ab8b6 100644 --- a/casic-metering-service/src/main/java/com/casic/missiles/service/Impl/business/BusinessOrderServiceImpl.java +++ b/casic-metering-service/src/main/java/com/casic/missiles/service/Impl/business/BusinessOrderServiceImpl.java @@ -90,8 +90,10 @@ List customerSampleList = new ArrayList<>(); for (BusinessOrderSampleRelation orderSample : orderSampleList) { CustomerSampleInfo customerSampleInfo = customerSampleService.sampleDetail(orderSample.getSampleId()); - customerSampleInfo.setIsExistSample("1"); - customerSampleList.add(customerSampleInfo); + if (null != customerSampleInfo) { + customerSampleInfo.setIsExistSample("1"); + customerSampleList.add(customerSampleInfo); + } } businessOrder.setCustomerSampleInfoList(customerSampleList); return businessOrder; diff --git a/casic-metering-service/src/main/java/com/casic/missiles/service/Impl/business/BusinessOriginalRecordServiceImpl.java b/casic-metering-service/src/main/java/com/casic/missiles/service/Impl/business/BusinessOriginalRecordServiceImpl.java index 1e35b7a..1c602b8 100644 --- a/casic-metering-service/src/main/java/com/casic/missiles/service/Impl/business/BusinessOriginalRecordServiceImpl.java +++ b/casic-metering-service/src/main/java/com/casic/missiles/service/Impl/business/BusinessOriginalRecordServiceImpl.java @@ -131,7 +131,7 @@ @Override public ReturnDTO updateOriginal(BusinessOriginalRecord businessOriginalRecord) { - if (this.baseMapper.insert(businessOriginalRecord) > 0) { + if (this.baseMapper.updateById(businessOriginalRecord) > 0) { //加入技术文件绑定 if (ObjectUtil.isNotEmpty(businessOriginalRecord.getFileList()) && businessOriginalRecord.getFileList().size() > 0) { originalRecordFileRelationService.saveBatch(businessOriginalRecord.getId(), businessOriginalRecord.getFileList()); diff --git a/casic-metering-api/src/main/java/com/casic/missiles/controller/business/BusinessCertificateReportController.java b/casic-metering-api/src/main/java/com/casic/missiles/controller/business/BusinessCertificateReportController.java index c440253..408b580 100644 --- a/casic-metering-api/src/main/java/com/casic/missiles/controller/business/BusinessCertificateReportController.java +++ b/casic-metering-api/src/main/java/com/casic/missiles/controller/business/BusinessCertificateReportController.java @@ -9,17 +9,13 @@ import com.casic.missiles.dto.business.certificate.CertificateReportApprovalRequest; import com.casic.missiles.dto.business.certificate.CertificateReportResponse; import com.casic.missiles.dto.flowable.ApprovalDeleteRequest; -import com.casic.missiles.dto.meter.TraceSupplierListRequest; import com.casic.missiles.enums.BusinessExceptionEnum; import com.casic.missiles.exception.BusinessException; import com.casic.missiles.model.business.BusinessCertificateReport; import com.casic.missiles.model.exception.enums.CoreExceptionEnum; -import com.casic.missiles.model.meter.MeterTraceSupplier; import com.casic.missiles.service.business.IBusinessCertificateReportService; -import com.casic.missiles.service.meter.IMeterTraceSupplierService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.util.CollectionUtils; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.*; @@ -45,28 +41,7 @@ public class BusinessCertificateReportController extends ExportController { @Resource private IBusinessCertificateReportService certificateReportService; - @Autowired - private IMeterTraceSupplierService traceSupplierService; - @ApiOperation("证书报告列表(分页)") - @PostMapping("/listPage") - @ResponseBody - public ReturnDTO> supplierListPage(@RequestBody @Valid TraceSupplierListRequest request, BindingResult bindingResult) { - if (bindingResult.hasErrors()) { - throw new BusinessException(CoreExceptionEnum.REQUEST_NULL.getCode(), bindingResult.getFieldError().getDefaultMessage()); - } - Page page = PageFactory.defaultPage(); - return ReturnUtil.success(super.packForBT(traceSupplierService.listPage(page, request))); - } - @ApiOperation("证书报告列表") - @PostMapping("/list") - @ResponseBody - public ReturnDTO> supplierList(@RequestBody @Valid TraceSupplierListRequest request, BindingResult bindingResult) { - if (bindingResult.hasErrors()) { - throw new BusinessException(CoreExceptionEnum.REQUEST_NULL.getCode(), bindingResult.getFieldError().getDefaultMessage()); - } - return ReturnUtil.success(traceSupplierService.list(request)); - } @ApiOperation("证书报告记录导出") @PostMapping("/listExport") @@ -113,18 +88,6 @@ return certificateReportService.submitCertificateReport(request); } - @ApiOperation("证书报告更新(审批通过后还能更新??暂时保留。。)") - @PostMapping("/update") - @ResponseBody - public ReturnDTO supplierUpdate(@RequestBody @Valid MeterTraceSupplier traceSupplier, BindingResult bindingResult) { - Assert.isFalse(Objects.isNull(traceSupplier.getId()), () -> { - throw new BusinessException(BusinessExceptionEnum.ID_NULL); - }); - Assert.isFalse(bindingResult.hasErrors(), () -> { - throw new BusinessException(CoreExceptionEnum.REQUEST_NULL.getCode(), bindingResult.getFieldError().getDefaultMessage()); - }); - return traceSupplierService.updateTraceSupplier(traceSupplier); - } @ApiOperation("证书报告批量删除") @PostMapping("/batchDelete") diff --git a/casic-metering-api/src/main/java/com/casic/missiles/controller/system/PoiController.java b/casic-metering-api/src/main/java/com/casic/missiles/controller/system/PoiController.java index 021eaa8..9848e68 100644 --- a/casic-metering-api/src/main/java/com/casic/missiles/controller/system/PoiController.java +++ b/casic-metering-api/src/main/java/com/casic/missiles/controller/system/PoiController.java @@ -3,12 +3,14 @@ import cn.afterturn.easypoi.entity.ImageEntity; import com.casic.missiles.utils.PdfUtil; +import com.casic.missiles.utils.StampUtils; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.stereotype.Controller; import org.springframework.util.Assert; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpServletResponse; import java.io.*; @@ -23,7 +25,51 @@ private String filepath="C:\\upload"; @ApiOperation("word转pdf") + @PostMapping(value = "/convertWordToPdf1") + @ResponseBody + public void convertWordToPdf1() throws Exception { + File uploadFile = new File(filepath); + String wordDir = ""; + if (!uploadFile.exists()) { + uploadFile.mkdirs(); + } + if (!filepath.endsWith("/")) { + wordDir = filepath + File.separator + "word"; + } + File tf = new File(wordDir + File.separator + "tem.docx"); + File tf_pic = new File(wordDir + File.separator + "logo.jpg"); + String pic_url = tf_pic.getCanonicalPath(); + Calendar now = Calendar.getInstance(); + Map params = new HashMap<>(); + List> dataList=new ArrayList<>(); + for (int i = 0; i < 5; i++) { + Map param = new HashMap<>(); + param.put("name", "彭于晏"+i); + param.put("sex", "男"+i); + param.put("address", "中国"+i); + ImageEntity image = new ImageEntity(); + image.setHeight(100); + image.setWidth(100); + image.setUrl(pic_url); + image.setData(PdfUtil.getImageBase64(pic_url)); + param.put("image", image); + dataList.add(param); + } + + params.put("dataList",dataList); + params.put("y", now.get(Calendar.YEAR)); + params.put("m", (now.get(Calendar.MONTH) + 1)); + params.put("d", now.get(Calendar.DAY_OF_MONTH)); + + String fileName = "wordExport.docx"; + String word = StampUtils.exportWord(tf.getPath(), wordDir, fileName, params); + System.out.println("****新模板"+word); + + } + + @ApiOperation("word转pdf") @PostMapping(value = "/convertWordToPdf") + @ResponseBody public void convertWordToPdf(HttpServletResponse response) throws Exception { File uploadFile = new File(filepath); String wordDir = ""; @@ -117,4 +163,5 @@ } } } + } diff --git a/casic-metering-common/pom.xml b/casic-metering-common/pom.xml index bb00ab9..e028713 100644 --- a/casic-metering-common/pom.xml +++ b/casic-metering-common/pom.xml @@ -11,6 +11,7 @@ casic-metering-common + @@ -171,6 +172,14 @@ 4.1.2 + + + + e-iceblue + spire.office.free + 5.3.1 + + com.google.zxing diff --git a/casic-metering-common/src/main/java/com/casic/missiles/utils/CustomXWPFDocumentUtil.java b/casic-metering-common/src/main/java/com/casic/missiles/utils/CustomXWPFDocumentUtil.java deleted file mode 100644 index 9e7ed3f..0000000 --- a/casic-metering-common/src/main/java/com/casic/missiles/utils/CustomXWPFDocumentUtil.java +++ /dev/null @@ -1,309 +0,0 @@ -package com.casic.missiles.utils; - -import java.io.*; -import java.util.*; -import java.util.Map.Entry; - -import cn.afterturn.easypoi.entity.ImageEntity; -import org.apache.commons.lang3.StringUtils; -import org.apache.poi.ooxml.POIXMLDocument; -import org.apache.poi.openxml4j.exceptions.InvalidFormatException; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.util.Units; -import org.apache.poi.xwpf.usermodel.*; -import org.apache.xmlbeans.XmlException; -import org.apache.xmlbeans.XmlToken; -import org.openxmlformats.schemas.drawingml.x2006.main.CTGraphicalObject; -import org.openxmlformats.schemas.drawingml.x2006.main.CTNonVisualDrawingProps; -import org.openxmlformats.schemas.drawingml.x2006.main.CTPositiveSize2D; -import org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.CTAnchor; -import org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.CTInline; -import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTDrawing; - -public class CustomXWPFDocumentUtil extends XWPFDocument { - - public CustomXWPFDocumentUtil(InputStream in) throws IOException { - super(in); - } - - public CustomXWPFDocumentUtil() { - super(); - } - - public CustomXWPFDocumentUtil(OPCPackage pkg) throws IOException { - super(pkg); - } - - /** - * 根据指定的参数值、模板,生成 word 文档 - * - * @param param 需要替换的变量 - * @param template 模板 - */ - public static XWPFDocument generateWord(Map param, String template) { - XWPFDocument doc = null; - try { - OPCPackage pack = POIXMLDocument.openPackage(template); - doc = new CustomXWPFDocumentUtil(pack); - if (param != null && param.size() > 0) { - - //处理段落 - List paragraphList = doc.getParagraphs(); - processParagraphs(paragraphList, param, doc); - - //处理表格 - Iterator it = doc.getTablesIterator(); - while (it.hasNext()) { - XWPFTable table = it.next(); - List rows = table.getRows(); - for (XWPFTableRow row : rows) { - List cells = row.getTableCells(); - for (XWPFTableCell cell : cells) { - List paragraphListTable = cell.getParagraphs(); - processParagraphs(paragraphListTable, param, doc); - } - } - } - } - } catch (IOException e) { - e.printStackTrace(); - } catch (Exception e) { - e.printStackTrace(); - } - return doc; - } - - /** - * 处理段落 - * - * @param paragraphList - * @param - * @throws FileNotFoundException - * @throws InvalidFormatException - */ - public static void processParagraphs(List paragraphList, Map param, XWPFDocument doc) throws InvalidFormatException, FileNotFoundException { - if (paragraphList != null && paragraphList.size() > 0) { - for (XWPFParagraph paragraph : paragraphList) { - List runs = paragraph.getRuns(); - for (XWPFRun run : runs) { - String text = run.getText(0); - //System.out.println("text=="+text); - if (text != null) { - boolean isSetText = false; - for (Entry entry : param.entrySet()) { - String key = entry.getKey(); - if (text.indexOf(key) != -1) { - isSetText = true; - Object value = entry.getValue(); - if (value instanceof String) {//文本替换 - //System.out.println("key=="+key); - text = text.replace(key, value.toString()); - } else if (value instanceof Map) { //图片替换 - text = text.replace(text, ""); - Map pic = (Map) value; - int width = Integer.parseInt(pic.get("width").toString()); - int height = Integer.parseInt(pic.get("height").toString()); - int picType = getPictureType(pic.get("type").toString()); - String picPath = (String) pic.get("picPath"); - CTInline inline = run.getCTR().addNewDrawing().addNewInline(); - insertPicture(doc, picPath, inline, width, height); - CTDrawing drawing = run.getCTR().getDrawingArray(0); - CTGraphicalObject graphicalobject = drawing.getInlineArray(0).getGraphic(); - //拿到新插入的图片替换添加CTAnchor 设置浮动属性 删除inline属性 - CTAnchor anchor = getAnchorWithGraphic(graphicalobject, "11", - Units.toEMU(width), Units.toEMU(height),//图片大小 - Units.toEMU(0), Units.toEMU(0));//相对当前段落位置的偏移位置,左右偏移:负数向左,正数向右,上下偏移:负数向上,正数向下 - drawing.setAnchorArray(new CTAnchor[]{anchor});//添加浮动属性 - drawing.removeInline(0);//删除行内属性 - } - } - } - if (isSetText) { - run.setText(text, 0); - } - } - } - } - } - } - - /** - * 根据图片类型,取得对应的图片类型代码 - * - * @param picType - * @return int - */ - private static int getPictureType(String picType) { - int res = CustomXWPFDocumentUtil.PICTURE_TYPE_PICT; - if (picType != null) { - if (picType.equalsIgnoreCase("png")) { - res = CustomXWPFDocumentUtil.PICTURE_TYPE_PNG; - } else if (picType.equalsIgnoreCase("dib")) { - res = CustomXWPFDocumentUtil.PICTURE_TYPE_DIB; - } else if (picType.equalsIgnoreCase("emf")) { - res = CustomXWPFDocumentUtil.PICTURE_TYPE_EMF; - } else if (picType.equalsIgnoreCase("jpg") || picType.equalsIgnoreCase("jpeg")) { - res = CustomXWPFDocumentUtil.PICTURE_TYPE_JPEG; - } else if (picType.equalsIgnoreCase("wmf")) { - res = CustomXWPFDocumentUtil.PICTURE_TYPE_WMF; - } - } - return res; - } - - /** - * insert Picture - * - * @param document - * @param filePath - * @param inline - * @param width - * @param height - * @throws InvalidFormatException - * @throws FileNotFoundException - */ - private static void insertPicture(XWPFDocument document, String filePath, - CTInline inline, int width, - int height) throws InvalidFormatException, - FileNotFoundException { - document.addPictureData(new FileInputStream(filePath), XWPFDocument.PICTURE_TYPE_PNG); - int id = document.getAllPictures().size() - 1; - final int EMU = 9525; - width *= EMU; - height *= EMU; - String blipId = - document.getAllPictures().get(id).getRelationId(document); - String picXml = getPicXml(blipId, width, height); - XmlToken xmlToken = null; - try { - xmlToken = XmlToken.Factory.parse(picXml); - } catch (XmlException xe) { - xe.printStackTrace(); - } - inline.set(xmlToken); - inline.setDistT(0); - inline.setDistB(0); - inline.setDistL(0); - inline.setDistR(0); - CTPositiveSize2D extent = inline.addNewExtent(); - extent.setCx(width); - extent.setCy(height); - CTNonVisualDrawingProps docPr = inline.addNewDocPr(); - docPr.setId(id); - docPr.setName("IMG_" + id); - docPr.setDescr("IMG_" + id); - } - - /** - * get the xml of the picture - * - * @param blipId - * @param width - * @param height - * @return - */ - private static String getPicXml(String blipId, int width, int height) { - String picXml = - "" + "" + - " " + - " " + - " " + " " + " " + - " " + " " + - " " + - " " + " " + - " " + " " + - " " + " " + - " " + - " " + " " + - " " + - " " + " " + - " " + " " + - " " + ""; - return picXml; - } - - /** - * @param ctGraphicalObject 图片数据 - * @param deskFileName 图片描述 - * @param width 宽 - * @param height 高 - * @param leftOffset 水平偏移:负数向左,正数向右 - * @param topOffset 垂直偏移:负数向上,正数向下 - * @return CTAnchor - * @throws Exception - */ - public static CTAnchor getAnchorWithGraphic(CTGraphicalObject ctGraphicalObject, - String deskFileName, int width, int height, - int leftOffset, int topOffset) { - //浮在文字上的设置主要是anchor标签下的behindDoc属性设为0,同时添加一个的空标签。 - if (StringUtils.isBlank(deskFileName)) { - deskFileName = new Random().nextInt(999) + "";//描述不能为空,赋值一个随机数 - } - String anchorXML = - "" - + "" - + "" - + "" + leftOffset + "" - + "" - + "" - + "" + topOffset + "" + - "" - + "" - + "" - + "" - + "" - + ""; - CTDrawing drawing = null; - try { - drawing = CTDrawing.Factory.parse(anchorXML); - } catch (XmlException e) { - e.printStackTrace(); - } - CTAnchor anchor = drawing.getAnchorArray(0); - anchor.setGraphic(ctGraphicalObject); - return anchor; - } - public static void main(String[] args) throws IOException{ - Map params = new HashMap<>(); - List> dataList=new ArrayList<>(); - for (int i = 0; i < 5; i++) { - Map param = new HashMap<>(); - param.put("name", "彭于晏"+i); - param.put("sex", "男"+i); - param.put("address", "中国"+i); - ImageEntity image = new ImageEntity(); - image.setHeight(100); - image.setWidth(100); - image.setUrl("C:\\upload\\word\\"); - image.setData(PdfUtil.getImageBase64("C:\\upload\\word\\logo.jpg")); - param.put("image", image); - dataList.add(param); - } - Calendar now = Calendar.getInstance(); - params.put("dataList",dataList); - params.put("y", now.get(Calendar.YEAR)+""); - params.put("m", (now.get(Calendar.MONTH) + 1)+""); - params.put("d", now.get(Calendar.DAY_OF_MONTH)+""); - String template="C:\\upload\\word\\tem.docx"; - ByteArrayOutputStream baos = null; - try { - XWPFDocument document = generateWord(params, template); - baos = new ByteArrayOutputStream(); - document.write(baos);//临时存储流到内存 - baos.flush(); - } catch (Exception e) { - e.printStackTrace(); - }finally{ - if(baos != null){ - baos.close(); - } - } - - - } - -} diff --git a/casic-metering-common/src/main/java/com/casic/missiles/utils/PdfUtil.java b/casic-metering-common/src/main/java/com/casic/missiles/utils/PdfUtil.java index 3d80a8e..3e4f58b 100644 --- a/casic-metering-common/src/main/java/com/casic/missiles/utils/PdfUtil.java +++ b/casic-metering-common/src/main/java/com/casic/missiles/utils/PdfUtil.java @@ -23,12 +23,12 @@ public class PdfUtil { /** - * 生成word 只支持docx + * 按照模板 填充数据生成word 只支持docx * * @param templatePath 模板文件路径 - * @param temDir 生成文件的目录 - * @param fileName 生成文件名 - * @param params 参数 + * @param temDir 生成文件的目录 + * @param fileName 生成文件名 + * @param params 参数 */ public static String exportWord(String templatePath, String temDir, String fileName, Map params) { Assert.notNull(templatePath, "模板路径不能为空"); @@ -39,8 +39,9 @@ temDir = temDir + File.separator; } File dir = new File(temDir); - if (!dir.exists()) { - dir.mkdirs(); + if (!dir.getParentFile().exists()) { + // 新建文件夹 + dir.getParentFile().mkdirs(); } String tmpPath = ""; try { @@ -51,13 +52,13 @@ fos.flush(); fos.close(); } catch (Exception e) { - //e.printStackTrace(); + e.printStackTrace(); } return tmpPath; } - public static String convertDocx2Pdf(String wordPath,String pdfPath) { + public static String convertDocx2Pdf(String wordPath, String pdfPath) { OutputStream os = null; InputStream is = null; try { diff --git a/casic-metering-common/src/main/java/com/casic/missiles/utils/PictureUtil.java b/casic-metering-common/src/main/java/com/casic/missiles/utils/PictureUtil.java deleted file mode 100644 index 4baa893..0000000 --- a/casic-metering-common/src/main/java/com/casic/missiles/utils/PictureUtil.java +++ /dev/null @@ -1,184 +0,0 @@ -//package com.casic.missiles.utils; -// -//import cn.hutool.core.codec.Base64; -//import com.alibaba.fastjson.JSONObject; -//import com.google.common.collect.Lists; -//import org.apache.poi.xwpf.usermodel.*; -//import org.apache.xmlbeans.XmlException; -//import org.openxmlformats.schemas.drawingml.x2006.main.CTGraphicalObject; -//import org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.CTAnchor; -//import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTDrawing; -// -//import java.io.*; -//import java.util.List; -//import java.util.Map; -//import java.util.Set; -// -//public class PictureUtil { -// public void create(String filePath, JSONObject jsonObject) { -// try { -// FileInputStream template = new FileInputStream(new File(filePath)); -// //获取docx解析对象 -// XWPFDocument document = new XWPFDocument(template); -// List tableList = Lists.newArrayList(); -// -// //解析替换表格对象 -// List tables = document.getTables(); -// for (int i = 0; i < tables.size(); i++) { -// //只处理行数大于等于2的表格,且不循环表头 -// XWPFTable table = tables.get(i); -// if (table.getRows().size() > 1) { -// //判断表格是需要替换还是需要插入,判断逻辑有$为替换,表格无$为插入 -// if (WordUtil.checkText(table.getText())) { -// List rows = table.getRows(); -// //遍历表格,并替换模板 -// eachTable(rows, jsonObject); -// } -// } -// } -// -// // workBook写入输出流 -// ByteArrayOutputStream baos = new ByteArrayOutputStream(); -// document.write(baos); -// baos.flush(); -// } catch (Exception e) { -// e.printStackTrace(); -// } -// } -// /** -// * 遍历表格 -// * -// * @param rows 表格行对象 -// * @param textMap 需要替换的信息集合 -// */ -// public static void eachTable(List rows, JSONObject textMap) { -// for (XWPFTableRow row : rows) { -// List cells = row.getTableCells(); -// for (XWPFTableCell cell : cells) { -// //判断单元格是否需要替换 -// if (checkText(cell.getText())) { -// List paragraphs = cell.getParagraphs(); -// for (XWPFParagraph paragraph : paragraphs) { -// List runs = paragraph.getRuns(); -// for (XWPFRun run : runs) { -//// run.setText(changeValue(run.toString(), textMap), 0); -// //新增制证照片单独处理 -// if (run.toString().indexOf("${jpeg}") != -1 && textMap.containsKey("jpeg")){ -// addPic(run,textMap, 1188000, 1728000,0, 0); -// break; -// } -// String value = changeValue(run.toString(), textMap); -// setWrap(value, run); -// } -// } -// } -// } -// } -// } -// -// /** -// * 匹配传入信息集合与模板 -// * -// * @param value 模板需要替换的区域 -// * @param textMap 传入信息集合 -// * @return 模板需要替换区域信息集合对应值 -// */ -// public static String changeValue(String value, JSONObject textMap) { -// -// boolean flag = false; -// Set> textSets = textMap.entrySet(); -// for (Map.Entry textSet : textSets) { -// //匹配模板与替换值 格式${key} -// String key = "${" + textSet.getKey() + "}"; -// if (value.indexOf(key) != -1) { -// value = textSet.getValue() == null ? "" : ("" + textSet.getValue()); -// flag = true; -// break; -// } -// } -// //模板未匹配到区域替换为空 -// if (checkText(value)) { -// value = ""; -// } -// return value; -// } -// public static void setWrap(String value, XWPFRun run) { -// if ( value.indexOf("\n") > 0) { -// //设置换行 -// String[] text = value.split("\n"); -// for (int f = 0; f < text.length; f++) { -// if (f == 0) { -// run.setText(text[f].trim(),0); -// } else { -//// run.addCarriageReturn();//硬回车 -// // 换行 -// run.addBreak(); -// run.setText(text[f]); -// } -// } -// } else { -// run.setText((String) value,0); -// } -// } -// -// /** -// * @param ctGraphicalObject 图片数据 -// * @param deskFileName 图片描述 -// * @param width 宽 -// * @param height 高 -// * @param leftOffset 水平偏移 left -// * @param topOffset 垂直偏移 top -// * @param behind 文字上方,文字下方 -// * @return -// * @throws Exception -// */ -// public static CTAnchor getAnchorWithGraphic(CTGraphicalObject ctGraphicalObject, String deskFileName, int width, int height, int leftOffset, int topOffset, boolean behind) { -// String anchorXML ="" -// +"" -// +" " -// +" " -// +" "+ leftOffset + "" -// +" " -// +" " -// +" "+ topOffset +"" -// +" " -// +" " -// +" " -// +" " -// +" " -// +""; -// try { -// CTDrawing drawing = CTDrawing.Factory.parse(anchorXML); -// CTAnchor anchor = drawing.getAnchorArray(0); -// anchor.setGraphic(ctGraphicalObject); -// return anchor; -// } catch (XmlException e) { -// e.printStackTrace(); -// return null; -// } -// } -// -// /** -// * 新增制证照片单独处理 -// * @param run -// * @param textMap -// */ -// public static void addPic(XWPFRun run, JSONObject textMap, int width, int height, int leftOffset, int topOffset){ -// String runText = run.toString().trim(); -// byte[] zjzp = Base64.decode(textMap.getString("jpeg")); -// try(ByteArrayInputStream byteInputStream = new ByteArrayInputStream(zjzp)) { -// //1、添加图片 -// run.addPicture(byteInputStream,XWPFDocument.PICTURE_TYPE_JPEG,"照片", width, height); -// //2、获取图片 -// CTDrawing cTDrawing = run.getCTR().getDrawingArray(0); -// CTGraphicalObject cTGraphicalObject = cTDrawing.getInlineArray(0).getGraphic(); -// //3、设置属性 -// CTAnchor ctAnchor = getAnchorWithGraphic(cTGraphicalObject,"照片", width, height,leftOffset, topOffset,false); -// cTDrawing.setAnchorArray(new CTAnchor[]{ctAnchor}); -// cTDrawing.removeInline(0); -// run.setText(runText.replace("${jpeg}",""), 0); -// }catch (Exception e){ -// e.printStackTrace(); -// } -// } -//} diff --git a/casic-metering-common/src/main/java/com/casic/missiles/utils/StampUtils.java b/casic-metering-common/src/main/java/com/casic/missiles/utils/StampUtils.java new file mode 100644 index 0000000..fb6d4cf --- /dev/null +++ b/casic-metering-common/src/main/java/com/casic/missiles/utils/StampUtils.java @@ -0,0 +1,482 @@ +package com.casic.missiles.utils; + + +import cn.afterturn.easypoi.word.WordExportUtil; +import cn.hutool.core.lang.Assert; +import com.baomidou.mybatisplus.core.toolkit.ObjectUtils; +import com.spire.doc.*; +import com.spire.doc.documents.*; +import com.spire.doc.fields.DocPicture; +import com.spire.doc.fields.TextRange; +import org.apache.commons.lang3.StringUtils; +import org.apache.poi.xwpf.usermodel.XWPFDocument; + +import javax.imageio.ImageIO; +import java.awt.*; +import java.awt.image.BufferedImage; +import java.io.*; +import java.util.Map; + +/** + * @Author:zt + * @Create:2023/3/7/9:30 + * @Description:TODO Word文件操作工具类 + * @Version:1.0 + */ + +public class StampUtils { + + //关键字索引 (-1) + private final static Integer keyWordIndex = -1; + // 电子印章水平位置 + private final static float horizontal = 300f; + // 电子印章垂直位置 + private final static float vertical = -55f; + // 电子印章宽度 + private final static float stampWidth = 120; + // 电子印章高度 + private final static float stampHeight = 120; + //照片透明度设置 + private final static int alpha = 150; + + + /** + * 1、自定义位置添加电子印章 + * 2、替换书签名位置文本内容 bookmarkName传参为null,则不进行书签替换操作 + * + * @param wordOldUrl word文件路径 + * @param wordNewUrl 新word文件路径 + * @param stampImgUrl 电子印章图片路径 + * @param horizontal 电子印章水平位置 (当前文件推荐260f) + * @param vertical 电子印章垂直位置 (当前推荐455f) + * @param stampWidth 电子印章宽度(推荐120) + * @param stampHeight 电子印章高度(推荐120) + * @param bookmarkName 书签名,通过名称寻找书签文本所在位置 + * @param newBookmarkText 替换的文本新内容 + */ + public void addStamp(String wordOldUrl, String wordNewUrl, String stampImgUrl, + Float horizontal, Float vertical, Float stampWidth, + Float stampHeight, String bookmarkName, String newBookmarkText) { + // 加载文档 + Document document = new Document(); + document.loadFromFile(wordOldUrl); + +// 获取指定段落 + Section section = document.getSections().get(0); +// 获取段落总数 + int count = section.getParagraphs().getCount(); +// log.info("获取文档内容段落总数{}",count); + Paragraph paragraph = section.getParagraphs().get(0); + + // 判断是否需要替换书签位置文本内容 + if (StringUtils.isNotEmpty(bookmarkName)) { + replaceBookmarkContent(document, bookmarkName, newBookmarkText); + } + +// 添加电子印章 + DocPicture docPicture = paragraph.appendPicture(stampImgUrl); + +// 指定电子章位置 +// 水平位置 + docPicture.setHorizontalPosition(horizontal); +// 垂直位置 + docPicture.setVerticalPosition(vertical); + +// 设置电子章大小 + docPicture.setWidth(stampWidth); + docPicture.setHeight(stampHeight); + +// 设置图片位于文字顶层 + docPicture.setTextWrappingStyle(TextWrappingStyle.In_Front_Of_Text); + + // 保存添加电子章的Word文档 + document.saveToFile(wordNewUrl); + document.dispose(); +// log.info("文档添加电子印章结束,新WORD文档地址:{}",wordNewUrl); + + } + + /** + * 1、根据关键词位置添加电子印章 + * 2、替换书签名位置文本内容 bookmarkName传参为null,则不进行书签替换操作 + * + * @param wordOldUrl word文件路径 + * @param wordNewUrl 新word文件路径 + * @param stampImgUrl 电子印章图片路径 + * @param keyWord 关键字 (自定义) + * @param keyWordIndex 关键字索引 (-1) + * @param horizontal 电子印章水平位置 (260f) + * @param vertical 电子印章垂直位置 (-55f) + * @param stampWidth 电子印章宽度 (推荐120) + * @param stampHeight 电子印章高度(推荐120) + */ + public static void addKeyWordStamp(String wordOldUrl, String wordNewUrl, String stampImgUrl, String stampImgUrl1, + String keyWord, Integer keyWordIndex, Float horizontal, + Float vertical, Float stampWidth, Float stampHeight) { + // 加载文档 + Document document = new Document(); + document.loadFromFile(wordOldUrl); + //获取关键字位置 + TextSelection[] textSelections = document.findAllString(keyWord, false, false); + //加签章照片 + if (ObjectUtils.isNotEmpty(textSelections) && StringUtils.isNotEmpty(stampImgUrl)) { + Paragraph paragraph = textSelections[keyWordIndex > -1 ? 0 : textSelections.length - 1].getAsOneRange().getOwnerParagraph(); + //添加公司印章 + DocPicture docPicture = paragraph.appendPicture(stampImgUrl); + + //设置图片位于文字顶层 + docPicture.setTextWrappingStyle(TextWrappingStyle.In_Front_Of_Text); + + //指定电子章位置 + //水平位置 + docPicture.setHorizontalPosition(horizontal); + //垂直位置 + docPicture.setVerticalPosition(vertical); + //设置电子章大小 + docPicture.setWidth(stampWidth); + docPicture.setHeight(stampHeight); + } + + //加签名照片 + if (ObjectUtils.isNotEmpty(textSelections) && StringUtils.isNotEmpty(stampImgUrl1)) { + Paragraph paragraph = textSelections[keyWordIndex > -1 ? 0 : textSelections.length - 1].getAsOneRange().getOwnerParagraph(); + // 添加电子印章 + DocPicture docPicture = paragraph.appendPicture(stampImgUrl1); + //设置图片位于文字顶层 + docPicture.setTextWrappingStyle(TextWrappingStyle.In_Front_Of_Text); + + //指定电子章位置 + //水平位置 + docPicture.setHorizontalPosition(horizontal); + //垂直位置 + docPicture.setVerticalPosition(vertical); + //设置电子章大小 + docPicture.setWidth(stampWidth); + docPicture.setHeight(stampHeight); + } + + //保存添加电子章的Word文档 + document.saveToFile(wordNewUrl); + document.dispose(); + } + + /** + * 替换书签名位置文本内容 + * + * @param document word文档对象 + * @param bookmarkName 书签名 + * @param newBookmarkText 新文本内容 + */ + public void replaceBookmarkContent(Document document, String bookmarkName, String newBookmarkText) { + //定位到指定书签位置 + BookmarksNavigator bookmarksNavigator = new BookmarksNavigator(document); + bookmarksNavigator.moveToBookmark(bookmarkName); + //用文本内容替换原有书签位置的文本,新替换的内容与原文格式一致 + bookmarksNavigator.replaceBookmarkContent(newBookmarkText, true); + } + + /** + * 替换书签名位置文本内容为图片 + * + * @param document word文档对象 + * @param bookmarkName 书签名 + * @param newImgUrl 图片地址 + */ + public void replaceBookmarkContentToImg(Document document, String bookmarkName, String newImgUrl) { + //定位到指定书签位置 + BookmarksNavigator bookmarksNavigator = new BookmarksNavigator(document); + bookmarksNavigator.moveToBookmark(bookmarkName); + //添加图片,替换原有书签内容 + Paragraph para = new Paragraph(document); + para.appendPicture(newImgUrl); + TextBodyPart bodyPart = new TextBodyPart(document); + bodyPart.getBodyItems().add(para); + bookmarksNavigator.replaceBookmarkContent(bodyPart); + } + + /** + * 替换书签名位置文本内容为表格 + * + * @param document word文档对象 + * @param bookmarkName 书签名 + */ + public void replaceBookmarkContentToTable(Document document, String bookmarkName) { + //声明数组内容 + String[][] data = + { + new String[]{"分类", "等级", "编号"}, + new String[]{"A", "一级", "01A"}, + new String[]{"B", "二级", "02B"}, + new String[]{"C", "三级", "03C"}, + }; + + //创建表格 + Table table = new Table(document, true); + table.resetCells(4, 3); + for (int i = 0; i < data.length; i++) { + TableRow dataRow = table.getRows().get(i); + for (int j = 0; j < data[i].length; j++) { + TextRange range = dataRow.getCells().get(j).addParagraph().appendText(data[i][j]); + range.getOwnerParagraph().getFormat().setHorizontalAlignment(HorizontalAlignment.Center); + range.getCharacterFormat().setFontName("楷体"); + dataRow.getRowFormat().setHorizontalAlignment(RowAlignment.Center); + dataRow.getCells().get(j).getCellFormat().setVerticalAlignment(VerticalAlignment.Middle); + } + } + + //创建TextBodyPart对象 + TextBodyPart bodyPart = new TextBodyPart(document); + bodyPart.getBodyItems().add(table); + + //定位到指定书签位置 + BookmarksNavigator bookmarkNavigator = new BookmarksNavigator(document); + bookmarkNavigator.moveToBookmark(bookmarkName); + + //使用表格替换原书签的内容 + bookmarkNavigator.replaceBookmarkContent(bodyPart); + } + + /** + * 文件转流 + * + * @param wordNewUrl + * @return + */ + public byte[] getBytesByFile(String wordNewUrl) { + try { +// byte[] bytes = Files.readAllBytes(Paths.get(wordNewUrl)); + File file = new File(wordNewUrl); + FileInputStream fis = new FileInputStream(file); + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + byte[] b = new byte[1024]; + int len = -1; + while ((len = fis.read(b)) != -1) { + bos.write(b, 0, len); + } + fis.close(); + bos.close(); + byte[] bytes = bos.toByteArray(); + System.out.println("successful..."); + return bytes; + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + /** + * 流转文件 + * + * @param buf 流字节数组 + * @param filePath 新文件路径 + * @param fileName 新文件名称 + */ + public void byte2File(byte[] buf, String filePath, String fileName) { + BufferedOutputStream bos = null; + FileOutputStream fos = null; + File file = null; + try { + File dir = new File(filePath); + if (!dir.exists() && dir.isDirectory()) { + dir.mkdirs(); + } + file = new File(filePath + File.separator + fileName); + fos = new FileOutputStream(file); + bos = new BufferedOutputStream(fos); + bos.write(buf); + } catch (Exception e) { + e.printStackTrace(); + } finally { + if (bos != null) { + try { + bos.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + if (fos != null) { + try { + fos.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + } + + /** + * word转PDF + * + * @param wordNewUrl word文件路径 + * @param pdfNewUrl 存储新PDF文件路径 + */ + public static void wordToPdf(String wordNewUrl, String pdfNewUrl) { +// 将新Word文档转换为PDF文件 + Document document = new Document(); + document.loadFromFile(wordNewUrl); + document.saveToFile(pdfNewUrl, FileFormat.PDF); + document.dispose(); +// log.info("文档转换结束,新PDF文档地址:{}",pdfNewUrl); + } + + + /** + * 图片透明背景转换 + * + * @param imgsrc + * @param alpha + * @return + */ + public static BufferedImage img_alpha(BufferedImage imgsrc, int alpha) { + try { + //创建一个包含透明度的图片,半透明效果必须要存储为png合适才行,存储为jpg,底色为黑色 + BufferedImage back = new BufferedImage(imgsrc.getWidth(), imgsrc.getHeight(), BufferedImage.TYPE_INT_ARGB); + int width = imgsrc.getWidth(); + int height = imgsrc.getHeight(); + for (int j = 0; j < height; j++) { + for (int i = 0; i < width; i++) { + int rgb = imgsrc.getRGB(i, j); + Color color = new Color(rgb); + Color newcolor = new Color(color.getRed(), color.getGreen(), color.getBlue(), alpha); + back.setRGB(i, j, newcolor.getRGB()); + } + } + return back; + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + //读取图片 + public static BufferedImage file2img(String imgpath) { + try { + BufferedImage bufferedImage = ImageIO.read(new File(imgpath)); + return bufferedImage; + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + //保存图片,extent为格式,"jpg"、"png"等 + public static void img2file(BufferedImage img, String extent, String newfile) { + try { + ImageIO.write(img, extent, new File(newfile)); + } catch (Exception e) { + e.printStackTrace(); + } + } + + + /** + * 按照模板 填充数据生成word 只支持docx + * + * @param templatePath 模板文件路径 + * @param temDir 生成文件的目录 + * @param fileName 生成文件名 + * @param params 参数 + */ + public static String exportWord(String templatePath, String temDir, String fileName, Map params) { + Assert.notNull(templatePath, "模板路径不能为空"); + Assert.notNull(temDir, "临时文件路径不能为空"); + Assert.notNull(fileName, "导出文件名不能为空"); + Assert.isTrue(fileName.endsWith(".docx"), "word导出请使用docx格式"); + if (!temDir.endsWith("/")) { + temDir = temDir + File.separator; + } + File dir = new File(temDir); + if (!dir.getParentFile().exists()) { + // 新建文件夹 + dir.getParentFile().mkdirs(); + } + String tmpPath = ""; + try { + XWPFDocument doc = WordExportUtil.exportWord07(templatePath, params); + tmpPath = temDir + fileName; + FileOutputStream fos = new FileOutputStream(tmpPath); + doc.write(fos); + fos.flush(); + fos.close(); + } catch (Exception e) { + e.printStackTrace(); + } + return tmpPath; + } + + /** + * 按照模板 填充数据生成word 只支持docx + * + * @param templatePath 模板文件路径 + * @param temDir 生成文件的目录 + * @param fileName 生成文件名 + * @param params 填充参数 + */ + public static void generateReport(String templatePath, String temDir, + String fileName, Map params, + String stampImgUrl, String stampImgUrl1, + String wordNewUrl, String keyWord, + Integer keyWordIndex, Float horizontal, + Float vertical, Float stampWidth, + Float stampHeight, String pdfNewUrl) { + //1、按照模板填充数据,并导出word + String wordOldUrl = exportWord(templatePath, temDir, fileName, params); + //2、照片背景透明设置 + //2.1签章背景透明设置 + BufferedImage bi = file2img(stampImgUrl); + BufferedImage bii = img_alpha(bi, alpha); + String newPngPath = stampImgUrl.substring(0, stampImgUrl.length() - 4) + "1.png"; + img2file(bii, "PNG", newPngPath); + //2.2签名背景透明设置 + BufferedImage b = file2img(stampImgUrl1); + BufferedImage b0 = img_alpha(b, alpha); + String newPngPath1 = stampImgUrl.substring(0, stampImgUrl1.length() - 4) + "1.png"; + img2file(b0, "PNG", newPngPath1); + + //3、添加签章和签名 + addKeyWordStamp(wordOldUrl, wordNewUrl, newPngPath, newPngPath1, keyWord, keyWordIndex, + horizontal, vertical, stampWidth, stampHeight); + // 4、将新word转化为pdf文件 + wordToPdf(wordNewUrl, pdfNewUrl); + } + + + public static void main(String[] args) { + + //文件与BufferedImage间的转换 + //读取图片 + BufferedImage bi = file2img("C:\\upload\\word\\sign.png"); + BufferedImage bii = img_alpha(bi, alpha); + //生成透明背景图片 + img2file(bii, "PNG", "C:\\upload\\word\\sign1.png"); + + //文件与BufferedImage间的转换 + //读取图片 + BufferedImage b = file2img("C:\\upload\\word\\name.png"); + BufferedImage b0 = img_alpha(b, alpha); + //生成透明背景图片 + img2file(b0, "PNG", "C:\\upload\\word\\name1.png"); + + // 目标文件地址 + String wordOldUrl = "C:\\upload\\word\\wordExport.docx"; + // 添加电子印章后文件存放地址 + String wordNewUrl = "C:\\upload\\word\\tem2.docx"; + //WORD转PDF存放位置 + String pdfNewUrl = "C:\\upload\\word\\tem2.pdf"; + //电子印章图片地址 + String stampImgUrl = "C:\\upload\\word\\sign1.png"; + //电子签名图片地址 + String stampImgUrl1 = "C:\\upload\\word\\name1.png"; + // word文档内容关键字 + String keyWord = "盖章"; + StampUtils addStampUtils = new StampUtils(); + //获取关键字位置并加盖印章并替换书签名位置文本内容 + addStampUtils.addKeyWordStamp(wordOldUrl, wordNewUrl, + stampImgUrl, stampImgUrl1, + keyWord, keyWordIndex, + horizontal, vertical, + stampWidth, stampHeight); + // 将新word转化为pdf文件 + addStampUtils.wordToPdf(wordNewUrl, pdfNewUrl); + } +} \ No newline at end of file diff --git a/casic-metering-model/src/main/java/com/casic/missiles/dto/business/certificate/CertificateReportResponse.java b/casic-metering-model/src/main/java/com/casic/missiles/dto/business/certificate/CertificateReportResponse.java index b43617c..4581acf 100644 --- a/casic-metering-model/src/main/java/com/casic/missiles/dto/business/certificate/CertificateReportResponse.java +++ b/casic-metering-model/src/main/java/com/casic/missiles/dto/business/certificate/CertificateReportResponse.java @@ -1,6 +1,7 @@ package com.casic.missiles.dto.business.certificate; import com.alibaba.excel.annotation.ExcelIgnoreUnannotated; +import com.alibaba.excel.annotation.ExcelProperty; import com.alibaba.excel.annotation.write.style.ColumnWidth; import com.alibaba.excel.annotation.write.style.ContentRowHeight; import com.alibaba.excel.annotation.write.style.ContentStyle; @@ -28,73 +29,56 @@ private Long id; @ApiModelProperty(value = "证书报告编号", dataType = "String") + @ExcelProperty(value = "证书号", order = 0) private String certificateReportCode; @ApiModelProperty(value = "证书报告名称", dataType = "String") + @ExcelProperty(value = "证书名称", order = 1) private String certificateReportName; @ApiModelProperty(value = "样品编号", dataType = "String") + @ExcelProperty(value = "样品编号", order = 2) private String sampleNo; + @ApiModelProperty(value = "样品名称", dataType = "String") + @ExcelProperty(value = "样品名称", order = 3) private String sampleName; + @ApiModelProperty(value = "型号", dataType = "String") + @ExcelProperty(value = "型号", order = 4) private String sampleModel; + @ApiModelProperty(value = "出厂编号", dataType = "String") + @ExcelProperty(value = "出厂编号", order = 5) private String manufacturingNo; + @ApiModelProperty(value = "委托书编号", dataType = "String") + @ExcelProperty(value = "委托书编号", order = 6) private String orderCode; @ApiModelProperty(value = "检校专业", dataType = "String") @DictCodeField(message = "检校专业不合法", cacheName = MeterDictCode.CALIBRATION_MAJOR) private String calibrationMajor; -// @ApiModelProperty(value = "出具日期", dataType = "String") -// private String issuanceDate; -// -// -// @ApiModelProperty(value = "证书有效期", dataType = "String") -// private String expirationDate; -// -// @ApiModelProperty(value = "检定结果", dataType = "String") -// private String measureResult; -// -// -// @ApiModelProperty(value = "原始记录id", dataType = "Long") -// private Long originalRecordId; -// -// -// @ApiModelProperty(value = "可打印状态", dataType = "String") -// private String printStatus; -// -// -// @ApiModelProperty(value = "打印次数", dataType = "Integer") -// private Integer printNum; - - - @ApiModelProperty(value = "检定人员", dataType = "String") + @ApiModelProperty(value = "检定人员id", dataType = "String") private String measurePersonId; @ApiModelProperty(value = "检定人员名称", dataType = "String") + @ExcelProperty(value = "检定人员", order = 8) private String measurePersonName; @ApiModelProperty(value = "审批状态", dataType = "String") @DictCodeField(message = "审批状态不合法", cacheName = MeterDictCode.APPROVAL_STATUS) private String approvalStatus; -// @ApiModelProperty(value = "备注", dataType = "String") -// private String remark; -// -// private Long createUser; -// @ApiModelProperty(value = "创建时间", dataType = "String") + @ExcelProperty(value = "创建时间", order = 10) private String createTime; -// @ApiModelProperty(value = "检校专业名称", dataType = "String") -// private String calibrationMajorName; - @ApiModelProperty(value = "审批状态名称", dataType = "String") + @ExcelProperty(value = "审批状态", order = 9) private String approvalStatusName; /** @@ -120,6 +104,7 @@ private String measureCategory; @ApiModelProperty(value = "校验类别名称", dataType = "String") + @ExcelProperty(value = "校验类别", order = 7) private String measureCategoryName; diff --git a/casic-metering-model/src/main/java/com/casic/missiles/dto/business/originRecord/OriginRecordRequest.java b/casic-metering-model/src/main/java/com/casic/missiles/dto/business/originRecord/OriginRecordRequest.java index d2c2ec7..d2687bf 100644 --- a/casic-metering-model/src/main/java/com/casic/missiles/dto/business/originRecord/OriginRecordRequest.java +++ b/casic-metering-model/src/main/java/com/casic/missiles/dto/business/originRecord/OriginRecordRequest.java @@ -31,7 +31,7 @@ @ApiModelProperty(value = "创建人", dataType = "String") private String createUser; - @ApiModelProperty(value = "原始记录单id", dataType = "Long") + @ApiModelProperty(value = "委托书id", dataType = "Long") private Long id; @ApiModelProperty(value = "导出ids(查询不用传)", dataType = "List") diff --git a/casic-metering-service/src/main/java/com/casic/missiles/service/Impl/business/BusinessCertificateReportServiceImpl.java b/casic-metering-service/src/main/java/com/casic/missiles/service/Impl/business/BusinessCertificateReportServiceImpl.java index d03ab22..aabfac2 100644 --- a/casic-metering-service/src/main/java/com/casic/missiles/service/Impl/business/BusinessCertificateReportServiceImpl.java +++ b/casic-metering-service/src/main/java/com/casic/missiles/service/Impl/business/BusinessCertificateReportServiceImpl.java @@ -26,8 +26,6 @@ import com.casic.missiles.service.business.IBusinessCertificateReportService; import com.casic.missiles.service.business.IBusinessOriginalRecordService; import com.casic.missiles.service.flowable.ApprovalOperateService; -import com.casic.missiles.utils.ConvertUtils; -import com.casic.missiles.utils.DictCodeUtils; import com.casic.missiles.utils.NumberGeneratorUtil; import org.flowable.engine.RuntimeService; import org.flowable.engine.TaskService; @@ -68,8 +66,10 @@ private RuntimeService runtimeService; @Resource private IBaseExportService iBaseExportService; + /** * 保存证书报告信息 + * * @param certificateReport * @return */ @@ -77,7 +77,7 @@ public ReturnDTO saveCertificateReport(BusinessCertificateReport certificateReport) { initCertificateReport(certificateReport); - if(this.baseMapper.insert(certificateReport)>0) + if (this.baseMapper.insert(certificateReport) > 0) return ReturnUtil.success(); throw new BusinessException(BusinessExceptionEnum.HANDLE_FAILED); } @@ -90,9 +90,9 @@ @Override public ReturnDTO approvalDelete(ApprovalDeleteRequest request) { ReturnDTO returnDTO = approvalOperateService.delete(request); - if(ResponseData.DEFAULT_SUCCESS_CODE == returnDTO.getCode()){ + if (ResponseData.DEFAULT_SUCCESS_CODE == returnDTO.getCode()) { //删除数据库记录 - if(this.baseMapper.deleteById(request.getId()) > 0){ + if (this.baseMapper.deleteById(request.getId()) > 0) { return ReturnUtil.success(); } } @@ -101,7 +101,7 @@ @Override public ReturnDTO draftUpdate(BusinessCertificateReport certificateReport) { - if(this.baseMapper.updateById(certificateReport)>0){ + if (this.baseMapper.updateById(certificateReport) > 0) { return ReturnUtil.success(); } throw new BusinessException(BusinessExceptionEnum.HANDLE_FAILED); @@ -109,25 +109,27 @@ /** * 批量删除 + * * @param ids * @return */ @Override public ReturnDTO deleteBatchTraceSupplier(List ids) { - return baseMapper.deleteBatchIds(ids) > 0?ReturnUtil.success(): + return baseMapper.deleteBatchIds(ids) > 0 ? ReturnUtil.success() : ReturnUtil.failed("删除失败"); } /** * 证书报告详情 + * * @param id * @return */ @Override public BusinessCertificateReport certificateReportDetail(Long id) { BusinessCertificateReport certificateReport = this.baseMapper.selectById(id); - if(certificateReport.getOriginalRecordId()!=null){ + if (certificateReport.getOriginalRecordId() != null) { try { certificateReport.setBusinessOriginalRecord(originalRecordService.originalDetail(certificateReport.getOriginalRecordId())); } catch (Exception e) { @@ -139,6 +141,7 @@ /** * 提交证书报告 + * * @param request * @return */ @@ -148,10 +151,10 @@ String formId = request.getFormId(); //2.根据流程定义id启动流程实例 ReturnDTO returnDTO = baseApprovalService.processSubmit(formId, request.getId()); - if(ResponseData.DEFAULT_SUCCESS_CODE != returnDTO.getCode()){ + if (ResponseData.DEFAULT_SUCCESS_CODE != returnDTO.getCode()) { return returnDTO; } - ProcessInstance processInstance = (ProcessInstance)returnDTO.getData(); + ProcessInstance processInstance = (ProcessInstance) returnDTO.getData(); BusinessCertificateReport certificateReport = new BusinessCertificateReport(); certificateReport.setId(request.getId()); certificateReport.setApprovalStatus(ApprovalStatusEnum.UN_DRAFT); //非草稿状态 @@ -165,6 +168,7 @@ /** * 审批状态列表查询 + * * @param page * @param request * @return @@ -182,6 +186,7 @@ /** * 驳回后更新 + * * @param certificateReport * @return */ @@ -208,13 +213,14 @@ @Override public void originExport(CertificateReportApprovalRequest request, HttpServletResponse response) { try { - //toDo: -// List certificateReportResponses = this.certificateReport(request); -// for (OriginRecordResponse originRecordResponse : originExportList) { -// //字典值转换 -// DictCodeUtils.convertDictCodeToName(originRecordResponse); -// } -// iBaseExportService.exportExcel(response, CertificateReportResponse.class, originExportList, ExportEnum.CERTIFICATE_REPORT.getSheetName()); + //登录用户 + AuthUser user = ShiroKit.getUser(); + Assert.isFalse(Objects.isNull(user), () -> { + throw new BusinessException(BusinessExceptionEnum.LOGIN_USER_ACQUIRE_FAILED); + }); + request.setCreateUserId(user.getId()); + List reportResponseList= handleApprovalStatus(null, request); + iBaseExportService.exportExcel(response, CertificateReportResponse.class, reportResponseList, ExportEnum.CERTIFICATE_REPORT.getSheetName()); } catch (Exception e) { log.error("证书报告导出出现异常,异常信息为{}", e); } @@ -231,15 +237,15 @@ //待审批,该状态维护在flowable中 case ApprovalStatusEnum.TO_BE_APPROVED: List toBeApprovedList = baseApprovalService.getToBeApprovedList(request.getFormId()); - if(!CollectionUtils.isEmpty(toBeApprovedList)){ + if (!CollectionUtils.isEmpty(toBeApprovedList)) { businessKeys = toBeApprovedList.stream().map(ToBeApprovedDTO::getBusinessKey).distinct().collect(Collectors.toList()); } - if(!CollectionUtils.isEmpty(businessKeys)){ + if (!CollectionUtils.isEmpty(businessKeys)) { approvalList = handleApprovalListResponse(this.baseMapper.selectBatchForApproval(page, request, businessKeys), ApprovalStatusEnum.TO_BE_APPROVED); //DTO根据业务主键补全taskId approvalList.forEach(approval -> { toBeApprovedList.forEach(toBeApprovedDTO -> { - if(String.valueOf(approval.getId()).equals(toBeApprovedDTO.getBusinessKey())){ + if (String.valueOf(approval.getId()).equals(toBeApprovedDTO.getBusinessKey())) { approval.setTaskId(toBeApprovedDTO.getTaskId()); //补全可选决策项 approval.setDecisionItem(toBeApprovedDTO.getDecisionItem()); @@ -251,27 +257,27 @@ //审批中,该状态维护在flowable中 case ApprovalStatusEnum.IN_APPROVED: businessKeys = baseApprovalService.getInApprovedList(request.getFormId()); - if(!CollectionUtils.isEmpty(businessKeys)){ + if (!CollectionUtils.isEmpty(businessKeys)) { approvalList = handleApprovalListResponse(this.baseMapper.selectBatchForApproval(page, request, businessKeys), ApprovalStatusEnum.IN_APPROVED); } break; //已通过,该状态维护在flowable case ApprovalStatusEnum.PASSED: businessKeys = baseApprovalService.getPassedList(request.getFormId()); - if(!CollectionUtils.isEmpty(businessKeys)){ - approvalList = handleApprovalListResponse( this.baseMapper.selectBatchForApproval(page, request, businessKeys), ApprovalStatusEnum.PASSED); + if (!CollectionUtils.isEmpty(businessKeys)) { + approvalList = handleApprovalListResponse(this.baseMapper.selectBatchForApproval(page, request, businessKeys), ApprovalStatusEnum.PASSED); } break; //未通过(包括拒绝、驳回,拒绝为直接删除实例,驳回为驳回到起点),该状态维护在flowable case ApprovalStatusEnum.FAILED: businessKeys = baseApprovalService.getFailedList(request.getFormId()); //未通过-拒绝 List rejectBusinessKey = baseApprovalService.getFailedRejectList(request.getFormId()); //未通过-驳回 - if(!CollectionUtils.isEmpty(businessKeys)){ + if (!CollectionUtils.isEmpty(businessKeys)) { approvalList = handleApprovalListResponse(this.baseMapper.selectBatchForApproval(page, request, businessKeys), ApprovalStatusEnum.FAILED); } List rejectApprovalList = new ArrayList<>(); - if(!CollectionUtils.isEmpty(rejectBusinessKey)){ - rejectApprovalList = handleApprovalListResponse( this.baseMapper.selectBatchForApproval(page, request, rejectBusinessKey), ApprovalStatusEnum.FAILED_REJECT); + if (!CollectionUtils.isEmpty(rejectBusinessKey)) { + rejectApprovalList = handleApprovalListResponse(this.baseMapper.selectBatchForApproval(page, request, rejectBusinessKey), ApprovalStatusEnum.FAILED_REJECT); } //合并未通过-拒绝和未通过-驳回 approvalList.addAll(rejectApprovalList); @@ -279,7 +285,7 @@ //已取消(直接删除实例),该状态维护在flowable case ApprovalStatusEnum.CANCELED: businessKeys = baseApprovalService.getCanceledList(request.getFormId()); - if(!CollectionUtils.isEmpty(businessKeys)){ + if (!CollectionUtils.isEmpty(businessKeys)) { approvalList = handleApprovalListResponse(this.baseMapper.selectBatchForApproval(page, request, businessKeys), ApprovalStatusEnum.CANCELED); } break; @@ -288,10 +294,10 @@ //普通用户获取自己发起的(审批中、已通过、未通过、已取消),管理员获取全部(审批中、已通过、未通过、已取消) case ApprovalStatusEnum.ALL: List AllApproveList = baseApprovalService.getAllList(request.getFormId()); - if(!CollectionUtils.isEmpty(AllApproveList)){ + if (!CollectionUtils.isEmpty(AllApproveList)) { businessKeys = AllApproveList.stream().map(AllApproveDTO::getBusinessKey).collect(Collectors.toList()); } - if(!CollectionUtils.isEmpty(businessKeys)){ + if (!CollectionUtils.isEmpty(businessKeys)) { approvalList = handleAllApprovalListResponse(this.baseMapper.selectBatchForApproval(page, request, businessKeys), AllApproveList); } break; @@ -299,9 +305,11 @@ return approvalList; } - private List handleAllApprovalListResponse(List approvalList, List allApproveList) { - Map taskMap = new HashMap<>(); - allApproveList.forEach(allApprove -> {taskMap.put(allApprove.getBusinessKey(),allApprove.getStatus());}); + private List handleAllApprovalListResponse(List approvalList, List allApproveList) { + Map taskMap = new HashMap<>(); + allApproveList.forEach(allApprove -> { + taskMap.put(allApprove.getBusinessKey(), allApprove.getStatus()); + }); //状态补全 approvalList.forEach(approval -> { approval.setApprovalStatusName(dictService.getDictNameByCode(MeterDictEnum.APPROVAL_STATUS, taskMap.get(String.valueOf(approval.getId())))); @@ -313,7 +321,7 @@ return approvalList.stream().sorted(Comparator.comparing(CertificateReportResponse::getCreateTime).reversed()).collect(Collectors.toList()); } - private List handleApprovalListResponse(List approvalList, String status){ + private List handleApprovalListResponse(List approvalList, String status) { approvalList.stream().forEach(result -> { //审批状态两种获取方式:1、在此处设置,2、在flowable中设置业务状态,暂采取1 result.setApprovalStatusName(dictService.getDictNameByCode(MeterDictEnum.APPROVAL_STATUS, status)); @@ -324,14 +332,14 @@ private void initCertificateReport(BusinessCertificateReport certificateReport) { String prefix = MonitorCodeEnum.getByCode(certificateReport.getCalibrationMajor()).getValue() - +DateUtil.format(new Date(),"YYYYMM"); + + DateUtil.format(new Date(), "YYYYMM"); Long maxNo = this.baseMapper.selectMaxCode(prefix); //生成证书编号 - String certificateReportNo =NumberGeneratorUtil.getCode( - MonitorCodeEnum.getByCode(certificateReport.getCalibrationMajor()).getValue(),maxNo); + String certificateReportNo = NumberGeneratorUtil.getCode( + MonitorCodeEnum.getByCode(certificateReport.getCalibrationMajor()).getValue(), maxNo); AuthUser authUser = ShiroKit.getUser(); certificateReport.setCreateUser(authUser.getId()); - certificateReport.setMeasurePersonId(authUser.getId()+""); + certificateReport.setMeasurePersonId(authUser.getId() + ""); certificateReport.setMeasureDeptId(authUser.getDeptId()); certificateReport.setCertificateReportCode(certificateReportNo); } diff --git a/casic-metering-service/src/main/java/com/casic/missiles/service/Impl/business/BusinessOrderServiceImpl.java b/casic-metering-service/src/main/java/com/casic/missiles/service/Impl/business/BusinessOrderServiceImpl.java index f5c6f61..21ab8b6 100644 --- a/casic-metering-service/src/main/java/com/casic/missiles/service/Impl/business/BusinessOrderServiceImpl.java +++ b/casic-metering-service/src/main/java/com/casic/missiles/service/Impl/business/BusinessOrderServiceImpl.java @@ -90,8 +90,10 @@ List customerSampleList = new ArrayList<>(); for (BusinessOrderSampleRelation orderSample : orderSampleList) { CustomerSampleInfo customerSampleInfo = customerSampleService.sampleDetail(orderSample.getSampleId()); - customerSampleInfo.setIsExistSample("1"); - customerSampleList.add(customerSampleInfo); + if (null != customerSampleInfo) { + customerSampleInfo.setIsExistSample("1"); + customerSampleList.add(customerSampleInfo); + } } businessOrder.setCustomerSampleInfoList(customerSampleList); return businessOrder; diff --git a/casic-metering-service/src/main/java/com/casic/missiles/service/Impl/business/BusinessOriginalRecordServiceImpl.java b/casic-metering-service/src/main/java/com/casic/missiles/service/Impl/business/BusinessOriginalRecordServiceImpl.java index 1e35b7a..1c602b8 100644 --- a/casic-metering-service/src/main/java/com/casic/missiles/service/Impl/business/BusinessOriginalRecordServiceImpl.java +++ b/casic-metering-service/src/main/java/com/casic/missiles/service/Impl/business/BusinessOriginalRecordServiceImpl.java @@ -131,7 +131,7 @@ @Override public ReturnDTO updateOriginal(BusinessOriginalRecord businessOriginalRecord) { - if (this.baseMapper.insert(businessOriginalRecord) > 0) { + if (this.baseMapper.updateById(businessOriginalRecord) > 0) { //加入技术文件绑定 if (ObjectUtil.isNotEmpty(businessOriginalRecord.getFileList()) && businessOriginalRecord.getFileList().size() > 0) { originalRecordFileRelationService.saveBatch(businessOriginalRecord.getId(), businessOriginalRecord.getFileList()); diff --git a/casic-metering-service/src/main/java/com/casic/missiles/service/business/IBusinessCertificateReportService.java b/casic-metering-service/src/main/java/com/casic/missiles/service/business/IBusinessCertificateReportService.java index 89787de..38542be 100644 --- a/casic-metering-service/src/main/java/com/casic/missiles/service/business/IBusinessCertificateReportService.java +++ b/casic-metering-service/src/main/java/com/casic/missiles/service/business/IBusinessCertificateReportService.java @@ -6,7 +6,6 @@ import com.casic.missiles.dto.ReturnDTO; import com.casic.missiles.dto.business.certificate.CertificateReportApprovalRequest; import com.casic.missiles.dto.business.certificate.CertificateReportResponse; -import com.casic.missiles.dto.business.originRecord.OriginRecordRequest; import com.casic.missiles.dto.flowable.ApprovalDeleteRequest; import com.casic.missiles.model.business.BusinessCertificateReport;