zss
2024-07-08 ca734d69ab3937bac864b4361317a49dd15a7882
inspect-server/src/main/java/com/yuanchu/mom/service/impl/InsReportServiceImpl.java
@@ -1,51 +1,53 @@
package com.yuanchu.mom.service.impl;
import com.alibaba.fastjson.JSON;
import com.aspose.words.*;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.data.Pictures;
import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.itextpdf.text.BadElementException;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import com.yuanchu.mom.common.GetLook;
import com.yuanchu.mom.common.PrintChina;
import com.yuanchu.mom.dto.InsOrderPlanDTO;
import com.yuanchu.mom.dto.ReportPageDto;
import com.yuanchu.mom.dto.SampleOrderDto;
import com.yuanchu.mom.exception.ErrorException;
import com.yuanchu.mom.mapper.InsOrderMapper;
import com.yuanchu.mom.mapper.InsReportMapper;
import com.yuanchu.mom.mapper.UserMapper;
import com.yuanchu.mom.pojo.InsOrder;
import com.yuanchu.mom.pojo.InsReport;
import com.yuanchu.mom.service.InsReportService;
import com.yuanchu.mom.mapper.InsReportMapper;
import com.yuanchu.mom.utils.QueryWrappers;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
/**
* @author Administrator
* @description 针对表【ins_report(检验报告)】的数据库操作Service实现
* @createDate 2024-03-17 22:10:02
*/
 * @author Administrator
 * @description 针对表【ins_report(检验报告)】的数据库操作Service实现
 * @createDate 2024-03-17 22:10:02
 */
@Service
public class InsReportServiceImpl extends ServiceImpl<InsReportMapper, InsReport>
    implements InsReportService{
        implements InsReportService {
    @Resource
    private GetLook getLook;
@@ -76,18 +78,6 @@
    }
    @Override
    public String wordToHtml(String path) {
        try(ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
            Document document = new Document();
            document.loadFromFile(path.replace("/word", wordUrl));
            document.saveToFile(outputStream, FileFormat.Html);
            return outputStream.toString();
        } catch (Exception e) {
            throw new ErrorException("转换失败");
        }
    }
    @Override
    public int inReport(String url, Integer id) {
        InsReport insReport = new InsReport();
        insReport.setId(id);
@@ -109,14 +99,19 @@
        insReport.setWriteUserId(getLook.selectPowerByMethodAndUserId(null).get("userId"));//提交人
        insReport.setWriteTime(LocalDateTime.now());//提交时间
        //获取提交人的签名地址
        String signatureUrl = userMapper.selectById(insReport.getWriteUserId()).getSignatureUrl();
        String signatureUrl;
        try {
            signatureUrl = userMapper.selectById(insReport.getWriteUserId()).getSignatureUrl();
        } catch (Exception e) {
            throw new ErrorException("找不到编制人的签名");
        }
        //系统生成报告地址
        String url = insReport.getUrl();
        //手动上传报告地址
        String urlS = insReport.getUrlS();
        wordInsertUrl(new HashMap<String, Object>(){{
            put("writeUrl", Pictures.ofLocal(imgUrl+"/"+signatureUrl).create());
        }}, (urlS==null?url:urlS).replace("/word", wordUrl));
        wordInsertUrl(new HashMap<String, Object>() {{
            put("writeUrl", Pictures.ofLocal(imgUrl + "/" + signatureUrl).create());
        }}, (urlS == null ? url : urlS).replace("/word", wordUrl));
        return insReportMapper.updateById(insReport);
    }
@@ -130,20 +125,25 @@
        }
        insReport.setExamineUserId(getLook.selectPowerByMethodAndUserId(null).get("userId"));//审核人
        insReport.setExamineTime(LocalDateTime.now());//审核时间
        if (isExamine==0){
        if (isExamine == 0) {
            //如果审核不通过
            insReport.setState(0);//提交状态改为待提交
            return insReportMapper.updateById(insReport);
        }
        //获取审核人的签名地址
        String signatureUrl = userMapper.selectById(insReport.getExamineUserId()).getSignatureUrl();
        String signatureUrl;
        try {
            signatureUrl = userMapper.selectById(insReport.getExamineUserId()).getSignatureUrl();
        } catch (Exception e) {
            throw new ErrorException("找不到审核人的签名");
        }
        //系统生成报告地址
        String url = insReport.getUrl();
        //手动上传报告地址
        String urlS = insReport.getUrlS();
        wordInsertUrl(new HashMap<String, Object>(){{
            put("examineUrl", Pictures.ofLocal(imgUrl+"/"+signatureUrl).create());
        }}, (urlS==null?url:urlS).replace("/word", wordUrl));
        wordInsertUrl(new HashMap<String, Object>() {{
            put("examineUrl", Pictures.ofLocal(imgUrl + "/" + signatureUrl).create());
        }}, (urlS == null ? url : urlS).replace("/word", wordUrl));
        return insReportMapper.updateById(insReport);
    }
@@ -158,20 +158,53 @@
        }
        insReport.setRatifyUserId(getLook.selectPowerByMethodAndUserId(null).get("userId"));//批准人
        insReport.setRatifyTime(LocalDateTime.now());//批准时间
        if (isRatify==0){
        if (isRatify == 0) {
            //如果批准不通过
            insReport.setState(0);//提交状态改为待提交
            return insReportMapper.updateById(insReport);
        }
        //获取审核人的签名地址
        String signatureUrl = userMapper.selectById(insReport.getRatifyUserId()).getSignatureUrl();
        //获取批准人的签名地址
        String signatureUrl;
        try {
            signatureUrl = userMapper.selectById(insReport.getRatifyUserId()).getSignatureUrl();
        } catch (Exception e) {
            throw new ErrorException("找不到批准人的签名");
        }
        //获取场所的报告专用章
        String sealUrl;
        try {
            String laboratory = insOrderMapper.selectById(insReport.getInsOrderId()).getLaboratory();
            sealUrl = insReportMapper.getLaboratoryByName(laboratory);
        } catch (Exception e) {
            throw new ErrorException("找不到报告专用章");
        }
        if (sealUrl == null) throw new ErrorException("找不到报告专用章");
        //系统生成报告地址
        String url = insReport.getUrl();
        //手动上传报告地址
        String urlS = insReport.getUrlS();
        wordInsertUrl(new HashMap<String, Object>(){{
            put("ratifyUrl", Pictures.ofLocal(imgUrl+"/"+signatureUrl).create());
        }}, (urlS==null?url:urlS).replace("/word", wordUrl));
        String finalUrl = (urlS == null ? url : urlS).replace("/word", wordUrl);
        wordInsertUrl(new HashMap<String, Object>() {{
            put("ratifyUrl", Pictures.ofLocal(imgUrl + "/" + signatureUrl).create());
            put("seal1", Pictures.ofLocal(imgUrl + "/" + sealUrl).create());
            put("seal2", Pictures.ofLocal(imgUrl + "/" + sealUrl).create());
        }}, finalUrl);
        wordToPdf(finalUrl,sealUrl);
       /* String replace = finalUrl.replace(".docx", ".pdf");
        CompletableFuture.supplyAsync(() -> {
            try {
                stamperCheckMarkPDF(replace,replace,sealUrl);
                return null;
            } catch (Exception e) {
                throw new ErrorException("骑缝章插入失败");
            }
        }).thenAccept(res -> {
        }).exceptionally(e -> {
            e.printStackTrace();
            return null;
        });*/
        InsOrder insOrder = new InsOrder();
        insOrder.setId(insReportMapper.selectById(id).getInsOrderId());
        insOrder.setState(4);
@@ -189,8 +222,133 @@
        }
        return 1;
    }
    @Override
    public void wordToPdf(String path,String sealUrl) {
        CompletableFuture.supplyAsync(() -> {
            try {
                wordToPdf(path, path.replace(".docx", ".pdf"),sealUrl);
                return null;
            } catch (Exception e) {
                throw new ErrorException("转换失败");
            }
        }).thenAccept(res -> {
        }).exceptionally(e -> {
            e.printStackTrace();
            return null;
        });
    }
    public String wordToPdf(String wordPath, String pdfPath,String sealUrl) {
        FileOutputStream os = null;
        try {
            //凭证 不然切换后有水印
//            InputStream inputStream = this.getClass().getResourceAsStream("/lib/license.xml");
            /*String url;
            try {
                InputStream inputStream = this.getClass().getResourceAsStream("/lib/license.xml");
                File file = File.createTempFile("temp", ".tmp");
                OutputStream outputStream = new FileOutputStream(file);
                IOUtils.copy(inputStream, outputStream);
                url = file.getAbsolutePath();
            } catch (FileNotFoundException e) {
                throw new ErrorException("找不到模板文件");
            } catch (IOException e) {
                throw new RuntimeException(e);
            }*/
            InputStream is = new ClassPathResource("/lib/license.xml").getInputStream();
            License license = new License();
            license.setLicense(is);
            if (!license.getIsLicensed()) {
                System.out.println("License验证不通过...");
                return null;
            }
            //生成一个空的PDF文件
            File file = new File(pdfPath.replace(".pdf","-1.pdf"));
            os = new FileOutputStream(file);
            //要转换的word文件
            com.aspose.words.Document doc = new com.aspose.words.Document(wordPath);
            doc.save(os, SaveFormat.PDF);
            //添加骑缝章
            stamperCheckMarkPDF(pdfPath.replace(".pdf","-1.pdf"),pdfPath,imgUrl + "/" +sealUrl);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
    /**
     * 切割图片
     * @param Path  图片路径
     * @param n 切割份数
     */
    public static com.itextpdf.text.Image[] slicingImages(String Path, int n) throws IOException, BadElementException {
        com.itextpdf.text.Image[] nImage = new  com.itextpdf.text.Image[n];
        BufferedImage img = ImageIO.read(new File(Path));
        int h = img.getHeight();
        int w = img.getWidth();
        int sw = w/n;
        for(int i=0;i<n;i++){
            BufferedImage subImg;
            if(i==n-1){//最后剩余部分
                subImg = img.getSubimage(i * sw, 0, w-i*sw, h);
            }else {//前n-1块均匀切
                subImg = img.getSubimage(i * sw, 0, sw, h);
            }
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            ImageIO.write(subImg,Path.substring(Path.lastIndexOf('.')+1),out);
            nImage[i] = com.itextpdf.text.Image.getInstance(out.toByteArray());
        }
        return nImage;
    }
    /**
     *  盖骑缝章
     *
     * @param infilePath    原PDF路径
     * @param outFilePath    输出PDF路径
     */
    public static void stamperCheckMarkPDF(String infilePath,String outFilePath,String picPath) throws IOException, DocumentException {
        PdfReader reader = new PdfReader(infilePath);//选择需要印章的pdf
        PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(outFilePath));//加完印章后的pdf
        com.itextpdf.text.Rectangle pageSize = reader.getPageSize(1);//获得第一页
        float height = pageSize.getHeight();
        float width  = pageSize.getWidth();
        int nums = reader.getNumberOfPages();
        com.itextpdf.text.Image[] nImage =  slicingImages(picPath,nums);//生成骑缝章切割图片
        for(int n=1;n<=nums;n++){
            PdfContentByte over = stamp.getOverContent(n);//设置在第几页打印印章
            com.itextpdf.text.Image img = nImage[n-1];//选择图片
            float newHeight = 100f;
            float newWidth = img.getWidth()/(img.getHeight()/100);
            img.scaleAbsolute(newWidth,newHeight);//控制图片大小
            img.setAbsolutePosition(width-newWidth,height/2-newHeight/2);//控制图片位置
            over.addImage(img);
        }
        stamp.close();
    }
}