PdfUtils.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  1. using Common;
  2. using iTextSharp.text;
  3. using iTextSharp.text.pdf;
  4. using LisPacsDataUpload.Models.Report;
  5. using Newtonsoft.Json;
  6. using System;
  7. using System.Collections.Generic;
  8. using System.Configuration;
  9. using System.Data;
  10. using System.Diagnostics;
  11. using System.IO;
  12. using System.Linq;
  13. using System.Net;
  14. using System.Reflection;
  15. using System.Security.Cryptography.X509Certificates;
  16. namespace LisPacsDataUpload.business
  17. {
  18. /// <summary>
  19. /// pdf 工具类
  20. /// </summary>
  21. public class PdfUtils
  22. {
  23. /// <summary>
  24. /// 根据lis版本获取请求生成pdf报告的参数 0中联老版lis 1 中联新版lis 2 专业版临生免 10 标准服务老版lis 11标准服务新版lis 3 三方lis
  25. /// </summary>
  26. /// <returns></returns>
  27. public static string getPdfParamByLisVersion(int lisVersion, string reportNumber,string bbid,string yzid)
  28. {
  29. string dicLis = AppDomain.CurrentDomain.BaseDirectory + "Lis\\";
  30. if (!Directory.Exists(dicLis))
  31. {
  32. Directory.CreateDirectory(dicLis);
  33. }
  34. string path = dicLis + "LIS" + bbid+ ".pdf";
  35. Paramater paramter = new Paramater
  36. {
  37. RePortCode = reportNumber,
  38. PdfPath = $"pdf={path}",
  39. InvokeType = 4
  40. };
  41. if (lisVersion==0)
  42. {
  43. //老版lis
  44. /* Select Distinct 'ZLCISBILL' || Trim(To_Char(b.编号, '00000')) || '-2' 报表编号, a.相关id, d.id 标本id
  45. From 病人医嘱记录 A,检验标本记录 d, 病历文件列表 B, 病历单据应用 C
  46. Where a.诊疗项目id = c.诊疗项目id And a.病人来源 = c.应用场合 And c.病历文件id = b.Id And a.Id = :id and a.相关id = d.医嘱id*/
  47. paramter.ZlSysCode = 100;
  48. paramter.Params.Add(new SubParameter { Param = $"医嘱id={yzid}" });
  49. paramter.Params.Add(new SubParameter { Param = $"标本id={bbid}" });
  50. string strJson = JsonConvert.SerializeObject(paramter);
  51. LogHelper.Info("strJson==" + strJson);
  52. if (!Init())
  53. {
  54. LogHelper.Info("Init初始化异常");
  55. return "Init初始化异常";
  56. }
  57. //生成pdf成功
  58. if (OutPdf(strJson))
  59. {
  60. return path;
  61. }
  62. }
  63. else if (lisVersion == 1)
  64. {
  65. paramter.ZlSysCode = 2500;
  66. paramter.Params.Add(new SubParameter { Param = $"标本id={bbid}" });
  67. // 新版lis
  68. /* Select distinct 'ZLLISBILL00' || Decode(b.病人来源, 2, c.住院单据, 3, c.体检单据, 4, c.院外单据, c.门诊单据) || '-2' 报表编号, a.Id 标本id
  69. From 检验报告记录 A, 检验申请组合 B, 检验仪器记录 C
  70. Where a.Id = b.标本id And a.仪器id = c.Id And b.医嘱id = :id*/
  71. string strJson= JsonConvert.SerializeObject(paramter);
  72. LogHelper.Info("strJson=="+ strJson);
  73. if (!Init())
  74. {
  75. LogHelper.Info("Init初始化异常");
  76. return "Init初始化异常";
  77. }
  78. //生成pdf成功
  79. if (OutPdf(strJson))
  80. {
  81. return path;
  82. }
  83. }
  84. else if (lisVersion == 2)
  85. {
  86. //专业版临生免
  87. string sql_zlhr = @"select standard_url from 互认配置表";
  88. DataTable dt_lis = OracleHelper<object>.RunQueryDS(sql_zlhr);
  89. string standard_url = dt_lis.Rows[0]["standard_url"].ToString();
  90. 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}\"}}}";
  91. // 使用字符串插值替换占位符
  92. string data = jsonTemplate
  93. .Replace("{rpt_id}", bbid)
  94. .Replace("{time}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"))
  95. .Replace("{action_no}", Guid.NewGuid().ToString());
  96. string responseString = Tools.WSDataToZlsoftInterface(standard_url, data);
  97. ZlsoftOutVO zlsoftOutVO = JsonConvert.DeserializeObject<ZlsoftOutVO>(responseString);
  98. if (!"A".Equals(zlsoftOutVO.input.ack_info.exe_status))
  99. {
  100. return zlsoftOutVO.input.ack_info.err_msg;
  101. }
  102. return zlsoftOutVO.input.file_info.rpt_content;
  103. }
  104. else if(lisVersion == 3)
  105. {
  106. // 三方lis
  107. string three_sql = @"select pdfUrl from three_lis_pdf where yzid ='" + bbid+"'";
  108. LogHelper.Info("three_sql "+ three_sql);
  109. List<string> pdfs = SqlServerHelper.GetPdfUrlList(three_sql);
  110. if (pdfs != null && pdfs.Count()>0)
  111. {
  112. GetPdfFromJpgList(pdfs, path);
  113. return path;
  114. }
  115. return "三方lispdf报告获取失败";
  116. }
  117. else if (lisVersion == 10)
  118. {
  119. // 三方lis
  120. if (DownloadPdf2(reportNumber, path))
  121. {
  122. return path;
  123. };
  124. return "标准服务lispdf报告获取失败";
  125. }
  126. return "失败";
  127. }
  128. public static void GetPdfFromJpg(string jpgUrl,string pdfUrl)
  129. {
  130. LogHelper.Info("开始从jpg转换pdf");
  131. //string jpgFilePath = "path_to_your_jpg.jpg";
  132. //string pdfFilePath = "output.pdf";
  133. using (FileStream fs = new FileStream(pdfUrl, FileMode.Create))
  134. {
  135. // 创建一个文档对象
  136. Document document = new Document();
  137. // 创建一个 PDF 写入器,将文档写入文件流
  138. PdfWriter writer = PdfWriter.GetInstance(document, fs);
  139. document.Open();
  140. // 创建一个图像对象并加载 JPG 文件
  141. Image image = Image.GetInstance(jpgUrl);
  142. // 设置图像在 PDF 中的尺寸(可以根据需要调整)
  143. image.ScaleToFit(document.PageSize.Width - 20, document.PageSize.Height - 20);
  144. // 将图像添加到 PDF 文档中
  145. document.Add(image);
  146. document.Close();
  147. }
  148. LogHelper.Info("JPG 转换为 PDF 成功!");
  149. }
  150. public static void GetPdfFromJpgList(List<string> jpgUrls, string pdfUrl)
  151. {
  152. LogHelper.Info("开始从jpg列表转换pdf");
  153. using (FileStream fs = new FileStream(pdfUrl, FileMode.Create))
  154. {
  155. // 创建一个文档对象
  156. Document document = new Document();
  157. // 创建一个 PDF 写入器,将文档写入文件流
  158. PdfWriter writer = PdfWriter.GetInstance(document, fs);
  159. document.Open();
  160. foreach (string jpgUrl in jpgUrls)
  161. {
  162. try
  163. {
  164. LogHelper.Info("三方pdfUrl="+ jpgUrl);
  165. // 创建一个图像对象并加载 JPG 文件
  166. Image image = Image.GetInstance(jpgUrl);
  167. // 设置图像在 PDF 中的尺寸(可以根据需要调整)
  168. // 这里为了保持图片比例,我们先获取图片的原始尺寸
  169. float imgWidth = image.ScaledWidth;
  170. float imgHeight = image.ScaledHeight;
  171. // 根据需要调整图片大小,这里以A4纸大小减去边距为例
  172. float pdfWidth = document.PageSize.Width - 20;
  173. float pdfHeight = document.PageSize.Height - 20;
  174. // 根据宽度或高度调整图片大小,保持比例
  175. float scaleFactor = Math.Min(pdfWidth / imgWidth, pdfHeight / imgHeight);
  176. image.ScaleAbsolute(imgWidth * scaleFactor, imgHeight * scaleFactor);
  177. // 将图像添加到 PDF 文档中
  178. document.Add(image);
  179. // 添加一个空行以分隔图片(可选)
  180. document.Add(new Paragraph(string.Empty));
  181. document.NewPage(); // 如果需要在每张图片后添加新页,则使用此行
  182. }
  183. catch (Exception ex)
  184. {
  185. LogHelper.Error(ex ,"无法加载图片"+jpgUrl);
  186. }
  187. }
  188. document.Close();
  189. }
  190. LogHelper.Info("JPG 列表转换为 PDF 成功!");
  191. }
  192. public static string GeneratePdf(int lisVersion, string reportNumber, string bbid, string yzid)
  193. {
  194. string pdfUrl = getPdfParamByLisVersion(lisVersion, reportNumber, bbid, yzid);
  195. LogHelper.Info("GeneratePdf==");
  196. return pdfUrl;
  197. }
  198. private static bool AcceptAllCertificates(object sender, X509Certificate certificate, X509Chain chain,
  199. bool sslPolicyErrors)
  200. {
  201. return true;
  202. }
  203. public static bool DownloadPdf(string pdfUrl, string localFilePath)
  204. {
  205. // 忽略证书验证
  206. try
  207. {
  208. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(pdfUrl);
  209. HttpWebResponse response = (HttpWebResponse)request.GetResponse();
  210. if (response.StatusCode == HttpStatusCode.OK)
  211. {
  212. using (Stream responseStream = response.GetResponseStream())
  213. {
  214. using (FileStream fileStream = new FileStream(localFilePath, FileMode.Create))
  215. {
  216. byte[] buffer = new byte[1024*10];
  217. int bytesRead;
  218. while ((bytesRead = responseStream.Read(buffer, 0, buffer.Length)) > 0)
  219. {
  220. fileStream.Write(buffer, 0, bytesRead);
  221. }
  222. }
  223. }
  224. return true;
  225. }
  226. else
  227. {
  228. LogHelper.Info($"下载失败,状态码: {response.StatusCode}");
  229. return false;
  230. }
  231. }
  232. catch (Exception ex)
  233. {
  234. LogHelper.Info($"下载过程中出现错误: {ex.Message}");
  235. return false;
  236. }
  237. }
  238. public static bool DownloadPdf2(string pdfUrl, string localFilePath)
  239. {
  240. using (WebClient client = new WebClient())
  241. {
  242. try
  243. {
  244. client.DownloadFile(pdfUrl, localFilePath);
  245. LogHelper.Info("文件下载成功!");
  246. return true;
  247. }
  248. catch (Exception ex)
  249. {
  250. LogHelper.Info($"文件下载失败:{ex.Message}");
  251. return false;
  252. }
  253. }
  254. }
  255. static object Instance = null;
  256. public static bool Init()
  257. {
  258. if (Instance != null )
  259. {
  260. return true;
  261. }
  262. var para = JsonConvert.SerializeObject(new UserLogin
  263. {
  264. UserName = ConfigurationManager.AppSettings["UserName"],
  265. PassWord = ConfigurationManager.AppSettings["PasWord"],
  266. Server = ConfigurationManager.AppSettings["Server"]
  267. });
  268. LogHelper.Info("初始化入参" + para);
  269. string strReval = string.Empty;
  270. try
  271. {
  272. Process.GetProcessesByName("zlgyReport").ToList().ForEach(x => x.Kill());
  273. }
  274. catch (Exception ex) {
  275. LogHelper.Info("进程结束异常" + ex.Message); }
  276. var type = Type.GetTypeFromProgID("zlgyReport.clsGyReport");
  277. Instance = Activator.CreateInstance(type);
  278. ParameterModifier modifier = new ParameterModifier(2);
  279. modifier[1] = true;
  280. var result = type.InvokeMember("Init", BindingFlags.Default | BindingFlags.InvokeMethod, null, Instance, new object[] { para, strReval },
  281. new ParameterModifier[] { modifier },
  282. null,
  283. new string[] { "strJson", "strResult" });
  284. LogHelper.Info("出参:" + strReval);
  285. LogHelper.Info("返回:" + result.ToString());
  286. return (bool)result;
  287. }
  288. public static bool OutPdf(string para)
  289. {
  290. var type = Type.GetTypeFromProgID("zlgyReport.clsGyReport");
  291. ParameterModifier modifier = new ParameterModifier(2);
  292. modifier[1] = true;
  293. string strReval = string.Empty;
  294. var result = type.InvokeMember("ReportOpen", BindingFlags.Default | BindingFlags.InvokeMethod, null, Instance, new object[] { para, strReval },
  295. new ParameterModifier[] { modifier },
  296. null,
  297. new string[] { "strJson", "strResult" });
  298. LogHelper.Info("出参:" + strReval);
  299. LogHelper.Info("返回:" + result.ToString());
  300. return (bool)result;
  301. }
  302. public class UserLogin
  303. {
  304. public string UserName { get; set; }
  305. public string PassWord { get; set; }
  306. public string Server { get; set; }
  307. }
  308. }
  309. }