zhaowenxuan
2024-12-07 a67c8724bcd1449c00a5eb6a260a8c838336195f
ltkj-admin/src/main/java/com/ltkj/web/controller/his/HisPDFUtil.java
@@ -2,36 +2,47 @@
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itextpdf.text.*;
import com.itextpdf.text.Font;
import com.itextpdf.text.Image;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.*;
import com.itextpdf.text.pdf.draw.LineSeparator;
import com.ltkj.common.core.domain.AjaxResult;
import com.ltkj.common.core.domain.entity.SysDictData;
import com.ltkj.common.core.domain.entity.SysUser;
import com.ltkj.common.utils.DateUtils;
import com.ltkj.framework.config.MatchUtils;
import com.ltkj.hosp.domain.*;
import com.ltkj.hosp.mapper.DictUserInfoMapper;
import com.ltkj.hosp.service.*;
import com.ltkj.hosp.sqlDomain.LtkjExamJcbgd;
import com.ltkj.hosp.sqlDomain.LtkjHybgd;
import com.ltkj.hosp.sqlDomain.LtkjHysqd;
import com.ltkj.system.service.ISysConfigService;
import com.ltkj.system.service.ISysDictDataService;
import com.ltkj.system.service.ISysUserService;
import com.ltkj.web.config.pdfutils.PdfUtils;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.awt.*;
import java.io.*;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;
import java.util.stream.Collectors;
/**
 * 检查 检验报告pdf生成
@@ -75,10 +86,14 @@
    private DictUserInfoMapper dictUserInfoMapper;
    @Autowired
    private ISysConfigService sysConfigService;
//    private static final
    // TODO PDF所有医师名字显示 根据配置is_report_pdf_use_ysqm决定是否使用签名图片
    // TODO 有签名图片则使用签名图片 没有则使用文字显示
    @Resource
    private LtkjExamJcbgdService jcbgdService;
    @Resource
    private LtkjExamJcsqdService jcsqdService;
    @Autowired
    private IDictHospService dictHospService;
    @Autowired
    private ISysDictDataService sysDictDataService;
    private List<Map<String, Object>> makePDFInfo(HashMap<String, Object> map, AjaxResult ajaxResult, String key) {
        List<Map<String, Object>> data = null;
@@ -102,6 +117,10 @@
    }
    public AjaxResult hisPDF(TjOrder tjOrder, TjCustomer customer, TjReportTemplate tjReportTemplate) throws Exception {
        DictHosp dictHosp = dictHospService.list().get(0);
        String color = sysConfigService.selectConfigByKey("report_title_color");
//        list.get(0).getHospName().equals("澄合矿务局中心医院")
        List<SysDictData> sysUserSex = sysDictDataService.list(new LambdaQueryWrapper<SysDictData>().eq(SysDictData::getDictType, "sys_user_sex"));
        HashMap<String, Object> pdfChangGui = makePDFInfo(tjOrder, customer, tjReportTemplate);
        if (pdfChangGui == null)
            return AjaxResult.error();
@@ -111,8 +130,22 @@
        ByteArrayOutputStream byteArrayOutputStream1 = new ByteArrayOutputStream();
        Document document1 = new Document(PageSize.A4);
        PdfWriter pdfWriter = null;
        int pageSize = 0;
        try {
            pdfWriter = PdfWriter.getInstance(document1, byteArrayOutputStream1);
            if (dictHosp.getHospName().equals("澄合矿务局中心医院")){
                String sex = "";
                if (customer.getCusSex() != null) {
                    for (SysDictData userSex : sysUserSex) {
                        if (userSex.getDictValue().equals(String.valueOf(customer.getCusSex()))) {
                            sex = userSex.getDictLabel();
                        }
                    }
                }
                if (StrUtil.isBlank(sex)) sex = "未知";
                pdfWriter.setPageEvent(new FooterHeaderPageEvent("澄合矿务局中心医院",customer.getCusName(),tjOrder.getTjNumber(),sex,String.valueOf(DateUtil.ageOfNow(customer.getCusBrithday()))));
                pageSize = pdfWriter.getPageNumber();
            }
        } catch (DocumentException e) {
            e.printStackTrace();
            return AjaxResult.error();
@@ -123,7 +156,7 @@
        Map<TjOrderRemark, List<TjPdfVO>> printReport = new HashMap<>();
        notHuaYanData(tjOrder.getTjNumber(), printReport, tjOrder, customer);
        try {
            notHuaYanTable(document1, printReport);
            notHuaYanTable(document1, printReport,dictHosp,color);
        } catch (DocumentException e) {
            log.error("非化验项目填充表格异常");
            e.printStackTrace();
@@ -131,10 +164,12 @@
        }
        // 组装检验数据
        HashMap<String, Object> map = makeHisJianYan(tjOrder, customer);
        makeHisJianYanTable(document1, map);
        List<ByteArrayOutputStream> jianchas = makeHisJianChaTable(tjOrder);
        makeHisJianYanTable(document1, map,dictHosp,color);
        List<ByteArrayOutputStream> jianchas =  makeHisJianChaTable(tjOrder);
//        List<ByteArrayOutputStream> jianchas = makeCcgcHisJianChaTable(tjOrder);
        document1.close();
        pdfWriter.close();
        PdfReader reader = null;
        try {
            reader = new PdfReader(byteArrayOutputStream1.toByteArray());
@@ -167,16 +202,18 @@
            int pages = pdfReader.getNumberOfPages();
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            PdfStamper pdfStamper = new PdfStamper(pdfReader, outputStream);
            PdfContentByte contentByte;
            BaseFont baseFont = PdfUtils.createBaseFont(null);
            for (int i = 2; i <= pages; i++) {
                contentByte = pdfStamper.getOverContent(i);
                contentByte.beginText();
                contentByte.setFontAndSize(baseFont, 11);
                float x = contentByte.getPdfDocument().getPageSize().getWidth() / 2;
                float y = 20;
                contentByte.showTextAligned(PdfContentByte.ALIGN_CENTER, String.valueOf(i - 1), x, y, 0);
                contentByte.endText();
            if (!dictHosp.getHospName().equals("澄合矿务局中心医院")){
                PdfContentByte contentByte;
                BaseFont baseFont = PdfUtils.createBaseFont(null);
                for (int i = 2; i <= pages; i++) {
                    contentByte = pdfStamper.getOverContent(i);
                    contentByte.beginText();
                    contentByte.setFontAndSize(baseFont, 11);
                    float x = contentByte.getPdfDocument().getPageSize().getWidth() / 2;
                    float y = 20;
                    contentByte.showTextAligned(PdfContentByte.ALIGN_CENTER, String.valueOf(i - 1), x, y, 0);
                    contentByte.endText();
                }
            }
            pdfStamper.close();
            pdfReader.close();
@@ -202,6 +239,13 @@
        List<LtkjGetexamreportinfo> list = ltkjGetexamreportinfoService.list(lambdaQueryWrapper);
//        List<LtkjGetexamreportinfo> list = ltkjGetexamreportinfoService.list();
        List<ByteArrayOutputStream> jianchas = new ArrayList<>();
        Paragraph elements = new Paragraph();
        elements.setLeading(5f);
        elements.setSpacingBefore(10f);
        elements.setSpacingAfter(10f);
        elements.setAlignment(Element.ALIGN_RIGHT);
        Phrase phrase = new Phrase();
        Font doctorFonts = PdfUtils.setFont(11);
        for (LtkjGetexamreportinfo getexamreportinfo : list) {
            String xm = getexamreportinfo.getHzxm();
            String xb = getexamreportinfo.getHzxb().equals("2") ? "女" : "男";
@@ -223,13 +267,140 @@
            String sqrxm = getexamreportinfo.getSqrxm();
            String zyh = "";
            String ch = "";
            String footer = "申请人:" + sqrxm + "     审核医师:" + shysqm + "     医师签名:" + bgysqm;
            ByteArrayOutputStream outputStream = makeJcPDFByteArrayStream(xm, xb, nl, jcks, zyh, ch, sjks, jcsb, jch, jcxm, ms, ts, null, footer);
            String sqrbh = getexamreportinfo.getSqrbh();
            String shysbh = getexamreportinfo.getShysbh();
            String bgysbh = getexamreportinfo.getBgysbh();
            String jcysqm = getexamreportinfo.getJcysqm();
            String jcysbh = getexamreportinfo.getJcysbh();
            StringBuilder builder;
            String footer;
            // 检查返回的医师编码不属于his医师id 暂注释
//            String key = sysConfigService.selectConfigByKey("is_report_pdf_use_ysqm");
//            if (key.equals("Y")){
//                footer = null;
//                if (null != sqrbh && StrUtil.isNotBlank(sqrbh)){
//                    makeYiShiInfoLine(phrase, doctorFonts, sqrxm, sqrbh,"申请人:");
//                }
//                if (null != jcysbh && StrUtil.isNotBlank(jcysbh)){
//                    makeYiShiInfoLine(phrase, doctorFonts, jcysqm, jcysbh,"     检查医师:");
//                }
//                if (null != shysbh && StrUtil.isNotBlank(shysbh)){
//                    makeYiShiInfoLine(phrase, doctorFonts, shysqm, shysbh,"     审核医师:");
//                }
//                if (null != bgysbh && StrUtil.isNotBlank(bgysbh)){
//                    makeYiShiInfoLine(phrase, doctorFonts, bgysqm, bgysbh,"     报告医师:");
//                }
//            }else {
                builder = new StringBuilder();
                if (null != sqrxm && StrUtil.isNotBlank(sqrxm)){
                    builder.append("申请人:").append(sqrxm);
                }
                if (null != jcysqm && StrUtil.isNotBlank(jcysqm)){
                    builder.append("     检查医师:").append(jcysqm);
                }
                if (null != shysqm && StrUtil.isNotBlank(shysqm)){
                    builder.append("     审核医师:").append(shysqm);
                }
                if (null != bgysqm && StrUtil.isNotBlank(bgysqm)){
                    builder.append("     报告医师:").append(bgysqm);
                }
                footer = builder.toString().trim();
//            }
//            elements.add(phrase);
            ByteArrayOutputStream outputStream = makeJcPDFByteArrayStream(xm, xb, nl, jcks, zyh, ch, sjks, jcsb, jch, jcxm, ms, ts, null, footer,elements);
            if (outputStream == null)
                throw new Exception();
            jianchas.add(outputStream);
        }
        return jianchas;
    }
    /**
     * 生成检查表格存储过程时用
     *
     * @param tjOrder
     * @return
     */
    private List<ByteArrayOutputStream> makeCcgcHisJianChaTable(TjOrder tjOrder) throws Exception {
        TjCustomer customer = tjCustomerService.getById(tjOrder.getUserId());
       List<LtkjExamJcbgd> list=jcbgdService.getJianJcBaoGaoDanByTjh(tjOrder.getCardId());
        List<ByteArrayOutputStream> jianchas = new ArrayList<>();
        Paragraph elements = new Paragraph();
        elements.setLeading(5f);
        elements.setSpacingBefore(10f);
        elements.setSpacingAfter(10f);
        elements.setAlignment(Element.ALIGN_RIGHT);
        for (LtkjExamJcbgd getexamreportinfo : list) {
            String xm = customer.getCusName();
            String xb = customer.getCusSex()==2 ? "女" : "男";
            String nl = customer.getAge();
            String jcks = "体检中心";
            String sjks = "";
            String jcsb = "";
            String jch = getexamreportinfo.getTmh();
            String jcxm = getexamreportinfo.getXmmc();
            String ms = getexamreportinfo.getYxbx();
            String ts = getexamreportinfo.getYxzd();
            String bgysqm = getexamreportinfo.getShysxm();
            String shysqm = getexamreportinfo.getShysdm();
            String sqrxm = "王健萍";
            String zyh = "";
            String ch = "";
            String jcysqm = getexamreportinfo.getShysdm();
            StringBuilder builder;
            String footer;
            builder = new StringBuilder();
            if (null != sqrxm && StrUtil.isNotBlank(sqrxm)){
                builder.append("申请人:").append(sqrxm);
            }
            if (null != jcysqm && StrUtil.isNotBlank(jcysqm)){
                builder.append("     检查医师:").append(jcysqm);
            }
            if (null != shysqm && StrUtil.isNotBlank(shysqm)){
                builder.append("     审核医师:").append(shysqm);
            }
            if (null != bgysqm && StrUtil.isNotBlank(bgysqm)){
                builder.append("     报告医师:").append(bgysqm);
            }
            footer = builder.toString().trim();
            ByteArrayOutputStream outputStream = makeJcPDFByteArrayStream(xm, xb, nl, jcks, zyh, ch, sjks, jcsb, jch, jcxm, ms, ts, null, footer,elements);
            if (outputStream == null)
                throw new Exception();
            jianchas.add(outputStream);
        }
        return jianchas;
    }
    /**
     * 医师信息行
     * @param phrase
     * @param doctorFonts
     * @param sqrxm
     * @param sqrbh
     * @throws BadElementException
     */
    private void makeYiShiInfoLine(Phrase phrase, Font doctorFonts, String sqrxm, String sqrbh,String title) throws BadElementException {
        String qmImg = dictUserInfoMapper.selectQmImgInnerJoinUserByHisDictCode(sqrbh);
//        String qmImg = dictUserInfoMapper.selectQmImgInnerJoinUserByUserId(sqrbh);
        if (null != qmImg && StrUtil.isNotBlank(qmImg)) {
            byte[] decode = Base64.getDecoder().decode(qmImg);
            Image image = null;
            try {
                image = Image.getInstance(decode);
                image.scaleToFit(60, 25);
                phrase.add(new Chunk(title,doctorFonts));
                phrase.add(new Chunk(image,0,-10,true));
            } catch (IOException e) {
                phrase.add(new Chunk(title+sqrxm, doctorFonts));
            }
        }else {
            phrase.add(new Chunk(title+sqrxm, doctorFonts));
        }
    }
    /**
@@ -239,10 +410,9 @@
     * @param customer
     * @param finalOutPut
     */
    private void savePDFFile(String outputFileName1, TjOrder tjOrder, TjCustomer customer, ByteArrayOutputStream finalOutPut) throws IOException {
        // 文件配置
//        String outputPath1 = "/Users/chacca/开发相关/代码/";
        String outputPath1 = value + "\\";
    private void savePDFFile(String outputFileName1, TjOrder tjOrder, TjCustomer customer, ByteArrayOutputStream finalOutPut) throws IOException, DocumentException, InterruptedException {
        // 第一步:生成文件并保存
        String outputPath1 = value + File.separator;
        File file = new File(outputPath1 + outputFileName1);
        BufferedOutputStream outputStream = null;
        outputStream = new BufferedOutputStream(new FileOutputStream(file));
@@ -250,7 +420,30 @@
        outputStream.flush();
        outputStream.close();
        finalOutPut.close();
//        Thread.sleep(2000);
//
//        FileInputStream fileInputStream = new FileInputStream(file);
//        FileOutputStream fileOutputStream = new FileOutputStream(file);
//
//        PdfReader pdfReader = new PdfReader(fileInputStream);
//        PdfStamper pdfStamper = new PdfStamper(pdfReader, fileOutputStream);
//        AcroFields form = pdfStamper.getAcroFields();
//
//        List<String> fieldNames = new ArrayList<>(form.getFields().keySet());
//        if (fieldNames.contains("page")) {
//            form.setField("page", "1111");
//        }
//
//        pdfStamper.setFormFlattening(true);  // 设置为 true 后表单字段不可编辑
//
//        pdfStamper.close();
//        pdfReader.close();
//        fileInputStream.close();
//        fileOutputStream.close();
    }
    /**
     * 填充检验表格数据
@@ -259,18 +452,19 @@
     * @param map
     * @throws DocumentException
     */
    private void makeHisJianYanTable(Document document1, HashMap<String, Object> map) throws DocumentException, IOException {
    private void makeHisJianYanTable(Document document1, HashMap<String, Object> map,DictHosp dictHosp,String colorStr) throws DocumentException {
        if (!map.isEmpty()) {
            String[] titles = new String[]{"体检项目", "体检结果", "单位", "参考范围"};
            float[] titlesWidth = new float[]{120, 120, 120, 120};
            String[] titles = new String[]{"体检项目", "体检结果","标志", "单位", "参考范围"};
            float[] titlesWidth = new float[]{270, 80, 40, 80, 100};
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                String titleName = entry.getKey().trim();
                HashMap<String, Object> entryValue = (HashMap<String, Object>) entry.getValue();
                HashSet<String> jyys = (HashSet<String>) entryValue.get("jyys");
                ArrayList<List<String>> lists = (ArrayList<List<String>>) entryValue.get("data");
                addJianYanTable(document1, titleName, titles, titlesWidth, lists);
                String shsj = entryValue.get("shsj").toString();
                addJianYanTable(document1, titleName, titles, titlesWidth, lists,dictHosp,colorStr);
                if (!jyys.isEmpty()) {
                    Font doctorFonts = PdfUtils.setFont(9);
                    Font doctorFonts = PdfUtils.setFont(11);
                    String doctors = "";
                    Paragraph elements = new Paragraph();
                    elements.setLeading(5f);
@@ -278,7 +472,7 @@
                    elements.setSpacingAfter(10f);
                    elements.setAlignment(Element.ALIGN_RIGHT);
                    Phrase phrase = new Phrase();
                    phrase.add(new Chunk("审核医师:",doctorFonts));
                    phrase.add(new Chunk("检查日期:"+shsj+"         审核医师:",doctorFonts));
                    boolean flag = false;
                    for (String s : jyys) {
                        if (s.contains("|")) {
@@ -286,11 +480,15 @@
                            String[] split = s.split("\\|");
                            String qmImg = dictUserInfoMapper.selectQmImgInnerJoinUserByHisDictCode(split[1]);
                            if (null != qmImg && StrUtil.isNotBlank(qmImg)) {
                                ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(Base64.getDecoder().decode(qmImg));
                                byte[] decode = Base64.getDecoder().decode(qmImg);
                                Image image = Image.getInstance(decode);
                                image.scaleToFit(60, 25);
                                phrase.add(new Chunk(image,0,-10,true));
                                Image image = null;
                                try {
                                    image = Image.getInstance(decode);
                                    image.scaleToFit(60, 25);
                                    phrase.add(new Chunk(image,0,-10,true));
                                } catch (IOException e) {
                                    phrase.add(new Chunk(split[0].trim(),doctorFonts));
                                }
                            } else {
                                phrase.add(new Chunk(split[0].trim(),doctorFonts));
                            }
@@ -300,7 +498,7 @@
                    }
                    if (!flag) {
                        String substring = doctors.substring(0, doctors.length() - 1).trim();
                        Paragraph df = PdfUtils.setParagraph(doctorFonts, "审核医师:" + substring);
                        Paragraph df = PdfUtils.setParagraph(doctorFonts, "检查日期:"+shsj+"         审核医师:" + substring);
                        df.setAlignment(Element.ALIGN_RIGHT);
                        document1.add(df);
                    } else {
@@ -309,9 +507,11 @@
                    }
                }
                //分割线
                LineSeparator objectName = new LineSeparator();
                objectName.setOffset(-5);
                document1.add(objectName);
                if (!dictHosp.getHospName().equals("澄合矿务局中心医院")) {
                    LineSeparator objectName = new LineSeparator();
                    objectName.setOffset(-5);
                    document1.add(objectName);
                }
            }
        }
    }
@@ -323,7 +523,7 @@
     * @param printReport
     * @throws DocumentException
     */
    private void notHuaYanTable(Document document1, Map<TjOrderRemark, List<TjPdfVO>> printReport) throws DocumentException {
    private void notHuaYanTable(Document document1, Map<TjOrderRemark, List<TjPdfVO>> printReport,DictHosp dictHosp,String colorStr) throws DocumentException {
        for (Map.Entry<TjOrderRemark, List<TjPdfVO>> entry : printReport.entrySet()) {
            LambdaQueryWrapper<TjProject> wqqq = new LambdaQueryWrapper<>();
            wqqq.eq(TjProject::getProId, entry.getKey().getProId());
@@ -337,6 +537,25 @@
                    // 设置标题字体样式
                    Font titleFonts = PdfUtils.setFont(9);
                    Paragraph paragraph = PdfUtils.setParagraph(titleFonts, titleName);
                    if (dictHosp.getHospName().equals("澄合矿务局中心医院")) {
                        Font titleFont = PdfUtils.setFont(11);
                        titleFont.setStyle(Font.BOLD);
                        PdfPCell cellTitle = new PdfPCell(PdfUtils.setParagraph(titleFont, titleName));
                        cellTitle.setBorder(Rectangle.NO_BORDER);
                        Color color = Color.decode(colorStr);
                        cellTitle.setBackgroundColor(new BaseColor(color.getRed(), color.getGreen(), color.getBlue())); // 设置背景颜色(十六进制 RGB)
                        // 创建表格并添加单元格
                        PdfPTable tableTitle = new PdfPTable(1);
                        tableTitle.setWidthPercentage(100);
                        tableTitle.addCell(cellTitle);
                        // 将表格添加到文档中
                        document1.add(tableTitle);
                    }else {
                        document1.add(paragraph);
                    }
                    String[] titles = {"体检项目", "体检结果", "单位"};
                    // 获取列表数据
                    //设置表头字体样式
@@ -345,7 +564,7 @@
                    Font textFont = PdfUtils.setFont(9);
                    //创建表格  将表头字体和正文字体放进去
                    PdfPTable table = PdfUtils.setTable2(headFont, textFont, titles, value);
                    document1.add(paragraph);
                    document1.add(table);
                    //判断备注是否为空  空不能显示null
                    if (entry.getKey().getRemark() == null) {
@@ -373,23 +592,12 @@
                        document1.add(pp);
                    }
                    //判断主检医师是否为空  空不能显示null
                    if (null != entry.getKey().getDoctorName() && null != userService.getById(entry.getKey().getDoctorName())) {
                        //主检医师
                        String doctorName = "主检医师:" + userService.getById(entry.getKey().getDoctorName()).getNickName();
                        Font doctorFonts = PdfUtils.setFont(9);
                        Paragraph df = PdfUtils.setParagraph(doctorFonts, doctorName);
                        df.setAlignment(Element.ALIGN_RIGHT);
                        document1.add(df);
                    } else {
                        String doctorName = "主检医师:" + "无";
                        Font doctorFonts = PdfUtils.setFont(9);
                        Paragraph df = PdfUtils.setParagraph(doctorFonts, doctorName);
                        df.setAlignment(Element.ALIGN_RIGHT);
                        document1.add(df);
                    }
                    zhuJianYiShi(document1, entry);
                    //分割线
                    LineSeparator objectName = new LineSeparator();
                    document1.add(objectName);
                    if (!dictHosp.getHospName().equals("澄合矿务局中心医院")) {
                        LineSeparator objectName = new LineSeparator();
                        document1.add(objectName);
                    }
                } else {
                    if (null != one11) {
                        titleName = one11.getProName();
@@ -399,6 +607,24 @@
                    // 设置标题字体样式
                    Font titleFonts = PdfUtils.setFont(9);
                    Paragraph paragraph = PdfUtils.setParagraph(titleFonts, titleName);
                    if (dictHosp.getHospName().equals("澄合矿务局中心医院")) {
                        Font titleFont = PdfUtils.setFont(11);
                        titleFont.setStyle(Font.BOLD);
                        PdfPCell cellTitle = new PdfPCell(PdfUtils.setParagraph(titleFont, titleName));
                        cellTitle.setBorder(Rectangle.NO_BORDER);
                        Color color = Color.decode("#B4CDCD");
                        cellTitle.setBackgroundColor(new BaseColor(color.getRed(), color.getGreen(), color.getBlue())); // 设置背景颜色(十六进制 RGB)
                        // 创建表格并添加单元格
                        PdfPTable tableTitle = new PdfPTable(1);
                        tableTitle.setWidthPercentage(100);
                        tableTitle.addCell(cellTitle);
                        // 将表格添加到文档中
                        document1.add(tableTitle);
                    }else {
                        document1.add(paragraph);
                    }
                    String[] titles = {"体检项目", "体检结果", "单位"};
                    // 获取列表数据
                    //设置表头字体样式
@@ -407,7 +633,6 @@
                    Font textFont = PdfUtils.setFont(9);
                    //创建表格  将表头字体和正文字体放进去
                    PdfPTable table = PdfUtils.setTable(headFont, textFont, titles, value);
                    document1.add(paragraph);
                    document1.add(table);
                    //判断备注是否为空  空不能显示null
                    if (entry.getKey().getRemark() == null) {
@@ -435,25 +660,71 @@
                        document1.add(pp);
                    }
                    //判断主检医师是否为空  空不能显示null
                    if (null != entry.getKey().getDoctorName() && null != userService.getById(entry.getKey().getDoctorName())) {
                        //主检医师
                        String doctorName = "主检医师:" + userService.getById(entry.getKey().getDoctorName()).getNickName();
                        Font doctorFonts = PdfUtils.setFont(9);
                        Paragraph df = PdfUtils.setParagraph(doctorFonts, doctorName);
                        df.setAlignment(Element.ALIGN_RIGHT);
                        document1.add(df);
                    } else {
                        String doctorName = "主检医师:" + "无";
                        Font doctorFonts = PdfUtils.setFont(9);
                    zhuJianYiShi(document1, entry);
                    if (!dictHosp.getHospName().equals("澄合矿务局中心医院")) {
                        //分割线
                        LineSeparator objectName = new LineSeparator();
                        document1.add(objectName);
                    }
                }
            }
        }
    }
    /**
     * 主见医师行显示设置
     * @param document1
     * @param entry
     * @throws DocumentException
     */
    private void zhuJianYiShi(Document document1, Map.Entry<TjOrderRemark, List<TjPdfVO>> entry) throws DocumentException {
        if (null != entry.getKey().getDoctorName() && null != userService.getById(entry.getKey().getDoctorName())) {
            //主检医师
            String key = sysConfigService.selectConfigByKey("is_report_pdf_use_ysqm");
            SysUser sysUser = userService.getById(entry.getKey().getDoctorName());
            Font doctorFonts = PdfUtils.setFont(9);
            if (key.equals("Y")){
                String qmImg = dictUserInfoMapper.selectQmImgInnerJoinUserByUserId(String.valueOf(sysUser.getUserId()));
                if (null != qmImg && StrUtil.isNotBlank(qmImg)) {
                    Paragraph elements = new Paragraph();
                    elements.setLeading(5f);
                    elements.setSpacingBefore(10f);
                    elements.setSpacingAfter(10f);
                    elements.setAlignment(Element.ALIGN_RIGHT);
                    Phrase phrase = new Phrase();
                    phrase.add(new Chunk("主检医师:",doctorFonts));
                    byte[] decode = Base64.getDecoder().decode(qmImg);
                    Image image = null;
                    try {
                        image = Image.getInstance(decode);
                        image.scaleToFit(60, 25);
                        phrase.add(new Chunk(image,0,-10,true));
                        elements.add(phrase);
                        document1.add(elements);
                    } catch (IOException e) {
                        String doctorName = "主检医师:" + sysUser.getNickName();
                        Paragraph df = PdfUtils.setParagraph(doctorFonts, doctorName);
                        df.setAlignment(Element.ALIGN_RIGHT);
                        document1.add(df);
                    }
                    //分割线
                    LineSeparator objectName = new LineSeparator();
                    document1.add(objectName);
                }else {
                    String doctorName = "主检医师:" + sysUser.getNickName();
                    Paragraph df = PdfUtils.setParagraph(doctorFonts, doctorName);
                    df.setAlignment(Element.ALIGN_RIGHT);
                    document1.add(df);
                }
            }else {
                String doctorName = "主检医师:" + sysUser.getNickName();
                Paragraph df = PdfUtils.setParagraph(doctorFonts, doctorName);
                df.setAlignment(Element.ALIGN_RIGHT);
                document1.add(df);
            }
        } else {
            String doctorName = "主检医师:" + "无";
            Font doctorFonts = PdfUtils.setFont(9);
            Paragraph df = PdfUtils.setParagraph(doctorFonts, doctorName);
            df.setAlignment(Element.ALIGN_RIGHT);
            document1.add(df);
        }
    }
@@ -461,7 +732,6 @@
        LambdaQueryWrapper<LtkjHysqd> ltkjHysqdLambdaQueryWrapper = new LambdaQueryWrapper<>();
        ltkjHysqdLambdaQueryWrapper.eq(LtkjHysqd::getTjh, tjOrder.getCardId());
        List<LtkjHysqd> list = ltkjHysqdService.list(ltkjHysqdLambdaQueryWrapper);
//        List<LtkjHysqd> list = ltkjHysqdService.list();
        HashMap<String, Object> data = new HashMap<>();
        for (LtkjHysqd hysqd : list) {
            LambdaQueryWrapper<LtkjHybgd> ltkjHybgdLambdaQueryWrapper = new LambdaQueryWrapper<>();
@@ -471,7 +741,9 @@
            String xmmc = hysqd.getXmmc();
            ArrayList<List<String>> lists = new ArrayList<>();
            HashSet<String> hashSet = new HashSet<>();
            String shsj = "";
            for (LtkjHybgd hybgd : hybgds) {
                shsj = hybgd.getShsj();
                // 检查项目
                String jcxm = hybgd.getJcxm() != null ? hybgd.getJcxm().trim() : null;
                // 检验结果
@@ -486,6 +758,8 @@
                String shysmc = hybgd.getShysmc() != null ? hybgd.getShysmc().trim() : null;
                // 审核医师编码
                String shys = hybgd.getShys() != null ? hybgd.getShys().trim() : null;
                String ycbz = "";
                if (jyjg != null && StrUtil.isNotBlank(jyjg) && fwz != null && StrUtil.isNotBlank(fwz)) {
                    try {
                        String[] fwzs = fwz.split("-");
@@ -495,10 +769,12 @@
                        // 比较检验结果和范围值
                        if (jyjgval.compareTo(min) < 0) {
                            // jyjg 小于范围最小值,添加下箭头
                            jyjg = jyjg + "   ↓";
//                            jyjg = jyjg + "   ↓";
                            ycbz = "↓";
                        } else if (jyjgval.compareTo(max) > 0) {
                            // jyjg 大于范围最大值,添加上箭头
                            jyjg = jyjg + "   ↑";
//                            jyjg = jyjg + "   ↑";
                            ycbz = "↑";
                        }
                    } catch (Exception ignored) {
                    }
@@ -517,6 +793,7 @@
                ArrayList<String> strings = new ArrayList<>();
                strings.add(jcxm);
                strings.add(jyjg);
                strings.add(ycbz);
                strings.add(jgdw);
                strings.add(fwz);
                lists.add(strings);
@@ -525,6 +802,10 @@
                HashMap<String, Object> map = new HashMap<>();
                map.put("data", lists);
                map.put("jyys", hashSet);
                if (StrUtil.isNotBlank(shsj)){
                    shsj = shsj.split(" ")[0];
                }
                map.put("shsj",shsj);
                data.put(xmmc, map);
            }
        }
@@ -611,6 +892,7 @@
            }
            //异常项目
            data.put("yichang", str.toString());
            data.put("zjrq",new SimpleDateFormat("yyyy-MM-dd").format(tjOrder.getCheckTime()));
            // 遍历data 给pdf表单表格赋值
            for (String key : data.keySet()) {
                acroFields.setField(key, data.get(key).toString());
@@ -638,6 +920,7 @@
            map.put("document", document);
            map.put("copy", copy);
            map.put("stream", finalOutPut);
            map.put("form",pdfStamper);
            return map;
        } catch (IOException | DocumentException e) {
            e.printStackTrace();
@@ -654,12 +937,13 @@
     * @param customer
     */
    private void notHuaYanData(String tjNumber, Map<TjOrderRemark, List<TjPdfVO>> printReport, TjOrder one, TjCustomer customer) {
        LambdaQueryWrapper<TjOrderRemark> wqq = new LambdaQueryWrapper<>();
        wqq.eq(TjOrderRemark::getTjNumber, tjNumber);
        wqq.ne(TjOrderRemark::getDeptId, "241");
        wqq.in(TjOrderRemark::getDeptId, "269", "270", "253", "254", "255", "257");
        wqq.notIn(TjOrderRemark::getProId, projectService.getNneedReprotProId());
        List<TjOrderRemark> tjOrderRemarks = tjOrderRemarkService.list(wqq);
//        LambdaQueryWrapper<TjOrderRemark> wqq = new LambdaQueryWrapper<>();
//        wqq.eq(TjOrderRemark::getTjNumber, tjNumber);
//        wqq.ne(TjOrderRemark::getDeptId, "241");
//        wqq.in(TjOrderRemark::getDeptId, "269", "270", "253", "254", "255", "257");
//        wqq.notIn(TjOrderRemark::getProId, projectService.getNneedReprotProId());
//        List<TjOrderRemark> tjOrderRemarks = tjOrderRemarkService.list(wqq);
        List<TjOrderRemark> tjOrderRemarks = tjOrderRemarkService.notHuaYanData(tjNumber);
        for (TjOrderRemark tjOrderRemark : tjOrderRemarks) {
            printReport.put(tjOrderRemark, null);
        }
@@ -810,10 +1094,14 @@
        document.add(table);
    }
    private static void addJianYanTable(Document document, String titleName, String[] titles, float[] titlesWidth, ArrayList<List<String>> lists) throws DocumentException {
        Font titleFont = PdfUtils.setFont(9);
    private static void addJianYanTable(Document document, String titleName, String[] titles, float[] titlesWidth, ArrayList<List<String>> lists,DictHosp dictHosp,String colorStr) throws DocumentException {
        // 大项标题
        Font titleFont = PdfUtils.setFont(10);
        if (dictHosp.getHospName().equals("澄合矿务局中心医院")) {
            titleFont.setSize(11);
            titleFont.setStyle(Font.BOLD);
        }
        Paragraph paragraph = new Paragraph(titleName, titleFont);
        // 设置文字居中
        paragraph.setAlignment(Element.ALIGN_LEFT);
        // 行间距
        paragraph.setLeading(5f);
@@ -821,13 +1109,34 @@
        paragraph.setSpacingBefore(10f);
        // 设置段落下空白
        paragraph.setSpacingAfter(10f);
        document.add(paragraph);
        if (dictHosp.getHospName().equals("澄合矿务局中心医院")) {
            // 行间距
            paragraph.setLeading(7f);
            // 设置段落上空白
            paragraph.setSpacingBefore(12f);
            // 设置段落下空白
            paragraph.setSpacingAfter(12f);
            // 大项
            PdfPCell cellTitle = new PdfPCell(paragraph);
            cellTitle.setBorder(Rectangle.NO_BORDER);
            Color color = Color.decode(colorStr);
            cellTitle.setBackgroundColor(new BaseColor(color.getRed(), color.getGreen(), color.getBlue())); // 设置背景颜色(十六进制 RGB)
            // 创建表格并添加单元格
            PdfPTable tableTitle = new PdfPTable(1);
            tableTitle.setWidthPercentage(100);
            tableTitle.addCell(cellTitle);
            // 将表格添加到文档中
            document.add(tableTitle);
        }else {
            document.add(paragraph);
        }
        // 创建一个表格并添加到文档
        Font headFont = PdfUtils.setFont(9);
        Font textFont = PdfUtils.setFont(9);
        Font headFont = PdfUtils.setFont(10);
        Font textFont = PdfUtils.setFont(10);
        PdfPTable table = new PdfPTable(titlesWidth);
        table.setTotalWidth(PageSize.A4.getWidth() - 100); // 设置表格总宽度
        table.setLockedWidth(true); // 锁定表格宽度
        table.setTotalWidth(PageSize.A4.getWidth() - 10); // 设置表格总宽度
        //table.setLockedWidth(true); // 锁定表格宽度
        table.setHorizontalAlignment(Element.ALIGN_LEFT);
        table.getDefaultCell().setBorder(0);
        table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT);
@@ -836,15 +1145,36 @@
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell.setHorizontalAlignment(Element.ALIGN_LEFT);
            cell.setBorder(Rectangle.NO_BORDER); // 移除单元格边框
//            Color color = Color.decode(colorStr);
//            cell.setBackgroundColor(new BaseColor(color.getRed(), color.getGreen(), color.getBlue())); // 设置背景颜色(十六进制 RGB)
            table.addCell(cell);
        }
        for (List<String> list : lists) {
            boolean isYc = false;
            textFont = PdfUtils.setFont(10);
            if (dictHosp.getHospName().equals("澄合矿务局中心医院")){
                if (list.contains("↓") || list.contains("↑")){
                    isYc = true;
                }
            }
            for (String s : list) {
                PdfPCell nameCell = new PdfPCell();
                nameCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
                nameCell.setHorizontalAlignment(Element.ALIGN_LEFT);
                nameCell.setPhrase(new Paragraph(s, textFont));
                nameCell.setBorder(Rectangle.NO_BORDER); // 移除单元格边框
                if (isYc){
                    textFont.setStyle(Font.BOLD);
                    nameCell.setPhrase(new Paragraph(s, textFont));
                    nameCell.setBorder(Rectangle.NO_BORDER);
//                    Color color = Color.decode("#0033cc");
//                    nameCell.setBackgroundColor(new BaseColor(color.getRed(), color.getGreen(), color.getBlue())); // 设置背景颜色(十六进制 RGB)
                }else {
                    nameCell.setPhrase(new Paragraph(s, textFont));
                }
                table.addCell(nameCell);
            }
        }
@@ -870,12 +1200,17 @@
     * @param footer
     * @return bytearrayoutputstream
     */
    public static ByteArrayOutputStream makeJcPDFByteArrayStream(String xm, String xb, String nl, String jcks, String zyh, String ch, String sjks, String jcsb, String jch, String jcxm, String ms, String ts, File[] files, String footer) {
    public static ByteArrayOutputStream makeJcPDFByteArrayStream(String xm, String xb, String nl, String jcks, String zyh, String ch, String sjks, String jcsb, String jch
            , String jcxm, String ms, String ts, File[] files, String footer,Paragraph elements) {
        try {
            Document document = new Document(PageSize.A4);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            PdfWriter writer = PdfWriter.getInstance(document, baos);
            writer.setPageEvent(new Footer(footer));
            if (footer != null) {
                writer.setPageEvent(new Footer(footer));
            } else {
                writer.setPageEvent(new Footer(elements));
            }
            document.open();
            document.setMargins(70, 70, 40, 40);
@@ -886,7 +1221,7 @@
            table1.setSpacingAfter(10f);
            Font titleFont = PdfUtils.setFont(12);
            PdfPCell mergedCell = new PdfPCell(new Phrase("泾 川 县 人 民 医 院", titleFont));
            PdfPCell mergedCell = new PdfPCell(new Phrase("陕健医澄合矿务局中心医院", titleFont));
            mergedCell.setBorder(Rectangle.NO_BORDER);
            mergedCell.setColspan(10);
            mergedCell.setHorizontalAlignment(Element.ALIGN_CENTER);
@@ -1146,9 +1481,14 @@
    static class Footer extends PdfPageEventHelper {
        private String footerText;
        private Font footerFont = PdfUtils.setFont(10);
        private Paragraph paragraph;
        public Footer(String footerText) {
            this.footerText = footerText;
        }
        public Footer(Paragraph paragraph){
            this.paragraph = paragraph;
        }
        @Override
@@ -1158,8 +1498,136 @@
            footer.setWidthPercentage(100);
            footer.getDefaultCell().setBorder(Rectangle.NO_BORDER);
            footer.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
            footer.addCell(new Phrase(footerText, footerFont));
            if (footerText != null)
                footer.addCell(new Phrase(footerText, footerFont));
            if (paragraph != null)
                footer.addCell(paragraph);
            footer.writeSelectedRows(0, -1, 36, 50, writer.getDirectContent());
        }
    }
    // 自定义页脚和页眉的绘制
    static class FooterHeaderPageEvent extends PdfPageEventHelper {
        private String name; // 页眉的名字
        private String tjName;
        private String tjNumber;
        private String sex;
        private String age;
        public FooterHeaderPageEvent(String name,String tjName,String tjNumber,String sex,String age) {
            this.name = name;
            this.tjNumber = tjNumber;
            this.tjName = tjName;
            this.sex = sex;
            this.age = age;
        }
        // 在每一页的顶部绘制页眉
        @Override
        public void onStartPage(PdfWriter writer, Document document) {
            // 获取页面宽度和高度
            float width = document.getPageSize().getWidth();
            float margin = document.leftMargin();
            // 创建页眉表格:2行,第一行包含姓名、性别、年龄和体检号,第二行是分割线
            PdfPTable headerTable = new PdfPTable(2);  // 2列:第一列为姓名、性别、年龄,第二列为体检号
            headerTable.setWidthPercentage(100); // 设置宽度为100%
            headerTable.setSpacingAfter(10); // 页眉与内容之间的间距
            // 设置列宽度
            float[] columnWidths = {0.6f, 0.4f}; // 第一列占 60%,第二列占 40%
            try {
                headerTable.setWidths(columnWidths);
            } catch (DocumentException e) {
                e.printStackTrace();
            }
            // 第一行:姓名、性别、年龄以及体检号
            PdfPCell infoCell = new PdfPCell(new Phrase("姓名:" + tjName + " 性别:" + sex + " 年龄:" + age, PdfUtils.setFont(8)));
            infoCell.setBorder(Rectangle.NO_BORDER);
            infoCell.setHorizontalAlignment(Element.ALIGN_LEFT); // 第一列左对齐
            infoCell.setVerticalAlignment(Element.ALIGN_MIDDLE); // 垂直居中
            headerTable.addCell(infoCell);
            PdfPCell idCell = new PdfPCell(new Phrase("体检号:" + tjNumber, PdfUtils.setFont(8)));
            idCell.setBorder(Rectangle.NO_BORDER);
            idCell.setHorizontalAlignment(Element.ALIGN_RIGHT); // 第二列右对齐
            idCell.setVerticalAlignment(Element.ALIGN_MIDDLE); // 垂直居中
            headerTable.addCell(idCell);
            // 第二行:淡灰色分割线
            PdfPCell separatorCell = new PdfPCell();
            separatorCell.setBorder(Rectangle.TOP);  // 设置上边框
            separatorCell.setBorderColor(BaseColor.LIGHT_GRAY); // 设置为淡灰色
            separatorCell.setBorderWidthTop(0.5f); // 设置上边框的宽度
            separatorCell.setColspan(2); // 合并两列
            headerTable.addCell(separatorCell);
            // 将页眉表格添加到文档
            try {
                document.add(headerTable);
            } catch (DocumentException e) {
                e.printStackTrace();
            }
        }
        // 在每一页的底部绘制页脚
        @SneakyThrows
        @Override
        public void onEndPage(PdfWriter writer, Document document) {
            // 获取页面宽度和高度
            float width = document.getPageSize().getWidth();
            float height = document.getPageSize().getHeight();
            float margin = document.leftMargin();
            // 页脚距离底部的位置,确保其位于页面底部 增加是上移 减少是下移
            float footerPositionY = document.bottomMargin();
            // 页脚表格:2行2列,第一行医院名和页码,第二行祝福语
            PdfPTable footerTable = new PdfPTable(2); // 2列,第一列医院名,第二列页码
            footerTable.setWidthPercentage(100); // 设置宽度为100%,使其水平居中
            footerTable.setTotalWidth(width - margin * 2 + 10); // 设置总宽度,避免与页边距重叠
            footerTable.setSpacingBefore(0); // 去除表格顶部的间距
            footerTable.setSpacingAfter(0); // 去除表格底部的间距
            footerTable.getDefaultCell().setBorder(Rectangle.NO_BORDER); // 去除所有单元格的边框
            float[] columnWidths = { 2.5f, 2f };  // 第一列占 1,第二列占 2
            footerTable.setWidths(columnWidths); // 设置列宽比例
            // 第一行:医院名和页码
            PdfPCell hospitalNameCell = new PdfPCell(new Phrase(name, PdfUtils.setFont(8)));
            hospitalNameCell.setHorizontalAlignment(Element.ALIGN_RIGHT); // 水平居中
            hospitalNameCell.setVerticalAlignment(Element.ALIGN_TOP); // 垂直对齐到底部
            hospitalNameCell.setMinimumHeight(12f); // 设置最小高度,避免高度过大
            hospitalNameCell.setBorder(Rectangle.TOP); // 设置上边框
            hospitalNameCell.setBorderColor(BaseColor.LIGHT_GRAY); // 设置上边框为淡灰色
            hospitalNameCell.setBorderWidthTop(0.5f); // 设置上边框宽度
            footerTable.addCell(hospitalNameCell);
            // 创建页码的单元格:右对齐
//            String pageText = "第 " + writer.getPageNumber() + 1 + " 页,共 " + writer.getPageNumber() + " 页"; // 页码
            String pageText = "第 " + (writer.getPageNumber() + 1) + " 页"; // 页码
            PdfPCell pageCell = new PdfPCell(new Phrase(pageText, PdfUtils.setFont(8)));
            pageCell.setHorizontalAlignment(Element.ALIGN_RIGHT); // 右对齐
            pageCell.setVerticalAlignment(Element.ALIGN_TOP); // 垂直对齐到底部
            pageCell.setMinimumHeight(12f); // 设置最小高度,避免高度过大
            pageCell.setBorder(Rectangle.TOP); // 设置上边框
            pageCell.setBorderColor(BaseColor.LIGHT_GRAY); // 设置上边框为淡灰色
            pageCell.setBorderWidthTop(0.5f); // 设置上边框宽度
            footerTable.addCell(pageCell);
            // 第二行:祝福语,合并两列
            PdfPCell footerTextCell = new PdfPCell(new Phrase("本体检报告仅供临床参考,不作为临床依据,祝您身体健康!!!", PdfUtils.setFont(8)));
            footerTextCell.setColspan(2); // 合并两列
            footerTextCell.setHorizontalAlignment(Element.ALIGN_CENTER); // 居中
            footerTextCell.setVerticalAlignment(Element.ALIGN_TOP); // 垂直对齐到底部
            footerTextCell.setMinimumHeight(14f); // 设置最小高度,避免高度过大
            footerTextCell.setBorder(Rectangle.NO_BORDER); // 去除所有边框
            footerTable.addCell(footerTextCell);
            // 页脚表格的位置:将表格写入页脚,Y 坐标需要设置为距离页面底部指定的位置
            footerTable.writeSelectedRows(0, -1, margin, footerPositionY, writer.getDirectContent());
        }
    }
}