PdfUtils.cs 15 KB

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