using Common; using iTextSharp.text; using iTextSharp.text.pdf; using LisPacsDataUpload.Models.Report; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Diagnostics; using System.IO; using System.Linq; using System.Net; using System.Reflection; using System.Security.Cryptography.X509Certificates; namespace LisPacsDataUpload.business { /// /// pdf 工具类 /// public class PdfUtils { /// /// 根据lis版本获取请求生成pdf报告的参数 0中联老版lis 1 中联新版lis 2 专业版临生免 10 标准服务老版lis 11标准服务新版lis 3 三方lis /// /// public static string getPdfParamByLisVersion(int lisVersion, string reportNumber,string bbid,string yzid) { string dicLis = AppDomain.CurrentDomain.BaseDirectory + "Lis\\"; if (!Directory.Exists(dicLis)) { Directory.CreateDirectory(dicLis); } string path = dicLis + "LIS" + bbid+ ".pdf"; Paramater paramter = new Paramater { RePortCode = reportNumber, PdfPath = $"pdf={path}", InvokeType = 4 }; if (lisVersion==0) { //老版lis /* Select Distinct 'ZLCISBILL' || Trim(To_Char(b.编号, '00000')) || '-2' 报表编号, a.相关id, d.id 标本id From 病人医嘱记录 A,检验标本记录 d, 病历文件列表 B, 病历单据应用 C Where a.诊疗项目id = c.诊疗项目id And a.病人来源 = c.应用场合 And c.病历文件id = b.Id And a.Id = :id and a.相关id = d.医嘱id*/ paramter.ZlSysCode = 100; paramter.Params.Add(new SubParameter { Param = $"医嘱id={yzid}" }); paramter.Params.Add(new SubParameter { Param = $"标本id={bbid}" }); string strJson = JsonConvert.SerializeObject(paramter); LogHelper.Info("strJson==" + strJson); if (!Init()) { LogHelper.Info("Init初始化异常"); return "Init初始化异常"; } //生成pdf成功 if (OutPdf(strJson)) { return path; } } else if (lisVersion == 1) { paramter.ZlSysCode = 2500; paramter.Params.Add(new SubParameter { Param = $"标本id={bbid}" }); // 新版lis /* Select distinct 'ZLLISBILL00' || Decode(b.病人来源, 2, c.住院单据, 3, c.体检单据, 4, c.院外单据, c.门诊单据) || '-2' 报表编号, a.Id 标本id From 检验报告记录 A, 检验申请组合 B, 检验仪器记录 C Where a.Id = b.标本id And a.仪器id = c.Id And b.医嘱id = :id*/ string strJson= JsonConvert.SerializeObject(paramter); LogHelper.Info("strJson=="+ strJson); if (!Init()) { LogHelper.Info("Init初始化异常"); return "Init初始化异常"; } //生成pdf成功 if (OutPdf(strJson)) { return path; } } else if (lisVersion == 2) { //专业版临生免 string sql_zlhr = @"select standard_url from 互认配置表"; DataTable dt_lis = OracleHelper.RunQueryDS(sql_zlhr); string standard_url = dt_lis.Rows[0]["standard_url"].ToString(); string jsonTemplate = "{\"input\":{\"req_info\":{\"rpt_id\":\"{rpt_id}\",\"rpt_type\":\"0\"},\"head\":{\"bizno\":\"S4021\",\"sysno\":\"zlhr\",\"tarno\":\"ZLHIS\",\"time\":\"{time}\",\"action_no\":\"{action_no}\"}}}"; // 使用字符串插值替换占位符 string data = jsonTemplate .Replace("{rpt_id}", bbid) .Replace("{time}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")) .Replace("{action_no}", Guid.NewGuid().ToString()); string responseString = Tools.WSDataToZlsoftInterface(standard_url, data); ZlsoftOutVO zlsoftOutVO = JsonConvert.DeserializeObject(responseString); if (!"A".Equals(zlsoftOutVO.input.ack_info.exe_status)) { return zlsoftOutVO.input.ack_info.err_msg; } return zlsoftOutVO.input.file_info.rpt_content; } else if(lisVersion == 3) { // 三方lis string three_sql = @"select pdfUrl from three_lis_pdf where yzid ='" + bbid+"'"; LogHelper.Info("three_sql "+ three_sql); List pdfs = SqlServerHelper.GetPdfUrlList(three_sql); if (pdfs != null && pdfs.Count()>0) { GetPdfFromJpgList(pdfs, path); return path; } return "三方lispdf报告获取失败"; } else if (lisVersion == 10) { // 三方lis if (DownloadPdf2(reportNumber, path)) { return path; }; return "标准服务lispdf报告获取失败"; } return "失败"; } public static void GetPdfFromJpg(string jpgUrl,string pdfUrl) { LogHelper.Info("开始从jpg转换pdf"); //string jpgFilePath = "path_to_your_jpg.jpg"; //string pdfFilePath = "output.pdf"; using (FileStream fs = new FileStream(pdfUrl, FileMode.Create)) { // 创建一个文档对象 Document document = new Document(); // 创建一个 PDF 写入器,将文档写入文件流 PdfWriter writer = PdfWriter.GetInstance(document, fs); document.Open(); // 创建一个图像对象并加载 JPG 文件 Image image = Image.GetInstance(jpgUrl); // 设置图像在 PDF 中的尺寸(可以根据需要调整) image.ScaleToFit(document.PageSize.Width - 20, document.PageSize.Height - 20); // 将图像添加到 PDF 文档中 document.Add(image); document.Close(); } LogHelper.Info("JPG 转换为 PDF 成功!"); } public static void GetPdfFromJpgList(List jpgUrls, string pdfUrl) { LogHelper.Info("开始从jpg列表转换pdf"); using (FileStream fs = new FileStream(pdfUrl, FileMode.Create)) { // 创建一个文档对象 Document document = new Document(); // 创建一个 PDF 写入器,将文档写入文件流 PdfWriter writer = PdfWriter.GetInstance(document, fs); document.Open(); foreach (string jpgUrl in jpgUrls) { try { LogHelper.Info("三方pdfUrl="+ jpgUrl); // 创建一个图像对象并加载 JPG 文件 Image image = Image.GetInstance(jpgUrl); // 设置图像在 PDF 中的尺寸(可以根据需要调整) // 这里为了保持图片比例,我们先获取图片的原始尺寸 float imgWidth = image.ScaledWidth; float imgHeight = image.ScaledHeight; // 根据需要调整图片大小,这里以A4纸大小减去边距为例 float pdfWidth = document.PageSize.Width - 20; float pdfHeight = document.PageSize.Height - 20; // 根据宽度或高度调整图片大小,保持比例 float scaleFactor = Math.Min(pdfWidth / imgWidth, pdfHeight / imgHeight); image.ScaleAbsolute(imgWidth * scaleFactor, imgHeight * scaleFactor); // 将图像添加到 PDF 文档中 document.Add(image); // 添加一个空行以分隔图片(可选) document.Add(new Paragraph(string.Empty)); document.NewPage(); // 如果需要在每张图片后添加新页,则使用此行 } catch (Exception ex) { LogHelper.Error(ex ,"无法加载图片"+jpgUrl); } } document.Close(); } LogHelper.Info("JPG 列表转换为 PDF 成功!"); } public static string GeneratePdf(int lisVersion, string reportNumber, string bbid, string yzid) { string pdfUrl = getPdfParamByLisVersion(lisVersion, reportNumber, bbid, yzid); LogHelper.Info("GeneratePdf=="); return pdfUrl; } private static bool AcceptAllCertificates(object sender, X509Certificate certificate, X509Chain chain, bool sslPolicyErrors) { return true; } public static bool DownloadPdf(string pdfUrl, string localFilePath) { // 忽略证书验证 try { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(pdfUrl); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); if (response.StatusCode == HttpStatusCode.OK) { using (Stream responseStream = response.GetResponseStream()) { using (FileStream fileStream = new FileStream(localFilePath, FileMode.Create)) { byte[] buffer = new byte[1024*10]; int bytesRead; while ((bytesRead = responseStream.Read(buffer, 0, buffer.Length)) > 0) { fileStream.Write(buffer, 0, bytesRead); } } } return true; } else { LogHelper.Info($"下载失败,状态码: {response.StatusCode}"); return false; } } catch (Exception ex) { LogHelper.Info($"下载过程中出现错误: {ex.Message}"); return false; } } public static bool DownloadPdf2(string pdfUrl, string localFilePath) { using (WebClient client = new WebClient()) { try { client.DownloadFile(pdfUrl, localFilePath); LogHelper.Info("文件下载成功!"); return true; } catch (Exception ex) { LogHelper.Info($"文件下载失败:{ex.Message}"); return false; } } } static object Instance = null; public static bool Init() { if (Instance != null ) { return true; } var para = JsonConvert.SerializeObject(new UserLogin { UserName = ConfigurationManager.AppSettings["UserName"], PassWord = ConfigurationManager.AppSettings["PasWord"], Server = ConfigurationManager.AppSettings["Server"] }); LogHelper.Info("初始化入参" + para); string strReval = string.Empty; try { Process.GetProcessesByName("zlgyReport").ToList().ForEach(x => x.Kill()); } catch (Exception ex) { LogHelper.Info("进程结束异常" + ex.Message); } var type = Type.GetTypeFromProgID("zlgyReport.clsGyReport"); Instance = Activator.CreateInstance(type); ParameterModifier modifier = new ParameterModifier(2); modifier[1] = true; var result = type.InvokeMember("Init", BindingFlags.Default | BindingFlags.InvokeMethod, null, Instance, new object[] { para, strReval }, new ParameterModifier[] { modifier }, null, new string[] { "strJson", "strResult" }); LogHelper.Info("出参:" + strReval); LogHelper.Info("返回:" + result.ToString()); return (bool)result; } public static bool OutPdf(string para) { var type = Type.GetTypeFromProgID("zlgyReport.clsGyReport"); ParameterModifier modifier = new ParameterModifier(2); modifier[1] = true; string strReval = string.Empty; var result = type.InvokeMember("ReportOpen", BindingFlags.Default | BindingFlags.InvokeMethod, null, Instance, new object[] { para, strReval }, new ParameterModifier[] { modifier }, null, new string[] { "strJson", "strResult" }); LogHelper.Info("出参:" + strReval); LogHelper.Info("返回:" + result.ToString()); return (bool)result; } public class UserLogin { public string UserName { get; set; } public string PassWord { get; set; } public string Server { get; set; } } } }