diff --git a/doc/sql脚本.sql b/doc/sql脚本.sql index 0fecbec..b29a88b 100644 --- a/doc/sql脚本.sql +++ b/doc/sql脚本.sql @@ -1,7 +1,12 @@ --commomtable表新增字段 wj 2024-08-19 ALTER TABLE commomtable - ADD medical_no varchar(255) NULL, + ADD + memo varchar(255) NULL, + id_card varchar(255) NULL, + file_source nvarchar(20) NULL, + ph varchar(255) NULL, + medical_no varchar(255) NULL, female_name varchar(255) NULL, male_name varchar(255) NULL, cycle_type varchar(255) NULL, diff --git a/pom.xml b/pom.xml index c6adb4e..8f8d4ac 100644 --- a/pom.xml +++ b/pom.xml @@ -44,6 +44,7 @@ 3.9 1.16.8 5.5.7 + 5.2.0 1.1.3 6.1.5.Final @@ -213,6 +214,11 @@ ${itextpdf.version} compile + + com.itextpdf + itext-asian + ${itextasian.version} + org.apache.pdfbox diff --git a/src/main/java/com/emr/controller/FontController.java b/src/main/java/com/emr/controller/FontController.java index a3fcc76..9abb98d 100644 --- a/src/main/java/com/emr/controller/FontController.java +++ b/src/main/java/com/emr/controller/FontController.java @@ -42,6 +42,7 @@ import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.UsernamePasswordToken; import org.apache.shiro.subject.Subject; import org.apache.shiro.util.CollectionUtils; +import org.json.JSONArray; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; @@ -51,6 +52,7 @@ import org.springframework.util.Base64Utils; import org.springframework.util.ObjectUtils; import org.springframework.web.bind.annotation.*; +import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.*; @@ -658,9 +660,14 @@ public class FontController { @RequestParam(value="admissId",required = false) String admissId, @RequestParam(value="outpatientNo",required = false) String outpatientNo) { + System.out.println("开始跳转接口准备鉴权。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。"); + try { String userName = request.getParameter("userName"); String dataSource = request.getParameter("dataSource"); + + System.out.println("获取接口传递的参数{}--------------------------用户账号userName为:" + userName + "---------dataSource为:" + dataSource); + if(ObjectUtils.isEmpty(userName)){ model.addAttribute("msg", "用户账号不能为空"); return "font/msg"; @@ -677,6 +684,9 @@ public class FontController { */ userParams.put("userName", userName); String userResult = HttpClientUtils.doPost(POWER_URLHEAD + "/queryUserByUserNameAndPassword", userParams); + + System.out.println("通过用户账号获取的用户信息为:" + userResult); + JSONObject userResultJson = JSONObject.parseObject(userResult); if(ObjectUtils.isEmpty(userResultJson)){ model.addAttribute("msg", "用户账号不存在"); @@ -690,9 +700,17 @@ public class FontController { params.put("userPwd", userResultJson.getString("userPwd")); params.put("remark", "GZINTERFACE"); + System.out.println("开始模拟登录------------参数为:" + params); + String result = HttpClientUtils.doPost(POWER_URLHEAD + "/login", params); JSONObject jsonObject = JSONObject.parseObject(result); + + System.out.println("模拟登录成功------------返回结果为:" + jsonObject); + String token = jsonObject.getString("token"); + + System.out.println("登录成功------------token为:" + token); + if(!ObjectUtils.isEmpty(token)){ this.getUserInfo(request, token, userName); //查询表格配置表的数据,根据配置动态显示表格字段 @@ -753,14 +771,21 @@ public class FontController { Power_User powerUser = JSON.parseObject(objects[0].toString(), Power_User.class); powerUser.setUserName(userName); + System.out.println("调用power系统登录成功之后的用户信息为----------------------------------------------------------------" + JSONObject.toJSONString(powerUser)); + //设置进session - request.getSession().setAttribute("CURRENT_USER", powerUser); + //request.getSession().setAttribute("CURRENT_USER", powerUser); + ServletContext context = request.getServletContext(); + context.setAttribute("CURRENT_USER", powerUser); request.getSession().setAttribute("power_menus", powerUser.getMenus()); request.getSession().setAttribute("token", token); //验证shiro(有shiro才此操作) UsernamePasswordToken userToken = new UsernamePasswordToken(userName, "123456"); + + System.out.println("验证shiro获取userToken为----------------------------------------------------------" + JSONObject.toJSONString(userToken)); + Subject subject = SecurityUtils.getSubject(); subject.login(userToken); } @@ -800,7 +825,118 @@ public class FontController { */ @RequestMapping(value = "getOutpatientData", method = RequestMethod.POST) @ResponseBody - public void getOutpatientData() { + public Msg getOutpatientData(@RequestBody String json) { + try { + Map data = new HashMap<>(); //数据集合 + //json = new String(Files.readAllBytes(Paths.get("C:\\Users\\Lenovo\\OneDrive\\桌面\\data.json")), StandardCharsets.UTF_8); + + String patientID = "";//患者唯一标识 + String medicalRecordNo = "";//病历号 + String handleTime = "";//就诊时间 + String visitCount = "";//就诊次数 + String patientName = "";//姓名 + String birthday = "";//出生日期 + String sex = "";//性别 + String SSN = "";//身份证号码 + + // 创建一个JSONObject对象 + org.json.JSONObject jsonObjectData = new org.json.JSONObject(json); + + // 获取Request请求数据 + if (jsonObjectData.has("Request")) { + org.json.JSONObject requestData = jsonObjectData.getJSONObject("Request"); + + // 获取返回的body数据并转为JSONObject对象 + if (requestData.has("Body")) { + org.json.JSONObject requestBodyData = requestData.getJSONObject("Body"); + + /** + * 获取病历号 + * 1. 先获取Demography数据,包含PatientName 姓名,Birthday 出生日期,Sex 性别,SSN 身份证号码 等数据 + * 2. 再获取Demography里面PatientIdentifierList数据,PatientIdentifierList包含了 MedicalRecordNo-病历号 + */ + if (requestBodyData.has("Demography")) { + org.json.JSONObject DemographyData = requestBodyData.getJSONObject("Demography"); + + if (DemographyData.has("PatientName")) { + patientName = DemographyData.getString("PatientName"); + } + if (DemographyData.has("Birthday")) { + birthday = DemographyData.getString("Birthday"); + } + + if (DemographyData.has("Sex") && DemographyData.getJSONObject("Sex").has("Text")) { + org.json.JSONObject sexData = DemographyData.getJSONObject("Sex"); + sex = sexData.getString("Text"); + } + + if (DemographyData.has("SSN")) { + SSN = DemographyData.getString("SSN"); + } + + // 循环遍历PatientIdentifierList数据,拿到MedicalRecordNo 病案号数据 + if (DemographyData.has("PatientIdentifierList")) { + JSONArray PatientIdentifierListDataJsonArray = DemographyData.getJSONArray("PatientIdentifierList"); + + for (int i = 0; i < PatientIdentifierListDataJsonArray.length(); i++) { + org.json.JSONObject PatientIdentifierListDataJsonObject = PatientIdentifierListDataJsonArray.getJSONObject(i); + if ("MedicalRecordNo".equals(PatientIdentifierListDataJsonObject.get("IDType"))) { + medicalRecordNo = PatientIdentifierListDataJsonObject.getString("IDNumber"); + } else if ("PatientID".equals(PatientIdentifierListDataJsonObject.get("IDType"))) { + patientID = PatientIdentifierListDataJsonObject.getString("IDNumber"); + } + } + } + } + /** + * 获取就诊时间,就诊次数 + */ + if (requestBodyData.has("PatientVisit")) { + org.json.JSONObject patientVisitData = requestBodyData.getJSONObject("PatientVisit"); + + //就诊次数 + if(patientVisitData.has("VisitCount")){ + visitCount = patientVisitData.getString("VisitCount"); + } + + //就诊时间 + if(patientVisitData.has("HandleList")){ + JSONArray HandleListDataJsonArray = patientVisitData.getJSONArray("HandleList"); + for (int i = 0; i < HandleListDataJsonArray.length(); i++) { + org.json.JSONObject HandleListDataJsonObject = HandleListDataJsonArray.getJSONObject(i); + if (HandleListDataJsonObject.has("HandleTime")) { + handleTime = HandleListDataJsonObject.getString("HandleTime"); + } + } + } + } + } + } +// System.out.println("患者唯一标识为:" + patientID + "\n病案号为:" + medicalRecordNo + "\n姓名为:" + patientName + +// "\n出生日期为:" + birthday + "\n性别为:" + sex + "\n身份证号为:" + SSN + "\n就诊时间为:" + handleTime + "\n就诊次数为:" + visitCount); + + data.put("patientID", patientID); + data.put("medicalRecordNo", medicalRecordNo); + data.put("patientName", patientName); + data.put("birthday", birthday); + data.put("sex", sex); + data.put("SSN", SSN); + data.put("handleTime", handleTime); + data.put("visitCount", visitCount); + + //判断是否已经存在改数据,通过唯一标识patientID + String isExist = commomMapper.quertIsExist(patientID); + + if(ObjectUtils.isEmpty(isExist)){ + commomMapper.saveData(data); + }else{ + commomMapper.updateData(data); + } + return Msg.successData(data); + } catch (Exception e) { + e.printStackTrace(); + return Msg.fail("数据接入失败"); + } } } diff --git a/src/main/java/com/emr/controller/FontShowRecordController.java b/src/main/java/com/emr/controller/FontShowRecordController.java index d0575da..1d3c7dd 100644 --- a/src/main/java/com/emr/controller/FontShowRecordController.java +++ b/src/main/java/com/emr/controller/FontShowRecordController.java @@ -152,7 +152,7 @@ public class FontShowRecordController { //虚假登陆 //验证shiro(有shiro才此操作) Power_User user = new Power_User(); - user.setUserName("第三方"); + user.setUserName("第三方") ; user.setUserId(-999); user.setRoleId(-999); Set menu = new TreeSet<>(); diff --git a/src/main/java/com/emr/controller/commomSearch/CommomSearchController.java b/src/main/java/com/emr/controller/commomSearch/CommomSearchController.java index 751d83e..94491eb 100644 --- a/src/main/java/com/emr/controller/commomSearch/CommomSearchController.java +++ b/src/main/java/com/emr/controller/commomSearch/CommomSearchController.java @@ -19,10 +19,7 @@ import com.emr.service.emrPrintOrDownLoadInfo.PrintOrDownLoadInfoService; import com.emr.service.recordType.EmrTypeRelatedService; import com.emr.service.recordType.EmrTypeService; import com.emr.service.tScanAssort.T_Scan_AssortService; -import com.emr.util.DateUtils; -import com.emr.util.ExceptionPrintUtil; -import com.emr.util.Jpg2PdfUtil; -import com.emr.util.img2PdfUtil; +import com.emr.util.*; import com.emr.vo.EmrPrintOrDownLoadInfo.EmrPrintOrDownLoadInfoVo; import com.emr.vo.FontVo.ScanAssortVo; import com.emr.vo.browseRecords; @@ -30,6 +27,8 @@ import com.emr.vo.commomSearch.*; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import org.apache.commons.lang3.StringUtils; +import org.apache.pdfbox.pdmodel.PDDocument; +import org.apache.pdfbox.rendering.PDFRenderer; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.apache.shiro.util.CollectionUtils; import org.springframework.beans.factory.annotation.Autowired; @@ -42,13 +41,21 @@ import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import org.springframework.web.multipart.MultipartFile; +import javax.imageio.ImageIO; +import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; +import java.awt.image.BufferedImage; +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.IOException; +import java.io.PrintWriter; import java.net.InetAddress; import java.net.UnknownHostException; import java.text.SimpleDateFormat; import java.util.*; +import java.util.Base64; import java.util.stream.Collectors; /** @@ -349,7 +356,15 @@ public class CommomSearchController { model.addAttribute("patientId", patientId); model.addAttribute("dataSource", dataSource); //加载登陆者 - Power_User user = (Power_User) request.getSession().getAttribute("CURRENT_USER"); + Power_User user; + Object currentUser = request.getSession().getAttribute("CURRENT_USER"); + if(ObjectUtils.isEmpty(currentUser)){ + ServletContext context = request.getServletContext(); + user = (Power_User)context.getAttribute("CURRENT_USER"); + }else{ + //查询通过审批且未过期的patientId集合 + user = (Power_User) currentUser; + } if (null != user) { model.addAttribute("user", user); model.addAttribute("roleId", user.getRoleId()); @@ -427,6 +442,129 @@ public class CommomSearchController { return "recordManage/commomSearch/showRecord174"; } + @RequestMapping("showMegerPDFView") + public String showMegerPDFView(String patientId, String dataSource, Model model, HttpServletRequest request) { + model.addAttribute("patientId", patientId); + model.addAttribute("dataSource", dataSource); + //加载登陆者 + Power_User user = (Power_User) request.getSession().getAttribute("CURRENT_USER"); + if (null != user) { + model.addAttribute("user", user); + model.addAttribute("roleId", user.getRoleId()); + model.addAttribute("hospitalName", hospitalName); + } + List printCount = null; + try { + printCount = printOrDownLoadInfoService.getPrintCount(patientId); + + } catch (Exception e) { + ExceptionPrintUtil.printException(e); + e.printStackTrace(); + } + if (null != printCount && !printCount.isEmpty()) { + model.addAttribute("printCount", 1); + } + Short admissTimes = null; + String name = null; + String disDate = null; + String disDept = null; + String attending = null; + String fileSource = null; + List commomVos = commomMapper.selectAllAndPatientId(patientId); + for (CommomVo list : commomVos) { + admissTimes = list.getAdmissTimes(); + name = list.getName(); + fileSource = list.getFileSource(); + disDate = list.getDisDate(); + disDept = list.getDisDept(); + attending = list.getAttending(); + } + String userName = user.getUserPosition(); + SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss "); + Date date = new Date(System.currentTimeMillis()); + String format = formatter.format(date); + browseRecords browseRecords = new browseRecords(); + browseRecords.setAdmissTimes(admissTimes); + browseRecords.setPatientName(name); + browseRecords.setDisDate(disDate); + browseRecords.setDisDept(disDept); + browseRecords.setAttending(attending); + browseRecords.setPatientId(patientId); + browseRecords.setBrowseTime(format); + browseRecords.setBrowseName(userName); + // 获取访问真实IP + String ipAddress = request.getHeader("x-forwarded-for"); + if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) { + ipAddress = request.getHeader("Proxy-Client-IP"); + } + if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) { + ipAddress = request.getHeader("WL-Proxy-Client-IP"); + } + if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) { + ipAddress = request.getRemoteAddr(); + if ("127.0.0.1".equals(ipAddress) || "0:0:0:0:0:0:0:1".equals(ipAddress)) { + //根据网卡取本机配置的IP + InetAddress inet = null; + try { + inet = InetAddress.getLocalHost(); + } catch (UnknownHostException e) { + e.printStackTrace(); + } + assert inet != null; + ipAddress = inet.getHostAddress(); + } + } + //对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割 + if (ipAddress != null && ipAddress.length() > 15) { //"***.***.***.***".length() = 15 + if (ipAddress.indexOf(",") > 0) { + ipAddress = ipAddress.substring(0, ipAddress.indexOf(",")); + } + } + browseRecords.setIp(ipAddress); + + return "recordManage/commomSearch/showMegerPDFView"; + } + + @RequestMapping("showMegerRecordIframeBlood") + public String showMegerRecordIframeBlood(String patientId, String flag, Model model, HttpServletRequest request) { + model.addAttribute("patientId", patientId); + Power_User user = (Power_User) request.getSession().getAttribute("CURRENT_USER"); + //打印分类集合 + List emrTypes = null; + List zdAssorts = null; + int isDownload = 0; + try { + emrTypes = emrTypeService.selectAllByCreater(1, request); + //病案分段集合 + zdAssorts = assortService.selectAllByPower(user); + isDownload = apply_approveMapper.selectIsPowerByUser(user.getUserName(), patientId, 3); + } catch (Exception e) { + ExceptionPrintUtil.printException(e); + e.printStackTrace(); + } + model.addAttribute("emrTypes", emrTypes); + model.addAttribute("zdAssorts", zdAssorts); + model.addAttribute("isDownload", isDownload); + //查询是否有打印权限 + int printFlag = 0; + int moveFlag = 0; + Set menus = user.getMenus(); + for (String menu : menus) { + if (StringUtils.isNotBlank(menu)) { + if ("/commom/printPdf".equals(menu)) { + printFlag = 1; + } + if ("/commom/movePdf".equals(menu)) { + moveFlag = 1; + } + } + } + model.addAttribute("moveFlag", moveFlag); + model.addAttribute("printFlag", printFlag); + model.addAttribute("flag", flag); + return "recordManage/commomSearch/showMegerRecordIframeBlood"; + } + @RequestMapping("showRecordSouth") public String showRecordSouth(String patientId, String userName, String deptName, Model model, HttpServletRequest request) { model.addAttribute("patientId", patientId); @@ -531,7 +669,15 @@ public class CommomSearchController { @RequestMapping("showRecordIframeBlood") public String showRecordIframeBlood(String patientId, String flag, Model model, HttpServletRequest request) { model.addAttribute("patientId", patientId); - Power_User user = (Power_User) request.getSession().getAttribute("CURRENT_USER"); + Power_User user; + Object currentUser = request.getSession().getAttribute("CURRENT_USER"); + if(ObjectUtils.isEmpty(currentUser)){ + ServletContext context = request.getServletContext(); + user = (Power_User)context.getAttribute("CURRENT_USER"); + }else{ + //查询通过审批且未过期的patientId集合 + user = (Power_User) currentUser; + } //打印分类集合 List emrTypes = null; List zdAssorts = null; @@ -682,8 +828,16 @@ public class CommomSearchController { List treeList = new ArrayList<>(); //查询该有的权限分类 try { - Power_User user = (Power_User) request.getSession().getAttribute("CURRENT_USER"); - List commomVos = new ArrayList<>(); + Power_User user; + Object currentUser = request.getSession().getAttribute("CURRENT_USER"); + if(ObjectUtils.isEmpty(currentUser)){ + ServletContext context = request.getServletContext(); + user = (Power_User)context.getAttribute("CURRENT_USER"); + }else{ + //查询通过审批且未过期的patientId集合 + user = (Power_User) currentUser; + } + List commomVos; if (user.getRoleId() == 0 || user.getRoleId() == -100 || user.getRoleId() == -999) { commomVos = commomMapper.selectScanImgTreeByPatientId(patientId, sortFlag,null, null); } else { @@ -795,6 +949,100 @@ public class CommomSearchController { } } } + if (commomVos.size() == 0) { + List archiveDetail = archiveDetailMapper.selectPdfPathByPatient2(patientId); + //第一级:全部影像资料 + CommomTree tree1 = new CommomTree(); + Integer id = 1; + tree1.setId(id); + tree1.setNewName("全部影像资料"); + if (null != archiveDetail && !archiveDetail.isEmpty()) { + //去重,取出不重复的分类集合 + Map assortMap = new LinkedHashMap<>(); + for (CommomTree commomVo1 : archiveDetail) { + assortMap.put(commomVo1.getAssortId(), commomVo1); + } + //判断分类是否全选,全选,父类跟着全选 + if (null != typeRelateds && !typeRelateds.isEmpty()) { + boolean checkedFlag = true; + for (Map.Entry map : assortMap.entrySet()) { + //定义是否存在 + boolean flag = false; + for (Emr_Type_Related typeRelated : typeRelateds) { + if (typeRelated.getAssortId().equals(map.getKey())) { + flag = true; + break; + } + } + if (!flag) { + checkedFlag = false; + break; + } + } + if (checkedFlag) { + tree1.setChecked("true"); + } + } else { + tree1.setChecked("true"); + } + treeList.add(tree1); + int oneId = 0; + for (Map.Entry map : assortMap.entrySet()) { + id++; + oneId = id; + String assortId = map.getValue().getAssortId(); + CommomTree tree2 = new CommomTree(); + tree2.setId(id); + tree2.setParentId(1); + tree2.setAssortId(map.getValue().getAssortId()); + //判断选中 + boolean checkFlag = false; + if (null != typeRelateds && !typeRelateds.isEmpty()) { + for (Emr_Type_Related typeRelated : typeRelateds) { + if (StringUtils.isNotBlank(assortId) && assortId.equals(typeRelated.getAssortId())) { + tree2.setChecked("true"); + checkFlag = true; + break; + } + } + } else { + checkFlag = true; + tree2.setChecked("true"); + } + //定义该类影像图片数量 + int scanPathCount = 0; + //第二层 图片 + int scanPathCountNum = 0; + for (CommomTree commomVo : archiveDetail) { + if (StringUtils.isNotBlank(assortId) && StringUtils.isNotBlank(commomVo.getAssortId()) && + assortId.equals(commomVo.getAssortId())) { + id++; + CommomTree tree3 = new CommomTree(); + tree3.setId(id); + tree3.setParentId(oneId); + tree3.setAssortId(assortId); + if (checkFlag) { + tree3.setChecked("true"); + } + scanPathCount++; + //图片名称 + String name = commomVo.getScanPage(); + tree3.setAssortName(name); + //设置树图片节点的名称 + tree3.setNewName(commomVo.getTitle()); + tree3.setSource(commomVo.getSource()); + //存储水印图片 + treeList.add(tree3); + scanPathCountNum = commomVo.getPageCount(); + + + } + } + tree2.setNewName(map.getValue().getAssortName() + "(" + scanPathCountNum + ")"); + treeList.add(tree2); + } + } + } return JSON.toJSONString(treeList); } catch (Exception e) { ExceptionPrintUtil.printException(e); @@ -817,10 +1065,21 @@ public class CommomSearchController { @ResponseBody public ResultUtil selectPrintPic(HttpServletResponse response, String patientId, String rootPaths, String names, String sources, HttpServletRequest request) throws Exception { //生成加载进度mapKey - Power_User user = (Power_User) request.getSession().getAttribute("CURRENT_USER"); + Power_User user; + Object currentUser = request.getSession().getAttribute("CURRENT_USER"); + if(ObjectUtils.isEmpty(currentUser)){ + ServletContext context = request.getServletContext(); + user = (Power_User)context.getAttribute("CURRENT_USER"); + }else{ + //查询通过审批且未过期的patientId集合 + user = (Power_User) currentUser; + } String mapKey = user.getUserName() + "_" + patientId; - List outs = commomService.selectPrintPic(response, patientId, rootPaths, names, sources, mapKey); - return ResultUtil.ok(outs); + if(!ObjectUtils.isEmpty(rootPaths) && rootPaths.length() > 3){ + List outs = commomService.selectPrintPic(response, patientId, rootPaths, names, sources, mapKey); + return ResultUtil.ok(outs); + } + return ResultUtil.ok("图像路径为空,请检查数据是否有误"); } @@ -901,9 +1160,17 @@ public class CommomSearchController { @ResponseBody public void getRecordContentBlood(String patientId, HttpServletRequest request, HttpServletResponse response) { List commomTrees = archiveDetailMapper.selectPdfPathByPatient2(patientId); + Power_User user; + Object currentUser = request.getSession().getAttribute("CURRENT_USER"); + if(ObjectUtils.isEmpty(currentUser)){ + ServletContext context = request.getServletContext(); + user = (Power_User)context.getAttribute("CURRENT_USER"); + }else{ + //查询通过审批且未过期的patientId集合 + user = (Power_User) currentUser; + } if (commomTrees.size() == 0) { try { - Power_User user = (Power_User) request.getSession().getAttribute("CURRENT_USER"); String mapKey = user.getUserName() + "_" + patientId; List scanPages = (List) request.getSession().getAttribute(mapKey); if (!CollectionUtils.isEmpty(scanPages)) { @@ -929,22 +1196,24 @@ public class CommomSearchController { } } else { String pdfWater = ""; - Power_User user = (Power_User) request.getSession().getAttribute("CURRENT_USER"); String mapKey = user.getUserName() + "_" + patientId; List filePaths = (List) request.getSession().getAttribute(mapKey); if (!CollectionUtils.isEmpty(filePaths)) { //根据图片路径转换pdf EmrPdfWaterSet emrPdfWaterSet = pdfWaterSetMapper.selectByPrimaryKey(1); //定义第二文本水印 姓名 + 科室 + ip - EmrPdfWaterSet emrPdfWaterSet1 = commomService.getEmrPdfWaterSet(emrPdfWaterSet); Jpg2PdfUtil.mulFile2One2(response, filePaths, pdfWater,emrPdfWaterSet); //移除缓存 request.removeAttribute(mapKey); } - } } + public int calculateTotalSegments(int totalPages) { + // 假设每段包含100页 + return (int) Math.ceil((double) totalPages / 5); + } + /** * 南方医院访问 * @@ -1320,6 +1589,87 @@ public class CommomSearchController { @ResponseBody public ResultUtil uploadCost(HttpServletRequest request) { return commomService.uploadCost(request); + } + + @RequestMapping(value = "savePdfPage", method = RequestMethod.POST) + @ResponseBody + public ResultUtil savePdfPage(@RequestBody PdfPageRequest request) { + String[] base64Datas = request.getBase64Data(); + String[] assortIdDatas = request.getAssortIdData(); + String[] pageDatas = request.getPageData(); + String patientId = request.getPatientId(); + + Map dataMap = new HashMap<>(); + for(int i = 0; i < base64Datas.length; i++){ + String base64Data = base64Datas[i]; + String assortId = assortIdDatas[i]; + int pageNum = Integer.parseInt(pageDatas[i]); + String fileName = "merger_" + patientId + "_" + pageNum + ".jpg"; + try { + // 通过patientId查询文件上传路径 + String uploadPath = commomService.getUploadPath(patientId); + String savePath = uploadPath + "\\" + fileName; + + // 下载PDF文件 + byte[] pdfBytes = Base64.getDecoder().decode(base64Data.split(",")[1]); + // 加载PDF文件 + PDDocument document = PDDocument.load(new ByteArrayInputStream(pdfBytes)); + // 提取指定页码的内容 + PDFRenderer pdfRenderer = new PDFRenderer(document); + BufferedImage image = pdfRenderer.renderImageWithDPI(pageNum - 1, 150); // 使用300 DPI渲染图像 + // 将图像保存为JPG文件 + File file = new File(savePath); + ImageIO.write(image, "jpg", file); + document.close(); + + //判断是否已有改图像,防止重复插入 + Integer isExistflag = commomService.getIsExistFileName(fileName); + if(isExistflag == 1){ + continue; + } + // 存入分段数据表 + dataMap.put("patientId", patientId); + dataMap.put("assortId", assortId); + dataMap.put("scanPage", fileName); + commomService.saveAssortData(dataMap); + } catch (IOException e) { + e.printStackTrace(); + return ResultUtil.error("上传失败"); + } + } + return ResultUtil.ok(); + } + + @RequestMapping(value = "saveSubmitAssortLog", method = RequestMethod.POST) + @ResponseBody + public ResultUtil saveSubmitAssortLog(@RequestBody PdfPageRequest request) { + String[] assortIdDatas = request.getAssortIdData(); + String[] assortTexteData = request.getAssortTexteData(); + String[] pageDatas = request.getPageData(); + String patientId = request.getPatientId(); + + Map dataMap = new HashMap<>(); +// for(int i = 0; i < assortIdDatas.length; i++){ +// String assortId = assortIdDatas[i]; +// String assortTexte = assortTexteData[i]; +// int pageNum = Integer.parseInt(pageDatas[i]); +// try { +// //判断是否已有改图像,防止重复插入 +// Integer isExistflag = commomService.getIsExistFileName(fileName); +// if(isExistflag == 1){ +// continue; +// } +// // 存入分段数据表 +// dataMap.put("patientId", patientId); +// dataMap.put("assortId", assortId); +// dataMap.put("scanPage", fileName); +// commomService.saveAssortData(dataMap); +// } catch (IOException e) { +// e.printStackTrace(); +// return ResultUtil.error("上传失败"); +// } +// } + return ResultUtil.ok(); } } diff --git a/src/main/java/com/emr/controller/templateSearch/TemplateSearchController.java b/src/main/java/com/emr/controller/templateSearch/TemplateSearchController.java index 508bc06..0d18933 100644 --- a/src/main/java/com/emr/controller/templateSearch/TemplateSearchController.java +++ b/src/main/java/com/emr/controller/templateSearch/TemplateSearchController.java @@ -4,6 +4,7 @@ import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.emr.annotation.OptionalLog; import com.emr.controller.FormTokenFlagUtil; +import com.emr.controller.JAXDynamicClientFactory; import com.emr.dao.Archive_DetailMapper; import com.emr.dao.CommomMapper; import com.emr.dao.EmrComomSetMapper; @@ -37,7 +38,17 @@ import com.emr.vo.templateSearch.Emr_Modle_RelatedVo; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import org.apache.commons.lang3.StringUtils; +import org.apache.cxf.endpoint.Client; +import org.apache.http.client.HttpClient; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.DefaultHttpClient; import org.apache.shiro.authz.annotation.RequiresPermissions; +import org.apache.tools.zip.ZipEntry; +import org.dom4j.Document; +import org.dom4j.DocumentHelper; +import org.dom4j.Element; +import org.dom4j.io.OutputFormat; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Controller; @@ -45,13 +56,17 @@ import org.springframework.ui.Model; import org.springframework.util.ObjectUtils; import org.springframework.web.bind.annotation.*; +import javax.annotation.Resource; +import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.*; +import java.net.URLEncoder; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; -import org.apache.tools.zip.ZipEntry; +import java.util.stream.Collectors; + import org.apache.tools.zip.ZipOutputStream; /** @@ -69,6 +84,9 @@ import org.apache.tools.zip.ZipOutputStream; @Controller @RequestMapping("template/") public class TemplateSearchController { + + @Resource + private Logger logger; @Autowired private Emr_CustomizeMapper customizeMapper; @Autowired @@ -809,8 +827,15 @@ public class TemplateSearchController { @ResponseBody public String getApproves(HttpServletRequest request, int type) { try { - //查询通过审批且未过期的patientId集合 - Power_User user = (Power_User) request.getSession().getAttribute("CURRENT_USER"); + Power_User user; + Object currentUser = request.getSession().getAttribute("CURRENT_USER"); + if(ObjectUtils.isEmpty(currentUser)){ + ServletContext context = request.getServletContext(); + user = (Power_User)context.getAttribute("CURRENT_USER"); + }else{ + //查询通过审批且未过期的patientId集合 + user = (Power_User) currentUser; + } String userName = user.getUserName(); List approveList = applyApproveMapper.selectPatientIdsByUser(userName, null, type); StringBuilder approves = new StringBuilder(); @@ -864,7 +889,15 @@ public class TemplateSearchController { @ResponseBody public String cutomSearchTable(String selectSql,String fromTableSql,String whereSql,String orderBys,Integer page, Integer limit, HttpServletRequest request,String sortNames,String sortOrder) { //匹配权限 - Power_User user = (Power_User) request.getSession().getAttribute("CURRENT_USER"); + Power_User user; + Object currentUser = request.getSession().getAttribute("CURRENT_USER"); + if(ObjectUtils.isEmpty(currentUser)){ + ServletContext context = request.getServletContext(); + user = (Power_User)context.getAttribute("CURRENT_USER"); + }else{ + //查询通过审批且未过期的patientId集合 + user = (Power_User) currentUser; + } //获取默认排序字段和排序方式 String defaultSortField = (String) request.getSession().getAttribute("defaultSortField"); String defaultSortFieldType = (String) request.getSession().getAttribute("defaultSortFieldType"); @@ -1136,37 +1169,10 @@ public class TemplateSearchController { try { List scanPathVos = scanPathMapper.selectScanFileByBloodPatientIds(patientIds, null, flag); if (null != scanPathVos && !scanPathVos.isEmpty()) { - Set list = new LinkedHashSet<>(); - Set patientIdSet = new LinkedHashSet<>(); //批量添加下载记录 printOrDownLoadInfoService.SimpleInsert(scanPathVos, null, Short.valueOf("2")); - for (ScanPathVo scanPathVo : scanPathVos) { - patientIdSet.add(scanPathVo.getPatientId()); - } - for (String patinetId : patientIdSet) { - ScanPathForPatientListVo vo = new ScanPathForPatientListVo(); - List filePaths = new ArrayList<>(); - for (ScanPathVo scanPathVo : scanPathVos) { - if (scanPathVo.getPatientId().equals(patinetId)) { - vo.setName(scanPathVo.getName()); - vo.setInpatientNo(scanPathVo.getInpatientNo()); - vo.setSubjectNo(scanPathVo.getSubjectNo()); - String disDate = scanPathVo.getDisDate(); - if(!ObjectUtils.isEmpty(disDate)){ - SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - vo.setDisDate(sdf.parse(disDate)); - } - String fileRealPath = scanPathVo.getFileRealPath(); - if (StringUtils.isNoneBlank(fileRealPath) && new File(fileRealPath).exists()) { - filePaths.add(fileRealPath); - } - } - } - if (!filePaths.isEmpty()) { - vo.setScanPathList(filePaths); - list.add(vo); - } - } + List scanPathForPatientListVos = processScanPaths(scanPathVos); + Set list = new LinkedHashSet<>(scanPathForPatientListVos); String zipName = "档案pdf压缩包"; downloadPdfZip(response, zipName, list, dataSource); } @@ -1238,6 +1244,46 @@ public class TemplateSearchController { // } } + public List processScanPaths(List scanPathVos) { + // 收集患者ID + Set patientIdSet = scanPathVos.stream() + .map(ScanPathVo::getPatientId) + .collect(Collectors.toSet()); + + // 处理每个患者的数据 + return patientIdSet.parallelStream() + .map(patinetId -> { + ScanPathForPatientListVo vo = new ScanPathForPatientListVo(); + List filePaths = scanPathVos.stream() + .filter(scanPathVo -> scanPathVo.getPatientId().equals(patinetId)) + .peek(scanPathVo -> { + vo.setName(scanPathVo.getName()); + vo.setInpatientNo(scanPathVo.getInpatientNo()); + vo.setSubjectNo(scanPathVo.getSubjectNo()); + String disDate = scanPathVo.getDisDate(); + if (!ObjectUtils.isEmpty(disDate)) { + try { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + vo.setDisDate(sdf.parse(disDate)); + } catch (ParseException e) { + e.printStackTrace(); + } + } + }) + .map(ScanPathVo::getFileRealPath) + .filter(StringUtils::isNoneBlank) + .filter(fileRealPath -> new File(fileRealPath).exists()) + .collect(Collectors.toList()); + + if (!filePaths.isEmpty()) { + vo.setScanPathList(filePaths); + } + return vo; + }) + .filter(vo -> vo.getScanPathList() != null && !vo.getScanPathList().isEmpty()) + .collect(Collectors.toList()); + } + public void createFile(File file) { //如果文件夹不存在则创建 if (!file.exists() && !file.isDirectory()) { @@ -1340,11 +1386,12 @@ public class TemplateSearchController { //封装下载pdf压缩包方法 private void downloadPdfZip(HttpServletResponse response, String zipName, Set list, String dataSource) throws UnsupportedEncodingException { response.reset(); - response.setContentType("application/zip;charset=UTF-8"); - zipName = java.net.URLEncoder.encode(zipName, "UTF-8"); + response.setContentType("application/zip"); + response.setCharacterEncoding("UTF-8"); // 设置响应头的字符编码 + zipName = URLEncoder.encode(zipName, "UTF-8"); response.setHeader("Content-Disposition", "attachment;filename=" + zipName + "(" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + ").zip"); String filePdfName = ""; - try (ZipOutputStream zos = new ZipOutputStream(response.getOutputStream())){ + try (ZipOutputStream zos = new ZipOutputStream(response.getOutputStream())) { EmrPdfWaterSet emrPdfWaterSet = pdfWaterSetMapper.selectByPrimaryKey(1); SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMdd"); for (ScanPathForPatientListVo vo : list) { @@ -1353,29 +1400,52 @@ public class TemplateSearchController { disDate = fmt.format(vo.getDisDate()); } List scanPathList = vo.getScanPathList(); - try (ByteArrayOutputStream out = new ByteArrayOutputStream()) { - //每个文件名 - String inpatientNo = ObjectUtils.isEmpty(vo.getInpatientNo()) ? "无" : vo.getInpatientNo().trim(); - String name = ObjectUtils.isEmpty(vo.getName()) ? "无" : vo.getName().trim(); - if("3".equals(dataSource)){ - //药学楼 - filePdfName = vo.getSubjectNo().trim() + "-" + name + "_" + fmt.format(new Date()); - }else{ - filePdfName = inpatientNo + "-" + name + "-" + disDate.trim() + "_" + fmt.format(new Date()); - } - String fileName = hospitaInfo + "_" + filePdfName; - zos.putNextEntry(new ZipEntry(fileName + ".pdf")); - //合成pdf - img2PdfUtil.imageToPdfToBuffOut(out, scanPathList, emrPdfWaterSet); - try (BufferedInputStream bis = new BufferedInputStream(new ByteArrayInputStream(out.toByteArray()))) { - //输出 - int len = 0; - byte[] buf = new byte[1024 * 1024]; - while ((len = bis.read(buf, 0, buf.length)) != -1) { - zos.write(buf, 0, len); + // 每个文件名 + String inpatientNo = ObjectUtils.isEmpty(vo.getInpatientNo()) ? "无" : vo.getInpatientNo().trim(); + String name = ObjectUtils.isEmpty(vo.getName()) ? "无" : vo.getName().trim(); + if ("3".equals(dataSource)) { + // 药学楼 + filePdfName = vo.getSubjectNo().trim() + "_" + name + "_" + fmt.format(new Date()); + } else { + filePdfName = inpatientNo + "_" + name + "_" + disDate.trim() + "_" + fmt.format(new Date()); + } + String fileName = hospitaInfo + "_" + filePdfName; + fileName = new String(fileName.getBytes(),"ISO-8859-1"); + ZipEntry zipEntry = new ZipEntry(fileName + ".pdf"); + zos.putNextEntry(zipEntry); + + // 使用 PipedInputStream 和 PipedOutputStream 实现流式处理 + PipedInputStream pis = new PipedInputStream(); + PipedOutputStream pos = new PipedOutputStream(pis); + + // 创建一个线程生成 PDF 数据 + Thread pdfGeneratorThread = new Thread(() -> { + try { + img2PdfUtil.imageToPdfToBuffOut(pos, scanPathList, emrPdfWaterSet); + } catch (Exception e) { + ExceptionPrintUtil.printException(e); + } finally { + try { + pos.close(); + } catch (IOException e) { + e.printStackTrace(); } } + }); + pdfGeneratorThread.start(); + + // 在主线程中读取生成的 PDF 数据并写入 ZIP 文件 + byte[] buffer = new byte[1024 * 1024]; + int len; + while ((len = pis.read(buffer)) != -1) { + zos.write(buffer, 0, len); } + + // 关闭当前的 ZipEntry + zos.closeEntry(); + + // 确保生成 PDF 的线程已经完成 + pdfGeneratorThread.join(); } } catch (Exception e) { ExceptionPrintUtil.printException(e); @@ -1511,27 +1581,6 @@ public class TemplateSearchController { emrPdfWaterSet.setIsImg(emrPdfWaterSet.getDownloadIsImg()); EmrPdfWaterSet emrPdfWaterSet1 = commomService.getEmrPdfWaterSet(emrPdfWaterSet); imgToPdfUtil.imageToPdf(response, scanPathVos, pdfName, emrPdfWaterSet,emrPdfWaterSet1); - }else { - String fileRealPath=null; - List commomTrees = archiveDetailMapper.selectPdfPathByPatient3(patientIds, assortIds); - List filePaths = new ArrayList(); - for (int i = 0; i < commomTrees.size(); ++i) { - fileRealPath = commomTrees.get(i).getPDFPATH(); - if (StringUtils.isNoneBlank(new CharSequence[]{fileRealPath})) { - filePaths.add(fileRealPath); - } - } - SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMdd"); - List scanPathVos1 = scanPathMapper.selectFilaname(patientIds); - ScanPathVo vo = scanPathVos1.get(0); - String disDate = ""; - if (null != vo.getDisDate()) { - disDate = fmt.format(vo.getDisDate()); - } - EmrPdfWaterSet emrPdfWaterSet = pdfWaterSetMapper.selectByPrimaryKey(1); - //下载文件名 - String filename = vo.getInpatientNo().trim() + "-" + vo.getName().trim() + "-" + disDate.trim() + "_" + fmt.format(new Date()); - Jpg2PdfUtil.mulFile2One3(response,filePaths,filename,emrPdfWaterSet); } } catch (Exception e) { ExceptionPrintUtil.printException(e); @@ -1545,6 +1594,7 @@ public class TemplateSearchController { sb.append(hospitaInfo); ScanPathVo scanPathVo = scanPathVos.get(0); JSONObject jsonObject= (JSONObject) JSONObject.toJSON(scanPathVo); + String name = ObjectUtils.isEmpty(jsonObject.getString("name")) ? "无" : jsonObject.getString("name").trim(); List patientInfoList = Arrays.asList(patientInfo.split(",")); for (String list:patientInfoList){ String contents = ObjectUtils.isEmpty(jsonObject.getString(list)) ? "无" : jsonObject.getString(list).trim(); @@ -1556,7 +1606,7 @@ public class TemplateSearchController { String formattedDate = targetFormat.format(date); sb.append("_"+formattedDate); }else { - sb.append("_"+contents); + sb.append("_" + contents + "_" + name); } } return sb.toString(); @@ -1631,6 +1681,9 @@ public class TemplateSearchController { @RequestMapping(value = "printInfoBlood", produces = {"text/json;charset=UTF-8"}, method = RequestMethod.POST) @ResponseBody public void printInfoBlood(String patientIds, String assortIds, Integer typeId, String flag) { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + String printDate = sdf.format(new Date()); + if (StringUtils.isNoneBlank(patientIds)) { try { if (StringUtils.isNotBlank(assortIds)) { @@ -1647,6 +1700,8 @@ public class TemplateSearchController { List scanPathVos = scanPathMapper.selectScanFileByBloodPatientIds(patientIds, assortIds, flag); //批量添加打印记录 printOrDownLoadInfoService.SimpleInsert(scanPathVos, typeId, Short.valueOf("1")); +// //调用湘雅附二病历复印打印状态同步接口 +// this.MedicalPrintSyncPrintStatusAction(patientIds , printDate); } } catch (Exception e) { ExceptionPrintUtil.printException(e); @@ -1655,6 +1710,65 @@ public class TemplateSearchController { } } + /** + * 湘雅附二病历复印打印状态同步接口 + */ + public void MedicalPrintSyncPrintStatusAction(String patientIds, String printDate) { + //创建连接工厂 + JAXDynamicClientFactory dcf = JAXDynamicClientFactory.newInstance(); + //创建客户端 + Object[] objects; + Client client = dcf.createClient("http://172.16.198.250:13023/dev/openapi/health"); + //合作方密钥 + String partnerKey = "53fd4f5ff132528e2e071baeeb3f99a2"; + + try { + String stringSignTemp = "inpatientNo="+ patientIds + + "&partnerId=XYEYYHIS" + + "&printStatus=1" + + "&printTime=" + printDate + + "&serviceCode=MedicalPrintSyncPrintStatusAction" + + "&timeStamp=" + printDate + + "&" + partnerKey; + + String password = MD5.KL(stringSignTemp); + + //获取请求参数xml字符串 + String xmlStr = getXml(patientIds,printDate,password); + objects = client.invoke("MedicalPrintSyncPrintStatusAction", xmlStr); + //应答信息 + String result = objects[0].toString(); + + } catch (Exception e) { + e.printStackTrace(); + } finally { + if(null != client) { + client.destroy(); + } + } + } + + public String getXml(String patientIds, String printDate , String password) { + // 1、创建document对象 + Document document = DocumentHelper.createDocument(); + // 2、创建根节点rss + Element requestElement = document.addElement("Request"); + requestElement.addElement("serviceCode").setText("MedicalPrintSyncPrintStatusAction"); + requestElement.addElement("partnerId").setText("XYEYYHIS"); + requestElement.addElement("timeStamp").setText(printDate); + requestElement.addElement("password").setText(password); + requestElement.addElement("inpatientNo").setText(patientIds); + requestElement.addElement("printStatus").setText("1"); + requestElement.addElement("printTime").setText(printDate); + + OutputFormat format = OutputFormat.createPrettyPrint(); + // 设置编码格式 + format.setEncoding("UTF-8"); + String xml = document.asXML(); + + return document.asXML(); + } + /** * @MethodName: addLockByPatientId * @Description: 添加锁定 diff --git a/src/main/java/com/emr/dao/CommomMapper.java b/src/main/java/com/emr/dao/CommomMapper.java index 218c2ef..9ee1afd 100644 --- a/src/main/java/com/emr/dao/CommomMapper.java +++ b/src/main/java/com/emr/dao/CommomMapper.java @@ -175,4 +175,16 @@ public interface CommomMapper { List> queryImgStatistics(CommomVo commomVo); List> queryPeriodsStatistics(CommomVo commomVo); + + void saveData(Map data); + + String quertIsExist(String patientID); + + void updateData(Map data); + + String getUploadPath(String patientId); + + void saveAssortData(Map dataMap); + + Integer getIsExistFileName(String fileName); } \ No newline at end of file diff --git a/src/main/java/com/emr/service/CommomService.java b/src/main/java/com/emr/service/CommomService.java index d34fd0e..728ecfb 100644 --- a/src/main/java/com/emr/service/CommomService.java +++ b/src/main/java/com/emr/service/CommomService.java @@ -19,6 +19,7 @@ import com.emr.util.UploadUtil; import com.emr.util.img2PdfUtil; import com.emr.vo.ExportInpVo; import com.emr.vo.User; +import com.emr.vo.commomSearch.CommomTree; import com.emr.vo.commomSearch.CommomVo; import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.IOUtils; @@ -30,6 +31,8 @@ import org.apache.http.util.EntityUtils; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; +import org.springframework.scheduling.annotation.Async; +import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.stereotype.Component; import org.springframework.util.CollectionUtils; import org.springframework.util.ObjectUtils; @@ -39,15 +42,19 @@ import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartHttpServletRequest; import javax.imageio.ImageIO; +import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; import java.awt.image.BufferedImage; import java.io.*; import java.net.InetAddress; import java.net.UnknownHostException; import java.text.SimpleDateFormat; import java.util.*; -import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.*; +import java.util.stream.Collectors; +import java.util.stream.IntStream; /** * @ProjectName: @@ -274,10 +281,9 @@ public class CommomService { } } - //脐血库显示pdf public void showRecordContentBlood(String patientId, String scanPages, String sources, String flag, HttpServletResponse response, HttpServletRequest request) throws Exception { - if (StringUtils.isNotBlank(patientId)) { + /*if (StringUtils.isNotBlank(patientId)) { patientId = patientId.replace("\'", ""); //查询 if (StringUtils.isNotBlank(flag)) { @@ -291,20 +297,16 @@ public class CommomService { root1 = commomVo.getFilePath(); } //组织src - List src = new LinkedList<>(); + List filePaths = new LinkedList<>(); String[] scanPageArr = scanPages.split(","); for (int i = 0; i < scanPageArr.length; i++) { String srcStr = ""; if (StringUtils.isNotBlank(scanPageArr[i])) { srcStr = root1 + File.separator + scanPageArr[i]; - } - src.add(srcStr); - } - List filePaths = new LinkedList<>(); - for (String srcs : src) { - File file = new File(srcs); - if (file.isFile()) { - filePaths.add(srcs); + File file = new File(srcStr); + if (file.isFile()) { + filePaths.add(srcStr); + } } } if (!filePaths.isEmpty()) { @@ -321,6 +323,82 @@ public class CommomService { } } } + }*/ + + if (StringUtils.isNotBlank(patientId)) { + patientId = patientId.replace("'", ""); + // 查询 + if (StringUtils.isNotBlank(flag)) { + CommomVo commomVo = commomMapper.selectByPrimaryKey(patientId); + if (commomVo != null && StringUtils.isNotBlank(commomVo.getFilePath())) { + // flag = home_addr取home_addr字段,path_file取home_addr字段 + String root1; + if ("home_addr".equals(flag)) { + root1 = commomVo.getHomeAddr(); + } else if ("file_path".equals(flag)) { + root1 = commomVo.getFilePath(); + } else { + root1 = ""; + } + + // 组织src + ExecutorService executor = Executors.newFixedThreadPool(6); // 创建线程池 + String finalPatientId = patientId; + List filePaths = CompletableFuture.supplyAsync(() -> { + List pdfPaths = new LinkedList<>(); + String[] scanPageArr = (scanPages != null) ? scanPages.split(",") : new String[0]; + for (String scanPage : scanPageArr) { + if (StringUtils.isNotBlank(scanPage)) { + String srcStr = root1 + File.separator + scanPage; + if (StringUtils.isNotBlank(srcStr)) { + File file = new File(srcStr); + if (file.isFile()) { + pdfPaths.add(srcStr); + } + } + } + } + return pdfPaths; + }, executor).exceptionally(ex -> { + ex.printStackTrace(); + return Collections.emptyList(); // 返回空列表 + }).join(); // 阻塞等待结果 + + executor.shutdown(); // 关闭线程池 + + Power_User user; + Object currentUser = request.getSession().getAttribute("CURRENT_USER"); + if(ObjectUtils.isEmpty(currentUser)){ + ServletContext context = request.getServletContext(); + user = (Power_User)context.getAttribute("CURRENT_USER"); + }else{ + //查询通过审批且未过期的patientId集合 + user = (Power_User) currentUser; + } + + if (user != null) { + String mapKey = user.getUserName() + "_" + finalPatientId; + request.getSession().setAttribute(mapKey, filePaths); + } + } else { + List commomTrees = archiveDetailMapper.getPDFRATH(patientId, scanPages); + if (!CollectionUtils.isEmpty(commomTrees) && request != null) { + Power_User user; + Object currentUser = request.getSession().getAttribute("CURRENT_USER"); + if(ObjectUtils.isEmpty(currentUser)){ + ServletContext context = request.getServletContext(); + user = (Power_User)context.getAttribute("CURRENT_USER"); + }else{ + //查询通过审批且未过期的patientId集合 + user = (Power_User) currentUser; + } + if (user != null) { + String mapKey = user.getUserName() + "_" + patientId; + request.getSession().setAttribute(mapKey, commomTrees); + } + } + } + } } } @@ -339,7 +417,15 @@ public class CommomService { ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); //获取reuqest HttpServletRequest request = attributes.getRequest(); - Power_User user = (Power_User) request.getSession().getAttribute("CURRENT_USER"); + Power_User user; + Object currentUser = request.getSession().getAttribute("CURRENT_USER"); + if(ObjectUtils.isEmpty(currentUser)){ + ServletContext context = request.getServletContext(); + user = (Power_User)context.getAttribute("CURRENT_USER"); + }else{ + //查询通过审批且未过期的patientId集合 + user = (Power_User) currentUser; + } String text = ""; if (StringUtils.isNotBlank(user.getUserName())) { text += " " + user.getUserName(); @@ -604,11 +690,19 @@ public class CommomService { * @param sources * @return */ - public List selectPrintPic(HttpServletResponse response, String patientId, String rootPaths, String names, String sources, String mapKey) throws IOException { + public List selectPrintPic(HttpServletResponse response, String patientId, String rootPaths, String names, String sources, String mapKey) throws IOException, ExecutionException, InterruptedException { //获取登录用户信息 HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); // 从session获取用户名 - Power_User user = (Power_User) request.getSession().getAttribute("CURRENT_USER"); + Power_User user; + Object currentUser = request.getSession().getAttribute("CURRENT_USER"); + if(ObjectUtils.isEmpty(currentUser)){ + ServletContext context = request.getServletContext(); + user = (Power_User)context.getAttribute("CURRENT_USER"); + }else{ + //查询通过审批且未过期的patientId集合 + user = (Power_User) currentUser; + } List outs = new LinkedList<>(); if (StringUtils.isNotBlank(names)) { String[] rootPathList = rootPaths.split(","); @@ -689,7 +783,7 @@ public class CommomService { String root = ""; String picPath = ""; //判断是否是tif图片 - boolean tifFileFlag = checkTifFile(srcPath); + boolean tifFileFlag = img2PdfUtil.checkTifFile(srcPath); if (tifFileFlag) { //保存目录不存在新增 if (!new File(WATERTIFTOJPGPATH).isDirectory()) { @@ -746,8 +840,47 @@ public class CommomService { } } return outs; + + /*// 获取登录用户信息 + HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); + Power_User user = (Power_User) request.getSession().getAttribute("CURRENT_USER"); + + List outs = new LinkedList<>(); + if (StringUtils.isNotBlank(names)) { + String[] rootPathList = rootPaths.split(","); + String[] nameList = names.split(","); + String[] sourceList = sources.split(","); + + // 获取水印设置 + EmrPdfWaterSet emrPdfWaterSet = pdfWaterSetMapper.selectByPrimaryKey(1); + + // 使用 CompletableFuture 进行异步处理 + List> futures = IntStream.range(0, nameList.length) + .mapToObj(i -> CompletableFuture.supplyAsync(() -> { + try { + return processImagePath(rootPathList[i], nameList[i], sourceList[i], user, emrPdfWaterSet, patientId, mapKey); + } catch (IOException e) { + e.printStackTrace(); + return null; + } + })) + .collect(Collectors.toList()); + + // 等待所有任务完成并收集结果 + for (CompletableFuture future : futures) { + String result = future.get(); + if (result != null) { + outs.add(result); + } + } + } + + return outs;*/ } + public String processImagePath(String rootPath, String name, String source, Power_User user, EmrPdfWaterSet emrPdfWaterSet, String patientId, String mapKey) throws IOException { + return "processed_" + name; // 示例返回值 + } public List selectPrintPic2(HttpServletResponse response, String patientId, String names, String sources, String mapKey) { List outs = new LinkedList<>(); @@ -773,7 +906,7 @@ public class CommomService { String root = ""; String picPath = ""; //判断是否是tif图片 - boolean tifFileFlag = checkTifFile(srcPath); + boolean tifFileFlag = img2PdfUtil.checkTifFile(srcPath); if (tifFileFlag) { String picSrc = WATERPICPATH + patientId + File.separator; //目录不存在则创建 @@ -802,32 +935,6 @@ public class CommomService { return outs; } - /** - * 判断是否是tif图片 - * - * @param srcPath - * @return - */ - private boolean checkTifFile(String srcPath) { - InputStream is = null; - try { - is = new FileInputStream(new File(srcPath)); - } catch (FileNotFoundException e) { - e.printStackTrace(); - } - byte[] content = new byte[0]; - try { - content = IOUtils.toByteArray(is); - } catch (IOException e) { - e.printStackTrace(); - } - // 判断图片类型jpg jpeg png bmp编码方式是tif格式的 - if (content[0] == 0x49 && content[1] == 0x49 && content[2] == 0x2A && content[3] == 0x00) { - return true; - } - return false; - } - /*private static String tifToJpg(String tifUrl, String tifToJpgRoot) { File fileTiff = new File(tifToJpgRoot); if (fileTiff.exists()) { @@ -981,6 +1088,8 @@ public class CommomService { return "reloadK\\"; case "Z": return "reloadZ\\"; + case "W": + return "reloadW\\"; default: ; } @@ -1112,9 +1221,8 @@ public class CommomService { List picNameList = Pdf2ImgUtil.pdfToPic(saveFileName, pdfName, "jpg", commomVo.getFilePath()); if (picNameList != null && picNameList.size() > 0) { - List insertList = new ArrayList<>(); - T_Scan_Assort t_scan_assort = null; + T_Scan_Assort t_scan_assort; for (int k = 0; k < picNameList.size(); k++) { t_scan_assort = new T_Scan_Assort(); t_scan_assort.setPatientId(commomVo.getPatientId()); @@ -1131,7 +1239,9 @@ public class CommomService { insertList.add(t_scan_assort); } //批量新增图片记录 - scanAssortService.SimpleInsert(insertList); + if(!CollectionUtils.isEmpty(insertList)){ + scanAssortService.SimpleInsert(insertList); + } } } } @@ -1153,4 +1263,16 @@ public class CommomService { return ResultUtil.error("费用清单上传失败"); } } + + public String getUploadPath(String patientId) { + return commomMapper.getUploadPath(patientId); + } + + public void saveAssortData(Map dataMap) { + commomMapper.saveAssortData(dataMap); + } + + public Integer getIsExistFileName(String fileName) { + return commomMapper.getIsExistFileName(fileName); + } } diff --git a/src/main/java/com/emr/service/emrLog/LogServiceImpl.java b/src/main/java/com/emr/service/emrLog/LogServiceImpl.java index 3bd55e9..fffb04e 100644 --- a/src/main/java/com/emr/service/emrLog/LogServiceImpl.java +++ b/src/main/java/com/emr/service/emrLog/LogServiceImpl.java @@ -7,9 +7,11 @@ import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.ObjectUtils; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; +import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import java.net.InetAddress; import java.net.UnknownHostException; @@ -39,7 +41,15 @@ public class LogServiceImpl implements LogService { HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()) .getRequest(); // 从session获取用户名 - Power_User user = (Power_User)request.getSession().getAttribute("CURRENT_USER"); + Power_User user; + Object currentUser = request.getSession().getAttribute("CURRENT_USER"); + if(ObjectUtils.isEmpty(currentUser)){ + ServletContext context = request.getServletContext(); + user = (Power_User)context.getAttribute("CURRENT_USER"); + }else{ + //查询通过审批且未过期的patientId集合 + user = (Power_User) currentUser; + } String username = user.getUserName(); log.setCreater(username); // 获取系统当前时间 diff --git a/src/main/java/com/emr/service/emrPrintOrDownLoadInfo/PrintOrDownLoadInfoService.java b/src/main/java/com/emr/service/emrPrintOrDownLoadInfo/PrintOrDownLoadInfoService.java index ea27b72..016cd57 100644 --- a/src/main/java/com/emr/service/emrPrintOrDownLoadInfo/PrintOrDownLoadInfoService.java +++ b/src/main/java/com/emr/service/emrPrintOrDownLoadInfo/PrintOrDownLoadInfoService.java @@ -16,9 +16,11 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.ObjectUtils; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; +import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import java.net.InetAddress; import java.net.UnknownHostException; @@ -51,7 +53,16 @@ public class PrintOrDownLoadInfoService { //组织批量插入集合 List batchInsertList = new ArrayList<>(); //获取登录者用户名 - Power_User user = (Power_User)((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getSession().getAttribute("CURRENT_USER"); + HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); + Power_User user; + Object currentUser = request.getSession().getAttribute("CURRENT_USER"); + if(ObjectUtils.isEmpty(currentUser)){ + ServletContext context = request.getServletContext(); + user = (Power_User)context.getAttribute("CURRENT_USER"); + }else{ + //查询通过审批且未过期的patientId集合 + user = (Power_User) currentUser; + } //获取格式化日期 SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //遍历主键组织批量插入集合 diff --git a/src/main/java/com/emr/service/recordType/EmrTypeServiceImpl.java b/src/main/java/com/emr/service/recordType/EmrTypeServiceImpl.java index 64a891d..cc132f0 100644 --- a/src/main/java/com/emr/service/recordType/EmrTypeServiceImpl.java +++ b/src/main/java/com/emr/service/recordType/EmrTypeServiceImpl.java @@ -10,7 +10,9 @@ import com.emr.vo.emrType.EmrTypeFeVo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.ObjectUtils; +import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import java.text.SimpleDateFormat; import java.util.Date; @@ -38,7 +40,15 @@ public class EmrTypeServiceImpl implements EmrTypeService { private Emr_Type_RelatedMapper emrTypeRelatedMapper; @Override public List selectAllByCreater(Integer isEffective, HttpServletRequest request) { - Power_User user = (Power_User)request.getSession().getAttribute("CURRENT_USER"); + Power_User user; + Object currentUser = request.getSession().getAttribute("CURRENT_USER"); + if(ObjectUtils.isEmpty(currentUser)){ + ServletContext context = request.getServletContext(); + user = (Power_User)context.getAttribute("CURRENT_USER"); + }else{ + //查询通过审批且未过期的patientId集合 + user = (Power_User) currentUser; + } String userName = user.getUserName(); Integer roleId = user.getRoleId(); //系统管理员全查 diff --git a/src/main/java/com/emr/service/tScanAssort/T_Scan_AssortServiceImpl.java b/src/main/java/com/emr/service/tScanAssort/T_Scan_AssortServiceImpl.java index b2af7e1..e7dc4b1 100644 --- a/src/main/java/com/emr/service/tScanAssort/T_Scan_AssortServiceImpl.java +++ b/src/main/java/com/emr/service/tScanAssort/T_Scan_AssortServiceImpl.java @@ -65,6 +65,26 @@ public class T_Scan_AssortServiceImpl implements T_Scan_AssortService { @Override public void SimpleInsert(List list) { if (!CollectionUtils.isEmpty(list)) { + // 查询表列数 + int colCount = commomMapper.selectColByTableName("t_scan_assort"); + // 每条记录的参数数量等于列数,假设每条记录有 colCount 个参数 + // 最大参数数为 2100,因此每批次插入的记录数为 2100 / colCount + int simpleInsertCount = 1600 / colCount; + List scanAssorts = new ArrayList<>(); + + for (int i = 0; i < list.size(); i++) { + // 添加到临时列表 + scanAssorts.add(list.get(i)); + + // 当临时列表达到最大批次大小或到达最后一个元素时,进行插入 + if ((i + 1) % simpleInsertCount == 0 || i == list.size() - 1) { + System.out.println("Batch insert: {} records--------- " + scanAssorts.size()); + scanAssortMapper.SimpleInsert(scanAssorts); + scanAssorts.clear(); // 清空临时列表 + } + } + } + /*if (!CollectionUtils.isEmpty(list)) { //根据字段多少批量新增 ///查询表列数 int colCount = commomMapper.selectColByTableName("t_scan_assort"); @@ -81,7 +101,7 @@ public class T_Scan_AssortServiceImpl implements T_Scan_AssortService { scanAssortMapper.SimpleInsert(scanAssorts); } } - } + }*/ } @Override @@ -271,6 +291,8 @@ public class T_Scan_AssortServiceImpl implements T_Scan_AssortService { return "reloadK\\"; case "Z": return "reloadZ\\"; + case "W": + return "reloadW\\"; default: ; } diff --git a/src/main/java/com/emr/util/ExportExcelUtil.java b/src/main/java/com/emr/util/ExportExcelUtil.java index e891fef..d17e22c 100644 --- a/src/main/java/com/emr/util/ExportExcelUtil.java +++ b/src/main/java/com/emr/util/ExportExcelUtil.java @@ -84,10 +84,19 @@ public class ExportExcelUtil { sheetNum = 1; } - int cpuCores = Runtime.getRuntime().availableProcessors(); - int threadPoolSize = 2 * cpuCores; + int corePoolSize = Runtime.getRuntime().availableProcessors(); + int maximumPoolSize = 2 * corePoolSize; + long keepAliveTime = 60L; // 空闲线程存活时间,单位秒 + BlockingQueue workQueue = new LinkedBlockingQueue<>(); + + ExecutorService executor = new ThreadPoolExecutor( + corePoolSize, + maximumPoolSize, + keepAliveTime, + TimeUnit.SECONDS, + workQueue + ); - ExecutorService executor = Executors.newFixedThreadPool(threadPoolSize); CompletionService completionService = new ExecutorCompletionService<>(executor); List> futures = new ArrayList<>(); diff --git a/src/main/java/com/emr/util/HttpClientTool.java b/src/main/java/com/emr/util/HttpClientTool.java index ee2aeea..555ddb4 100644 --- a/src/main/java/com/emr/util/HttpClientTool.java +++ b/src/main/java/com/emr/util/HttpClientTool.java @@ -30,7 +30,7 @@ public class HttpClientTool { public static final String CHARSET = "UTF-8"; // 采用静态代码块,初始化超时时间配置,再根据配置生成默认httpClient对象 static { - RequestConfig config = RequestConfig.custom().setConnectTimeout(60000).setSocketTimeout(15000).build(); + RequestConfig config = RequestConfig.custom().setConnectTimeout(360000).setSocketTimeout(360000).build(); httpClient = HttpClientBuilder.create().setDefaultRequestConfig(config).build(); } diff --git a/src/main/java/com/emr/util/HttpClientUtils.java b/src/main/java/com/emr/util/HttpClientUtils.java index 42ccc83..204caa6 100644 --- a/src/main/java/com/emr/util/HttpClientUtils.java +++ b/src/main/java/com/emr/util/HttpClientUtils.java @@ -42,7 +42,7 @@ public class HttpClientUtils { static { // 设置请求和传输超时时间 - requestConfig = RequestConfig.custom().setSocketTimeout(2000).setConnectTimeout(2000).build(); + requestConfig = RequestConfig.custom().setSocketTimeout(360000).setConnectTimeout(360000).build(); } /** diff --git a/src/main/java/com/emr/util/Pdf2ImgUtil.java b/src/main/java/com/emr/util/Pdf2ImgUtil.java index a8df7a2..4115ad4 100644 --- a/src/main/java/com/emr/util/Pdf2ImgUtil.java +++ b/src/main/java/com/emr/util/Pdf2ImgUtil.java @@ -10,8 +10,10 @@ import java.io.FilenameFilter; import java.io.IOException; import java.util.ArrayList; import java.util.List; +import java.util.concurrent.*; public class Pdf2ImgUtil { + /** * 使用pdfbox将整个pdf转换成图片 * @@ -55,7 +57,76 @@ public class Pdf2ImgUtil { } } } + /*int corePoolSize = Runtime.getRuntime().availableProcessors(); + int maximumPoolSize = 4 * corePoolSize; + long keepAliveTime = 60L; // 空闲线程存活时间,单位秒 + BlockingQueue workQueue = new LinkedBlockingQueue<>(); + + ExecutorService executor = new ThreadPoolExecutor( + corePoolSize, + maximumPoolSize, + keepAliveTime, + TimeUnit.SECONDS, + workQueue + ); + + // 记录开始时间 + long startTime = System.currentTimeMillis(); + + try { + // 将文件地址和文件名拼接成路径 注意:线上环境不能使用\\拼接 + File file = new File(fileAddress + File.separator + filename + ".pdf"); + List picNameList = new ArrayList<>(); + PDDocument doc = null; + try { + // 写入文件 + doc = PDDocument.load(file); + PDFRenderer renderer = new PDFRenderer(doc); + int pageCount = doc.getNumberOfPages(); + + List> futures = new ArrayList<>(); + + for (int i = 0; i < pageCount; i++) { + int pageIndex = i; + Future future = executor.submit(() -> { + // dpi为150,越高越清晰,转换越慢 + BufferedImage image = renderer.renderImageWithDPI(pageIndex, 150); // Windows native DPI + // 将图片写出到该路径下 + ImageIO.write(image, type, new File(picPath + File.separator + "FY_" + filename + "_" + String.format("%04d", pageIndex + 1) + "." + type)); + picNameList.add("FY_" + filename + "_" + String.format("%04d", pageIndex + 1) + "." + type); + return null; + }); + futures.add(future); + } + + // 等待所有任务完成 + for (Future future : futures) { + future.get(); + } + long endTime = System.currentTimeMillis(); + long duration = (endTime - startTime) / 1000; + System.out.println("费用清单上传图片处理总耗时: " + duration + " 秒"); + + return picNameList; + } catch (IOException | InterruptedException | ExecutionException e) { + e.printStackTrace(); + return null; + } finally { + if (doc != null) { + try { + doc.close(); + } catch (IOException e) { + throw new RuntimeException("关闭PDDocument时发生错误", e); + } + } + // 关闭线程池 + executor.shutdown(); + } + } catch (Exception e) { + e.printStackTrace(); + return null; + }*/ } public static void main(String[] args) { diff --git a/src/main/java/com/emr/util/img2PdfUtil.java b/src/main/java/com/emr/util/img2PdfUtil.java index a85936a..ca5fb21 100644 --- a/src/main/java/com/emr/util/img2PdfUtil.java +++ b/src/main/java/com/emr/util/img2PdfUtil.java @@ -8,8 +8,8 @@ import com.itextpdf.text.pdf.PdfWriter; import com.lowagie.text.DocumentException; import com.lowagie.text.Element; import com.lowagie.text.pdf.*; +import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; -import org.slf4j.Logger; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; @@ -19,8 +19,9 @@ import javax.servlet.http.HttpServletResponse; import java.awt.*; import java.awt.image.BufferedImage; import java.io.*; -import java.util.ArrayList; +import java.util.*; import java.util.List; +import java.util.concurrent.*; /** * @ProjectName: @@ -37,6 +38,7 @@ import java.util.List; public class img2PdfUtil { final private static float A4_weight = 595; //标准A4的宽 final private static float A4_height = 842; //标准A4的高 + final private static Map imageCache = new HashMap<>(); public static void imageToPdf(HttpServletResponse response, List filePaths, String pdfName, EmrPdfWaterSet pdfWaterSet,EmrPdfWaterSet pdfWaterSet1) { Document document = new Document(PageSize.A4, 0, 0, 0, 0); //创建文档容器 @@ -78,9 +80,40 @@ public class img2PdfUtil { } } - - - + public static void imageToPdf(HttpServletResponse response, List filePaths, String pdfName, EmrPdfWaterSet pdfWaterSet,EmrPdfWaterSet pdfWaterSet1, int page) { + Document document = new Document(PageSize.A4, 0, 0, 0, 0); //创建文档容器 + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + //是否启用水印 + Short effective = pdfWaterSet.getEffective(); + Short isImg = pdfWaterSet.getIsImg(); + try { + if (effective == 1 || isImg == 1) { + PdfWriter.getInstance(document, bos); //创建编写器(PDF类型) + } else { + PdfWriter.getInstance(document, response.getOutputStream()); //创建编写器(PDF类型) + } + //图片合成pdf + imgToPdf(document, filePaths, page); + if (effective == 1 || isImg == 1) { + addWaterMark(bos, response, pdfWaterSet.getUpOrUnder(), pdfWaterSet.getTransparent(), + pdfWaterSet.getText(), pdfWaterSet.getTextX(), pdfWaterSet.getTextY(), + pdfWaterSet.getTextColor(), pdfWaterSet.getTextSize(), pdfWaterSet.getTextRotation(), + pdfWaterSet.getEffective(), pdfWaterSet.getIsImg(), pdfWaterSet.getImgFile(), pdfWaterSet.getImgWidth(), + pdfWaterSet.getImgHeight(), pdfWaterSet.getImgX(), pdfWaterSet.getImgY(),pdfWaterSet1.getText()); + } + } catch (Exception e) { + ExceptionPrintUtil.printException(e); + e.printStackTrace(); + } finally { + try { + bos.flush(); + bos.close(); + } catch (IOException e) { + e.printStackTrace(); + } + document.close(); + } + } public static void imageToPdfUserEffective(HttpServletResponse response, List filePaths, String pdfName, EmrPdfWaterSet pdfWaterSet) { Document document = new Document(PageSize.A4, 0, 0, 0, 0); //创建文档容器 @@ -202,29 +235,35 @@ public class img2PdfUtil { } } - //脐血库下载批量 - public static void imageToPdfToBuffOut(ByteArrayOutputStream bos, List filePaths, EmrPdfWaterSet pdfWaterSet) throws Exception { + public static void imageToPdfToBuffOut(PipedOutputStream pos, List filePaths, EmrPdfWaterSet pdfWaterSet) throws Exception { // 实例化图牿 - Document document = new Document(PageSize.A4, 30, 30, 30, 30); //创建文档容器 + Document document = new Document(PageSize.A4, 0, 0, 0, 0); //创建文档容器 //是否启用水印 - PdfWriter.getInstance(document, bos); + PdfWriter.getInstance(document, pos); try { //图片合成pdf imgToPdf(document, filePaths); //是否启用水印 - Short effective = pdfWaterSet.getDownloadEffective(); + /*Short effective = pdfWaterSet.getDownloadEffective(); Short isImg = pdfWaterSet.getDownloadIsImg(); if (effective == 1 || isImg == 1) { addWaterMark(bos, null, pdfWaterSet.getUpOrUnder(), pdfWaterSet.getTransparent(), pdfWaterSet.getText(), pdfWaterSet.getTextX(), pdfWaterSet.getTextY(), pdfWaterSet.getTextColor(), pdfWaterSet.getTextSize(), pdfWaterSet.getTextRotation(), - effective, isImg, pdfWaterSet.getImgFile(), pdfWaterSet.getImgWidth(), pdfWaterSet.getImgHeight(), pdfWaterSet.getImgX(), pdfWaterSet.getImgY()); - } + }*/ } catch (Exception e) { ExceptionPrintUtil.printException(e); e.printStackTrace(); } finally { + try { + if (pos != null) { + pos.flush(); + pos.close(); + } + } catch (IOException e) { + e.printStackTrace(); + } document.close(); } } @@ -364,68 +403,202 @@ public class img2PdfUtil { } } - //图片合成pdf - private static void imgToPdf(Document document, List filePaths) throws Exception { + public static void imgToPdf(Document document, List filePaths, int imagesPerPage) { + long startTime = System.currentTimeMillis(); document.open(); - float percent = 100; + BufferedImage bufferedImage = null; + Image img; + int imageCount = 0; + for (String filePath : filePaths) { - try { - File file = new File(filePath); - if (file.isFile()) { - Image img = Image.getInstance(filePath); - float w = img.getWidth(); - float h = img.getHeight(); - - // 计算缩放比例,基于宽度和高度中较大的值 - float scaleWidth = A4_weight / w; - float scaleHeight = A4_height / h; - percent = Math.min(scaleWidth, scaleHeight) * 100; - - img.setAlignment(com.lowagie.text.Image.ALIGN_CENTER); - img.scalePercent(percent); - document.add(img); + try (FileInputStream fis = new FileInputStream(filePath)) { + if(checkTifFile(filePath)){ + bufferedImage = ImageIO.read(fis); + img = Image.getInstance(bufferedImage, null); + }else{ + img = Image.getInstance(filePath); + } + float w = img.getWidth(); + float h = img.getHeight(); + + // 计算缩放比例,基于宽度和高度中较大的值 + float scaleWidth = A4_weight / w; + float scaleHeight = A4_height / h; + float percent = Math.min(scaleWidth, scaleHeight) * 100; + + img.setAlignment(Image.ALIGN_CENTER); + img.scalePercent(percent); + + //添加图像 + document.add(img); + + imageCount++; + + // 检查是否需要换页 + if (imageCount % imagesPerPage == 0) { + document.newPage(); + } + + if (bufferedImage != null){ + // 关闭资源 + bufferedImage.flush(); } } catch (Exception e) { - throw new RuntimeException("Error processing file: " + filePath, e); + System.err.println("文件加载失败: " + filePath + ", " + e.getMessage()); } } + + long endTime = System.currentTimeMillis(); + long duration = (endTime - startTime) / 1000; + System.out.println("图像合成中耗时: " + duration + " 秒"); + + document.close(); + } + + public static void imgToPdf(Document document, List filePaths) { + document.open(); + BufferedImage bufferedImage = null; + Image img; + for (String filePath : filePaths) { + try (FileInputStream fis = new FileInputStream(filePath)) { + if(checkTifFile(filePath)){ + bufferedImage = ImageIO.read(fis); + img = Image.getInstance(bufferedImage, null); + }else{ + img = Image.getInstance(filePath); + } + float w = img.getWidth(); + float h = img.getHeight(); + + // 计算缩放比例,基于宽度和高度中较大的值 + float scaleWidth = A4_weight / w; + float scaleHeight = A4_height / h; + float percent = Math.min(scaleWidth, scaleHeight) * 100; + + img.setAlignment(Image.ALIGN_CENTER); + img.scalePercent(percent); + + //添加图像 + document.add(img); + if (bufferedImage != null){ + // 关闭资源 + bufferedImage.flush(); + } + } catch (Exception e) { + System.err.println("文件加载失败: " + filePath + ", " + e.getMessage()); + } + } + document.close(); + /*// 记录开始时间 + long startTime = System.currentTimeMillis(); + + int corePoolSize = Runtime.getRuntime().availableProcessors(); + int maximumPoolSize = 4 * corePoolSize; + long keepAliveTime = 60L; // 空闲线程存活时间,单位秒 + BlockingQueue workQueue = new LinkedBlockingQueue<>(); + + ExecutorService executor = new ThreadPoolExecutor( + corePoolSize, + maximumPoolSize, + keepAliveTime, + TimeUnit.SECONDS, + workQueue + ); + + document.open(); + + // 使用 CompletableFuture 处理文件路径,并确保按顺序添加到文档 + CompletableFuture allFutures = CompletableFuture.completedFuture(null); + + for (int i = 0; i < filePaths.size(); i++) { + String filePath = filePaths.get(i); + int finalI = i; + allFutures = allFutures.thenCompose(v -> + CompletableFuture.supplyAsync(() -> processImage(filePath), executor) + .thenAccept(img -> addImageToDocument(document, img, finalI)) + ); + } + + // 等待所有任务完成 + try { + allFutures.get(); + } catch (Exception e) { + System.err.println("文件加载失败: " + filePaths + ", " + e.getMessage()); + } + + long endTime = System.currentTimeMillis(); + long duration = (endTime - startTime) / 1000; + System.out.println("图片加载总耗时: " + duration + " 秒"); + document.close(); -// document.open(); //打开容器 -// float percent = 100; -// float w, h; -// for (String filePath : filePaths) { -// try { -// File file = new File(filePath); -// if (file.isFile()) { -// Image img = Image.getInstance(filePath); -// /*处理图片缩放比例*/ -// w = img.getWidth(); -// h = img.getHeight(); -// if ((w > A4_weight) && (h < A4_height)) { -// percent = (A4_weight * 100) / w; -// } else if ((w < A4_weight) && (h > A4_height)) { -// percent = (A4_height * 100) / h; -// } else if ((w > A4_weight) && (h > A4_height)) { -// -// percent = (A4_weight * 100) / w; -// h = (h * percent) / 100; -// if (h > A4_height) { -// percent = (A4_height * 100) / h; -// } -// } -// img.setAlignment(com.lowagie.text.Image.ALIGN_CENTER); -// if(percent != 100){ -// img.scaleAbsolute(A4_weight,A4_height); -// }else{ -// img.scalePercent(percent); -// } -// document.add(img); -// } -// } catch (Exception e) { -// throw new RuntimeException(e); -// } -// } -// document.close(); //关闭容器 + executor.shutdown();*/ + } + + public static Image processImage(String filePath) { + // 检查缓存 + if (imageCache.containsKey(filePath)) { + return imageCache.get(filePath); + } + BufferedImage bufferedImage = null; + Image img = null; + try (FileInputStream fis = new FileInputStream(filePath)) { + if(checkTifFile(filePath)){ + bufferedImage = ImageIO.read(fis); + img = Image.getInstance(bufferedImage, null); + }else{ + img = Image.getInstance(filePath); + } + float w = img.getWidth(); + float h = img.getHeight(); + + // 计算缩放比例,基于宽度和高度中较大的值 + float scaleWidth = A4_weight / w; + float scaleHeight = A4_height / h; + float percent = Math.min(scaleWidth, scaleHeight) * 100; + + img.setAlignment(Image.ALIGN_CENTER); + img.scalePercent(percent); + + if (bufferedImage != null){ + // 关闭资源 + bufferedImage.flush(); + } + + // 缓存处理后的图像 + imageCache.put(filePath, img); + + } catch (Exception e) { + System.err.println("文件加载失败: " + filePath + ", " + e.getMessage()); + } + return img; + } + + public static synchronized void addImageToDocument(Document document, Image img, int index) { + try { + if (img != null) { + document.add(img); + } + } catch (Exception e) { + throw new RuntimeException("添加图像到document失败,图像序号为:" + index, e); + } + } + + /** + * 判断是否是tif图片 + * + * @param srcPath + * @return + */ + public static boolean checkTifFile(String srcPath) { + try (InputStream is = new FileInputStream(new File(srcPath))) { + byte[] content = IOUtils.toByteArray(is); + return content.length >= 4 && + content[0] == 0x49 && content[1] == 0x49 && + content[2] == 0x2A && content[3] == 0x00; + } catch (IOException e) { + System.err.println("Error reading file: " + srcPath + ", " + e.getMessage()); + return false; + } } //图片合成pdf @@ -572,14 +745,14 @@ public class img2PdfUtil { reader.close(); } } - /*public static void addWaterMark(ByteArrayOutputStream bos, HttpServletResponse response, int upOrUnder, float transparent, String text, int textX, int textY, + + public static void addWaterMark(ByteArrayOutputStream bos, HttpServletResponse response, int upOrUnder, float transparent, String text, int textX, int textY, String textColor, int textSize, int textRotation, Short effective, Short isImg, - String imgFile, int imgWidth, int imgHeight, int imgX, int imgY) { + String imgFile, int imgWidth, int imgHeight, int imgX, int imgY,String text1) { PdfReader reader = null; PdfStamper stamper = null; try { reader = new PdfReader(bos.toByteArray()); - bos.reset(); // 重置 bos,以便 PdfStamper 可以写入 // 加完水印的文件 if (null != response) { stamper = new PdfStamper(reader, response.getOutputStream()); @@ -588,13 +761,12 @@ public class img2PdfUtil { } // 设置字体 BaseFont font = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED); - + // PDF总页数 + int total = reader.getNumberOfPages() + 1; // 循环对每页插入水印 PdfContentByte content; PdfGState gs = new PdfGState(); - // PDF总页数 - int total = reader.getNumberOfPages(); - for (int i = 1; i <= total; i++) { + for (int i = 1; i < total; i++) { //upOrUnder = 1为在文本之上 if (upOrUnder == 1) { // 水印在之前文本之上 @@ -648,6 +820,32 @@ public class img2PdfUtil { // 底部水印 content.endText(); } + if(StringUtils.isNotBlank(text1)){ + content.beginText(); + //16进制颜色转color + Color color = toColorFromString(textColor); + content.setColorFill(color); + // 设置字体及字号 + content.setFontAndSize(font, textSize); + // 设置起始位置 + content.setTextMatrix(textX, textY); + // 中间水印 + content.showTextAligned(Element.ALIGN_LEFT, text1, textX, textY - 100, textRotation); + // 底部水印 + content.endText(); + //第二水印 + content.beginText(); + //16进制颜色转color + content.setColorFill(color); + // 设置字体及字号 + content.setFontAndSize(font, textSize); + // 设置起始位置 + content.setTextMatrix(textX, textY); + // 中间水印 + content.showTextAligned(Element.ALIGN_LEFT, text, textX, textY, textRotation); + // 底部水印 + content.endText(); + } } } catch (IOException | DocumentException e) { ExceptionPrintUtil.printException(e); @@ -664,11 +862,7 @@ public class img2PdfUtil { reader.close(); } } - }*/ - public static void addWaterMark(ByteArrayOutputStream bos, HttpServletResponse response, int upOrUnder, float transparent, String text, int textX, int textY, - String textColor, int textSize, int textRotation, Short effective, Short isImg, - String imgFile, int imgWidth, int imgHeight, int imgX, int imgY,String text1) { - PdfReader reader = null; + /*PdfReader reader = null; PdfStamper stamper = null; try { reader = new PdfReader(bos.toByteArray()); @@ -780,7 +974,7 @@ public class img2PdfUtil { if (null != reader) { reader.close(); } - } + }*/ } private static void addWaterMarkFont(ByteArrayOutputStream bos, int upOrUnder, float transparent, String text, int textX, int textY, @@ -882,7 +1076,7 @@ public class img2PdfUtil { * @param colorStr 16进制颜色字符串 * @return Color对象 */ - private static Color toColorFromString(String colorStr) { + public static Color toColorFromString(String colorStr) { int r = Integer.valueOf(colorStr.substring(1, 3), 16); int g = Integer.valueOf(colorStr.substring(3, 5), 16); int b = Integer.valueOf(colorStr.substring(5, 7), 16); diff --git a/src/main/java/com/emr/util/imgToPdfUtil.java b/src/main/java/com/emr/util/imgToPdfUtil.java index 8708a2f..97d20b3 100644 --- a/src/main/java/com/emr/util/imgToPdfUtil.java +++ b/src/main/java/com/emr/util/imgToPdfUtil.java @@ -1,23 +1,23 @@ package com.emr.util; - import com.emr.entity.emrPdfWaterSet.EmrPdfWaterSet; import com.emr.vo.commomSearch.ScanPathVo; import com.itextpdf.text.*; +import com.itextpdf.text.Image; import com.itextpdf.text.pdf.*; -import com.twelvemonkeys.imageio.metadata.tiff.IFD; import org.apache.commons.lang3.StringUtils; import org.springframework.util.ObjectUtils; +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; +import javax.servlet.ServletOutputStream; +import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import java.io.ByteArrayOutputStream; import java.io.File; -import java.io.FileOutputStream; import java.io.IOException; -import java.util.ArrayList; +import java.net.URLEncoder; import java.util.List; -import static com.emr.util.img2PdfUtil.addWaterMark; /** * @ClassName imgToPdfUtil @@ -28,8 +28,13 @@ import static com.emr.util.img2PdfUtil.addWaterMark; */ public class imgToPdfUtil { + //标签顺序 + private static int outNum = 1; + private static int pageIndex = 0; + private static String lastOutline = null; //上一个目录名称 + private static boolean outFlag = true;//是否增加标签 - public static void imageToPdf(HttpServletResponse response, List scanPathVos, String pdfName, EmrPdfWaterSet pdfWaterSet, EmrPdfWaterSet pdfWaterSet1) { + /*public static void imageToPdf(HttpServletResponse response, List scanPathVos, String pdfName, EmrPdfWaterSet pdfWaterSet, EmrPdfWaterSet pdfWaterSet1) throws IOException { Document document = new Document(PageSize.A4, 0, 0, 0, 0); //创建文档容器 ByteArrayOutputStream bos = new ByteArrayOutputStream(); PdfWriter writer; @@ -63,8 +68,170 @@ public class imgToPdfUtil { } document.close(); } + }*/ + + public static void imageToPdf(HttpServletResponse response, List scanPathVos, String pdfName, EmrPdfWaterSet pdfWaterSet, EmrPdfWaterSet pdfWaterSet1) throws IOException { + Document document = new Document(PageSize.A4, 0, 0, 0, 0); // 创建文档容器 + ServletOutputStream out = response.getOutputStream(); + PdfWriter writer; + outNum = 1; + pageIndex = 0; + + try { + writer = PdfWriter.getInstance(document, out); // 创建编写器(PDF类型) + + pdfName = URLEncoder.encode(pdfName, "UTF-8"); + response.reset(); + response.setCharacterEncoding("utf-8"); + response.setContentType("application/pdf"); // 设置正确的内容类型 + response.setHeader("Content-Disposition", "attachment; filename=" + pdfName + ".pdf"); + + document.open(); + for (ScanPathVo scanPathVo : scanPathVos) { + imgToPdf(document, writer, scanPathVo, pdfWaterSet, pdfWaterSet1.getText()); + pageIndex++; + out.flush(); + } + document.close(); + } catch (Exception e) { + // 记录详细的异常信息 + ExceptionPrintUtil.printException(e); + e.printStackTrace(); + // 响应客户端错误信息 + response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + response.getWriter().write("生成PDF文件时发生错误: " + e.getMessage()); + } finally { + try { + if (out != null) { + out.close(); + } + } catch (IOException e) { + e.printStackTrace(); + } + } } + //图片合成pdf增加目录 + public static void imgToPdf(Document document, PdfWriter writer, ScanPathVo scanPathVos, EmrPdfWaterSet pdfWaterSet, String userText) throws Exception { + PdfContentByte cb = writer.getDirectContent(); + cb.setFontAndSize(BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED), 12); + cb.beginText(); + cb.showTextAligned(PdfContentByte.ALIGN_CENTER, "目录", 300, 780, 0); + cb.endText(); + // 创建目录 + PdfOutline root = cb.getRootOutline(); + float percent = 100; + // 添加图片到PDF + String assortName = scanPathVos.getAssortName(); + if(!ObjectUtils.isEmpty(assortName)){ + if (StringUtils.isNotBlank(lastOutline) && lastOutline.equals(assortName)) { + outFlag = false; + } + if (StringUtils.isBlank(lastOutline)) { + lastOutline = assortName; + outFlag=true; + } + if (!lastOutline.equals(assortName)){ + lastOutline = assortName; + outFlag=true; + } + } + String imagePath = scanPathVos.getFileRealPath(); + if(imagePath.contains("/mnt/share")){ + imagePath = imagePath.replace("\\", "/"); + } + Image image = Image.getInstance(imagePath); + float w = image.getWidth(); + float h = image.getHeight(); + + // 计算缩放比例,基于宽度和高度中较大的值 + float scaleWidth = PageSize.A4.getWidth() / w; + float scaleHeight = PageSize.A4.getHeight() / h; + percent = Math.min(scaleWidth, scaleHeight) * 100; + + image.setAlignment(image.MIDDLE); + image.scalePercent(percent); + + // 创建新页面并添加图片 + if (pageIndex != 0) { + document.newPage(); + } + // 创建新页面并添加图片 + document.add(image); + + //添加水印 + addImageWaterMark(image, cb, pdfWaterSet, userText); + + if (outFlag) { + //目录跳转页面内容设置。 + PdfAction action = PdfAction.gotoLocalPage(pageIndex + 1, new PdfDestination(PdfDestination.FIT), writer); + //标题目录 + String title = outNum + "." + scanPathVos.getAssortName(); + new PdfOutline(root, action, title, false); + outNum++; + } + } + + public static void addImageWaterMark(Image image, PdfContentByte cb, EmrPdfWaterSet pdfWaterSet, String userText) throws Exception { + // 添加图像水印 + if (pdfWaterSet.getIsImg() == 1) { + HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); + String tomcatPath = request.getSession().getServletContext().getRealPath("/"); + String imgStr = tomcatPath + "static\\pdfWaterSet\\upload\\" + pdfWaterSet.getImgFile(); + Image watermarkImg; + if (StringUtils.isNotBlank(imgStr) && new File(imgStr).isFile()) { + watermarkImg = Image.getInstance(imgStr); + //位置 + image.setAbsolutePosition(pdfWaterSet.getImgX(), pdfWaterSet.getImgY()); + // 设置图片的显示大小 + image.scaleToFit(pdfWaterSet.getImgWidth(), pdfWaterSet.getImgHeight()); + cb.addImage(watermarkImg); + } + } + + // 添加文字水印 + if (pdfWaterSet.getEffective() == 1) { + PdfGState gstate = new PdfGState(); + gstate.setFillOpacity(pdfWaterSet.getTransparent()); // 设置透明度 + cb.saveState(); + cb.setGState(gstate); + cb.beginText(); + // 设置字体 + BaseFont font = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED); + cb.setFontAndSize(font, pdfWaterSet.getTextSize()); + cb.setTextMatrix(pdfWaterSet.getTextX(), pdfWaterSet.getTextY()); + cb.setColorFill(parseColor(pdfWaterSet.getTextColor())); + cb.showTextAligned(Element.ALIGN_LEFT, pdfWaterSet.getText(), pdfWaterSet.getTextX(), pdfWaterSet.getTextY(), pdfWaterSet.getTextRotation()); // 水印文本、位置和旋转角度 + cb.endText(); + cb.restoreState(); + } + + //用户水印 + if (pdfWaterSet.getUserEffective() == 1) { + PdfGState gstate = new PdfGState(); + gstate.setFillOpacity(pdfWaterSet.getTransparent()); // 设置透明度 + cb.saveState(); + cb.setGState(gstate); + cb.beginText(); + BaseFont font = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED); + cb.setFontAndSize(font, pdfWaterSet.getTextSize()); + cb.setTextMatrix(pdfWaterSet.getTextX(), pdfWaterSet.getTextY()); + cb.setColorFill(parseColor(pdfWaterSet.getTextColor())); + cb.showTextAligned(Element.ALIGN_LEFT, userText, pdfWaterSet.getTextX(), pdfWaterSet.getTextY() - 100, pdfWaterSet.getTextRotation()); // 水印文本、位置和旋转角度 + cb.endText(); + cb.restoreState(); + } + } + + public static BaseColor parseColor(String colorStr) { + if (colorStr.startsWith("#")) { + colorStr = colorStr.substring(1); + } + int r = Integer.parseInt(colorStr.substring(0, 2), 16); + int g = Integer.parseInt(colorStr.substring(2, 4), 16); + int b = Integer.parseInt(colorStr.substring(4, 6), 16); + return new BaseColor(r, g, b); + } //图片合成pdf增加目录 public static void imgToPdf(Document document, PdfWriter writer, List scanPathVos) throws Exception { @@ -116,7 +283,10 @@ public class imgToPdfUtil { image.setAlignment(image.MIDDLE); image.scalePercent(percent); // 创建新页面并添加图片 - //document.newPage(); + if (i != 0) { + document.newPage(); + } + // 创建新页面并添加图片 document.add(image); if (outFlag) { //目录跳转页面内容设置。 @@ -128,5 +298,107 @@ public class imgToPdfUtil { } } document.close(); //关闭容器 + + /*final String[] lastOutline = {null}; // 上一个目录名称 + final boolean[] outFlag = {true}; // 是否增加标签 + final Integer[] outNum = {1}; // 标签顺序 + final float[] percent = {100}; + PdfContentByte cb = writer.getDirectContent(); + cb.setFontAndSize(BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED), 12); + + cb.beginText(); + cb.showTextAligned(PdfContentByte.ALIGN_CENTER, "目录", 300, 780, 0); + cb.endText(); + + // 创建根目录 + PdfOutline root = cb.getRootOutline(); + + // 创建线程池 + int corePoolSize = Runtime.getRuntime().availableProcessors(); + int maximumPoolSize = 4 * corePoolSize; + long keepAliveTime = 60L; // 空闲线程存活时间,单位秒 + BlockingQueue workQueue = new LinkedBlockingQueue<>(); + + ExecutorService executor = new ThreadPoolExecutor( + corePoolSize, + maximumPoolSize, + keepAliveTime, + TimeUnit.SECONDS, + workQueue + ); + + // 使用 CompletableFuture 处理文件路径,并确保按顺序添加到文档 + CompletableFuture allFutures = CompletableFuture.completedFuture(null); + + for (int i = 0; i < scanPathVos.size(); i++) { + ScanPathVo scanPathVo = scanPathVos.get(i); + int finalI = i; + allFutures = allFutures.thenCompose(v -> + CompletableFuture.supplyAsync(() -> processImage(scanPathVo), executor) + .thenAccept(img -> addImageToDocument(document, img, finalI, lastOutline, outFlag, outNum, root, writer, scanPathVos)) + ); + } + + // 等待所有任务完成 + allFutures.join(); + + // 关闭线程池 + executor.shutdown();*/ + } + + public static Image processImage(ScanPathVo scanPathVo) { + try { + String imagePath = scanPathVo.getFileRealPath(); + if (imagePath.contains("/mnt/share")) { + imagePath = imagePath.replace("\\", "/"); + } + Image image = Image.getInstance(imagePath); + float w = image.getWidth(); + float h = image.getHeight(); + + // 计算缩放比例,基于宽度和高度中较大的值 + float scaleWidth = PageSize.A4.getWidth() / w; + float scaleHeight = PageSize.A4.getHeight() / h; + float percent = Math.min(scaleWidth, scaleHeight) * 100; + + image.setAlignment(image.MIDDLE); + image.scalePercent(percent); + return image; + } catch (IOException | BadElementException e) { + e.printStackTrace(); + throw new RuntimeException("Error processing image", e); + } + } + + public static void addImageToDocument(Document document, Image image, int pageIndex, String[] lastOutline, boolean[] outFlag, Integer[] outNum, PdfOutline root, PdfWriter writer, List scanPathVos) { + try { + synchronized (document) { + document.add(image); + } + String assortName = scanPathVos.get(pageIndex).getAssortName(); + if (!ObjectUtils.isEmpty(assortName)) { + if (StringUtils.isNotBlank(lastOutline[0]) && lastOutline[0].equals(assortName)) { + outFlag[0] = false; + } + if (StringUtils.isBlank(lastOutline[0])) { + lastOutline[0] = assortName; + outFlag[0] = true; + } + if (!lastOutline[0].equals(assortName)) { + lastOutline[0] = assortName; + outFlag[0] = true; + } + } + if (outFlag[0]) { + // 目录跳转页面内容设置。 + PdfAction action = PdfAction.gotoLocalPage(pageIndex + 1, new PdfDestination(PdfDestination.FIT), writer); + // 标题目录 + String title = outNum[0] + "." + assortName; + new PdfOutline(root, action, title, false); + outNum[0]++; + } + } catch (Exception e) { + e.printStackTrace(); + } } } diff --git a/src/main/java/com/emr/vo/Msg.java b/src/main/java/com/emr/vo/Msg.java index f37c7df..d5c8ebf 100644 --- a/src/main/java/com/emr/vo/Msg.java +++ b/src/main/java/com/emr/vo/Msg.java @@ -25,7 +25,7 @@ public class Msg { public static Msg success(){ Msg result=new Msg(); - result.setCode(100); + result.setCode(200); result.setMsg("success"); return result; } @@ -41,7 +41,7 @@ public class Msg { public static Msg successData(Object data){ Msg result=new Msg(); - result.setCode(100); + result.setCode(200); result.setMsg("success"); result.setData(data); return result; @@ -51,7 +51,7 @@ public class Msg { public static Msg fail(){ Msg result=new Msg(); - result.setCode(200); + result.setCode(500); result.setMsg("fail"); return result; } @@ -60,7 +60,7 @@ public class Msg { public static Msg fail(String msg){ Msg result=new Msg(); - result.setCode(200); + result.setCode(500); result.setMsg(msg); return result; } diff --git a/src/main/resources/config/applicationContext.xml b/src/main/resources/config/applicationContext.xml index d3f3c79..88d61ee 100644 --- a/src/main/resources/config/applicationContext.xml +++ b/src/main/resources/config/applicationContext.xml @@ -54,7 +54,7 @@ - + diff --git a/src/main/resources/config/config.properties b/src/main/resources/config/config.properties index 347e69c..12cc2c5 100644 --- a/src/main/resources/config/config.properties +++ b/src/main/resources/config/config.properties @@ -1,9 +1,9 @@ #power\u6743\u9650\u7CFB\u7EDF\u7684\u670D\u52A1\u5668\u5730\u5740\u5934 POWER_IP =localhost -POWER_URLHEAD = http://localhost:8081/power +POWER_URLHEAD = http://localhost:8080/power POWER_JSPHEAD = localhost -POWER_JSP = http://localhost:8081/power +POWER_JSP = http://localhost:8080/power #\u672C\u8EAB\u7CFB\u7EDF\u7684\u670D\u52A1\u5668\u5730\u5740\u5934 EMR_RECORD_JSP = http://localhost:8081/emr_record @@ -17,7 +17,7 @@ STR_SPLIT = *^:|,. #\u65E5\u5FD7\u4FDD\u7559\u5929\u6570 log.days = 180 -pdfWater = \u6F6E\u5DDE\u5E02\u4EBA\u6C11\u533B\u9662 +pdfWater = \u5e7f\u4e1c\u7701\u005f\u5e7f\u5dde\u5e02\u5929\u6cb3\u4eba\u6c11\u533b\u9662 #session\u8FC7\u671F\u65F6\u95F4ms TOKEN_EXPIRE_TIME = 3600000 @@ -43,7 +43,9 @@ applyApproveFlag =0 #//????? initialization =0 -export_pdf_hospital_info =\u6E58\u96C5\u533B\u9662 +export_pdf_hospital_info = \u5e7f\u4e1c\u7701\u005f\u6e5b\u6c5f\u5e02\u005f\u9042\u6eaa\u53bf\u4eba\u6c11\u533b\u9662 +#\u5e7f\u4e1c\u7701\u005f\u6e5b\u6c5f\u5e02\u005f\u9042\u6eaa\u53bf\u4eba\u6c11\u533b\u9662 +#\u5e7f\u4e1c\u7701\u005f\u5e7f\u5dde\u5e02\u5929\u6cb3\u533a\u4eba\u6c11\u533b\u9662 export_pdf_patient_info = inpatientNo,disDate @@ -65,8 +67,5 @@ NEW_EMR_RECORD_JSP : http://localhost:8081/emr_record #\u8D39\u7528\u6E05\u5355\u751F\u6210\u7684\u76EE\u5F55 cost_pdf_path=D://cost// -# ??????token -guangzong_token=JxUAVD4BGlRGTVRFRU5BRk5FQFQ3JyBURkRGQA== - diff --git a/src/main/resources/config/jdbc.properties b/src/main/resources/config/jdbc.properties index 510c3a9..6ee46e6 100644 --- a/src/main/resources/config/jdbc.properties +++ b/src/main/resources/config/jdbc.properties @@ -3,10 +3,14 @@ jdbc.driver=com.microsoft.sqlserver.jdbc.SQLServerDriver #jdbc.username=sa #jdbc.password=docus@702 -jdbc.url=jdbc\:sqlserver\://localhost:1433;databaseName=qf_record +jdbc.url=jdbc\:sqlserver\://192.168.2.22:1433;databaseName=qf_record_lin jdbc.username=sa -jdbc.password=admin123 +jdbc.password=123456 #dataSource2 -jdbc.url2=jdbc\:sqlserver\://localhost:1433;databaseName=blgd_java -jdbc.username2=jsuser -jdbc.password2=123456 +jdbc.driver2=com.mysql.jdbc.Driver +jdbc.url2=jdbc\:mysql\://192.168.2.22\:3306/gyw?useUnicode\=true&characterEncoding\=utf-8 +jdbc.username2=root +jdbc.password2=root +#jdbc.url2=jdbc\:sqlserver\://localhost:1433;databaseName=blgd_java +#jdbc.username2=jsuser +#jdbc.password2=123456 diff --git a/src/main/resources/mapper/Archive_DetailMapper.xml b/src/main/resources/mapper/Archive_DetailMapper.xml index 3602b85..c2a8cec 100644 --- a/src/main/resources/mapper/Archive_DetailMapper.xml +++ b/src/main/resources/mapper/Archive_DetailMapper.xml @@ -118,57 +118,21 @@ + + + + + + + + + + + insert into t_scan_assort + ( + patient_id, + assort_id, + scan_page, + source, + is_del + ) + values + ( + #{patientId}, + #{assortId}, + #{scanPage}, + 1, + 0 + ) + + + \ No newline at end of file diff --git a/src/main/resources/mapper/ExportTaskMapper.xml b/src/main/resources/mapper/ExportTaskMapper.xml index b593e46..94d6486 100644 --- a/src/main/resources/mapper/ExportTaskMapper.xml +++ b/src/main/resources/mapper/ExportTaskMapper.xml @@ -40,6 +40,7 @@ AND CONVERT ( VARCHAR ( 100 ), create_date, 23 ) <= #{endTime} + order by create_date desc delete from Export_Task diff --git a/src/main/resources/mapper/Zd_AssortMapper.xml b/src/main/resources/mapper/Zd_AssortMapper.xml index fbb5d73..4b29432 100644 --- a/src/main/resources/mapper/Zd_AssortMapper.xml +++ b/src/main/resources/mapper/Zd_AssortMapper.xml @@ -75,7 +75,7 @@ SELECT dbo.zd_assort.assort_id, dbo.zd_assort.assort_name, - dbo.emr_type_related.id printFlag + dbo.emr_type_related.id print_flag FROM dbo.zd_assort LEFT OUTER JOIN @@ -116,7 +116,7 @@ DISTINCT assort_id, assort_name, - emr_user_reader.record_id printFlag, + emr_user_reader.record_id print_flag, assort_sort FROM zd_assort diff --git a/src/main/webapp/WEB-INF/dispatcherServlet-servlet.xml b/src/main/webapp/WEB-INF/dispatcherServlet-servlet.xml index 14e6db1..60e7678 100644 --- a/src/main/webapp/WEB-INF/dispatcherServlet-servlet.xml +++ b/src/main/webapp/WEB-INF/dispatcherServlet-servlet.xml @@ -57,6 +57,7 @@ + diff --git a/src/main/webapp/WEB-INF/views/recordManage/bloodPurification/inspectionRecords.jsp b/src/main/webapp/WEB-INF/views/recordManage/bloodPurification/inspectionRecords.jsp index 9c4aedb..dc79bc8 100644 --- a/src/main/webapp/WEB-INF/views/recordManage/bloodPurification/inspectionRecords.jsp +++ b/src/main/webapp/WEB-INF/views/recordManage/bloodPurification/inspectionRecords.jsp @@ -162,7 +162,7 @@
- +
diff --git a/src/main/webapp/WEB-INF/views/recordManage/commomSearch/commomListqf.jsp b/src/main/webapp/WEB-INF/views/recordManage/commomSearch/commomListqf.jsp index a373470..e4b2d51 100644 --- a/src/main/webapp/WEB-INF/views/recordManage/commomSearch/commomListqf.jsp +++ b/src/main/webapp/WEB-INF/views/recordManage/commomSearch/commomListqf.jsp @@ -216,6 +216,8 @@ + + @@ -616,6 +618,17 @@
+
+
+
+ +
+
+ +
+
+
@@ -863,6 +876,9 @@
+ <%--
+ +
--%>
@@ -1017,6 +1033,14 @@
+
+ +
+ +
+
+
diff --git a/src/main/webapp/WEB-INF/views/recordManage/commomSearch/showRecordIframeBlood.jsp b/src/main/webapp/WEB-INF/views/recordManage/commomSearch/showRecordIframeBlood.jsp index 189a0c0..0e3e55a 100644 --- a/src/main/webapp/WEB-INF/views/recordManage/commomSearch/showRecordIframeBlood.jsp +++ b/src/main/webapp/WEB-INF/views/recordManage/commomSearch/showRecordIframeBlood.jsp @@ -267,6 +267,8 @@
+ +