zhaowenxuan
2024-12-07 497c4100c511e6880cf67817a4966196680b38cb
ltkj-admin/src/main/java/com/ltkj/web/controller/his/HisPDFUtil.java
@@ -3,11 +3,16 @@
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
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;
@@ -18,14 +23,17 @@
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;
@@ -34,6 +42,7 @@
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;
import java.util.stream.Collectors;
/**
 * 检查 检验报告pdf生成
@@ -81,6 +90,10 @@
    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;
@@ -104,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();
@@ -113,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();
@@ -125,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();
@@ -133,13 +164,12 @@
        }
        // 组装检验数据
        HashMap<String, Object> map = makeHisJianYan(tjOrder, customer);
        makeHisJianYanTable(document1, map);
        makeHisJianYanTable(document1, map,dictHosp,color);
        List<ByteArrayOutputStream> jianchas = makeHisJianChaTable(tjOrder);
        List<ByteArrayOutputStream> jianchas =  makeHisJianChaTable(tjOrder);
//        List<ByteArrayOutputStream> jianchas = makeCcgcHisJianChaTable(tjOrder);
        document1.close();
        pdfWriter.close();
        PdfReader reader = null;
        try {
            reader = new PdfReader(byteArrayOutputStream1.toByteArray());
@@ -172,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();
@@ -378,9 +410,8 @@
     * @param customer
     * @param finalOutPut
     */
    private void savePDFFile(String outputFileName1, TjOrder tjOrder, TjCustomer customer, ByteArrayOutputStream finalOutPut) throws IOException {
        // 文件配置
//        String outputPath1 = "/Users/chacca/开发相关/代码/";
    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;
@@ -389,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();
    }
    /**
     * 填充检验表格数据
@@ -398,16 +452,17 @@
     * @param map
     * @throws DocumentException
     */
    private void makeHisJianYanTable(Document document1, HashMap<String, Object> map) throws DocumentException {
    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(11);
                    String doctors = "";
@@ -417,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("|")) {
@@ -443,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 {
@@ -452,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);
                }
            }
        }
    }
@@ -466,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());
@@ -480,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 = {"体检项目", "体检结果", "单位"};
                    // 获取列表数据
                    //设置表头字体样式
@@ -488,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) {
@@ -518,8 +594,10 @@
                    //判断主检医师是否为空  空不能显示null
                    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();
@@ -529,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 = {"体检项目", "体检结果", "单位"};
                    // 获取列表数据
                    //设置表头字体样式
@@ -537,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) {
@@ -566,9 +661,11 @@
                    }
                    //判断主检医师是否为空  空不能显示null
                    zhuJianYiShi(document1, entry);
                    //分割线
                    LineSeparator objectName = new LineSeparator();
                    document1.add(objectName);
                    if (!dictHosp.getHospName().equals("澄合矿务局中心医院")) {
                        //分割线
                        LineSeparator objectName = new LineSeparator();
                        document1.add(objectName);
                    }
                }
            }
        }
@@ -644,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;
                // 检验结果
@@ -659,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("-");
@@ -668,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) {
                    }
@@ -690,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);
@@ -698,6 +802,7 @@
                HashMap<String, Object> map = new HashMap<>();
                map.put("data", lists);
                map.put("jyys", hashSet);
                map.put("shsj",shsj);
                data.put(xmmc, map);
            }
        }
@@ -790,7 +895,7 @@
                acroFields.setField(key, data.get(key).toString());
            }
            //设置为无法编辑
            pdfStamper.setFormFlattening(true);
//            pdfStamper.setFormFlattening(true);
            pdfStamper.close();
            reader.close();
            // 将修改后的PDF内容写入
@@ -812,6 +917,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();
@@ -985,10 +1091,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);
@@ -996,13 +1106,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);
@@ -1011,15 +1142,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);
            }
        }
@@ -1350,4 +1502,129 @@
            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());
        }
    }
}