RequestHandler.cs 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571
  1. using CefSharp;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Drawing;
  5. using System.Drawing.Drawing2D;
  6. using System.Linq;
  7. using System.Text.RegularExpressions;
  8. using System.Windows.Forms;
  9. using System.Drawing.Printing;
  10. using FastReport;
  11. using System.Data;
  12. using System.Threading;
  13. using System.Net;
  14. using System.Text;
  15. using System.Web;
  16. using System.Diagnostics;
  17. namespace UAS_Web.tool
  18. {
  19. class RequestHandler : IRequestHandler
  20. {
  21. public event Action<byte[]> NotifyMsg;
  22. //打印图片集合
  23. List<Bitmap> bitmaps = new List<Bitmap>();
  24. Report BarcodeReport = new Report();
  25. Report BoxReport = new Report();
  26. //图片打印中间变量
  27. int imagecount = 0;
  28. int index = 0;
  29. string PrinterName = "";
  30. string PrintType = "";
  31. PrinterList print;
  32. string LABELNAME = "";
  33. /// <summary>
  34. /// 拦截指定请求
  35. /// </summary>
  36. /// <param name="browserControl"></param>
  37. /// <param name="browser"></param>
  38. /// <param name="frame"></param>
  39. /// <param name="request"></param>
  40. /// <param name="response"></param>
  41. /// <returns></returns>
  42. IResponseFilter IRequestHandler.GetResourceResponseFilter(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, IResponse response)
  43. {
  44. MessageFilter filter;
  45. switch (request.Url.Substring(request.Url.LastIndexOf("/") + 1))
  46. {
  47. case "zplPrinter":
  48. filter = FilterManager.CreateFilter(request.Identifier.ToString()) as MessageFilter;
  49. return filter;
  50. case "zplPrint.action":
  51. filter = FilterManager.CreateFilter(request.Identifier.ToString()) as MessageFilter;
  52. return filter;
  53. case "getPrintType.action":
  54. filter = FilterManager.CreateFilter(request.Identifier.ToString()) as MessageFilter;
  55. return filter;
  56. case "vendorZplPrint.action":
  57. filter = FilterManager.CreateFilter(request.Identifier.ToString()) as MessageFilter;
  58. return filter;
  59. default:
  60. break;
  61. }
  62. return null;
  63. }
  64. /// <summary>
  65. /// 完成响应后获取Js返回的数据
  66. /// </summary>
  67. /// <param name="browserControl"></param>
  68. /// <param name="browser"></param>
  69. /// <param name="frame"></param>
  70. /// <param name="request"></param>
  71. /// <param name="response"></param>
  72. /// <param name="status"></param>
  73. /// <param name="receivedContentLength"></param>
  74. void IRequestHandler.OnResourceLoadComplete(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, IResponse response, UrlRequestStatus status, long receivedContentLength)
  75. {
  76. MessageFilter filter;
  77. string str;
  78. Dictionary<string, object> data;
  79. switch (request.Url.Substring(request.Url.LastIndexOf("/") + 1))
  80. {
  81. case "zplPrinter":
  82. var m = request.Method;
  83. if (request.Method == "POST")
  84. {
  85. using (var postData = request.PostData)
  86. {
  87. if (postData != null)
  88. {
  89. var elements = postData.Elements;
  90. var charSet = request.GetCharSet();
  91. foreach (var element in elements)
  92. {
  93. if (element.Type == PostDataElementType.Bytes)
  94. {
  95. string body = HttpUtility.UrlDecode(element.GetBody(charSet),Encoding.UTF8);
  96. LABELNAME = body.Substring(body.LastIndexOf('=')+1);
  97. }
  98. }
  99. }
  100. }
  101. }
  102. //弹出打印机选择列表
  103. print = new PrinterList(browser) { StartPosition = FormStartPosition.CenterScreen,TopMost=true };
  104. print.Controls["Confirm"].Click += RequestHandler_Click;
  105. print.PrintDoc.PrintPage += PrintPage;
  106. print.ShowDialog();
  107. break;
  108. case "zplPrint.action":
  109. filter = FilterManager.GetFileter(request.Identifier.ToString()) as MessageFilter;
  110. str = System.Text.Encoding.UTF8.GetString(filter.dataAll.ToArray());
  111. data = ToDictionary(str);
  112. //获取所有的打印格式数据
  113. if (data.ContainsKey("data"))
  114. {
  115. string PrintCode = data["data"].ToString().Replace(" ", "").Replace("\"", "");
  116. List<string> PrintList = new List<string>();
  117. int PrintTime = Regex.Matches(PrintCode, "XA").Count;
  118. for (int i = 0; i < PrintTime; i++)
  119. {
  120. PrintList.Add(PrintCode.Substring(0, PrintCode.IndexOf("XZ") + 2));
  121. PrintCode = PrintCode.Substring(PrintCode.IndexOf("XZ") + 2);
  122. }
  123. for (int i = 0; i < PrintList.Count; i++)
  124. {
  125. PrintHelper.SendStringToPrinter(PrinterName, PrintList[i]);
  126. }
  127. data.Clear();
  128. }
  129. else if (data.ContainsKey("exceptionInfo"))
  130. {
  131. //string PrintCode = data["exceptionInfo"].ToString();
  132. //MessageBox.Show(PrintCode);
  133. }
  134. break;
  135. case "getPrintType.action":
  136. filter = FilterManager.GetFileter(request.Identifier.ToString()) as MessageFilter;
  137. str = System.Text.Encoding.UTF8.GetString(filter.dataAll.ToArray());
  138. data = ToDictionary(str);
  139. PrintType = data["data"].ToString().Replace("\"", "");
  140. break;
  141. case "vendorZplPrint.action":
  142. try
  143. {
  144. filter = FilterManager.GetFileter(request.Identifier.ToString()) as MessageFilter;
  145. str = System.Text.Encoding.UTF8.GetString(filter.dataAll.ToArray());
  146. data = ToDictionary(str);
  147. vendorZplPrint(data);
  148. }
  149. catch (Exception ex)
  150. {
  151. MessageBox.Show(ex.Message + "请重新进行打印");
  152. return;
  153. }
  154. break;
  155. default:
  156. break;
  157. }
  158. }
  159. public void vendorZplPrint(Object data)
  160. {
  161. DataTable dt = new DataTable();
  162. RadioButton PRFR = (RadioButton)print.Controls["PRFR"];
  163. RadioButton PRPIC = (RadioButton)print.Controls["PRPIC"];
  164. string type;
  165. bitmaps.Clear();
  166. List<Dictionary<string, object>> parameter = new List<Dictionary<string, object>>();
  167. List<Dictionary<string, object>> barcode = new List<Dictionary<string, object>>();
  168. try
  169. {
  170. parameter = (List<Dictionary<string, object>>)((Dictionary<string, object>)data)["parameter"];
  171. barcode = (List<Dictionary<string, object>>)((Dictionary<string, object>)data)["barcode"];
  172. }
  173. catch {
  174. MessageBox.Show("打印数据解析异常,请联系管理员进行处理");
  175. return;
  176. }
  177. try
  178. {
  179. type = ((String)((Dictionary<string, object>)data)["type"]).Replace("\"", "");
  180. }
  181. catch
  182. {
  183. type = "no";
  184. }
  185. if (PRFR.Checked)
  186. {
  187. Thread.Sleep(1000);
  188. int i = 0;
  189. while (DownLoadFile.downloading && i < 2)
  190. {
  191. Thread.Sleep(1000);
  192. i++;
  193. }
  194. if (DownLoadFile.downloading)
  195. Console.WriteLine("标签更新有误");
  196. try
  197. {
  198. if (type == "box")
  199. {
  200. BoxReport.Load(System.AppDomain.CurrentDomain.BaseDirectory + LABELNAME + ".frx");
  201. }
  202. else {
  203. BarcodeReport.Load(System.AppDomain.CurrentDomain.BaseDirectory + LABELNAME + ".frx");
  204. }
  205. }
  206. catch
  207. {
  208. MessageBox.Show("未找到可使用的标签文件,请重试");
  209. return;
  210. }
  211. }
  212. int la_width = int.Parse(parameter.First()["LA_WIDTH"].ToString());
  213. int la_height = int.Parse(parameter.First()["LA_HEIGHT"].ToString());
  214. foreach (var item in barcode)
  215. {
  216. Bitmap bit = new Bitmap(la_width * 10, la_height * 4);
  217. using (Graphics g = Graphics.FromImage(bit))
  218. {
  219. //g.CompositingQuality = CompositingQuality.HighQuality;
  220. //g.SmoothingMode = SmoothingMode.HighQuality;
  221. //g.InterpolationMode = InterpolationMode.HighQualityBicubic;
  222. ////定义一枝画笔
  223. //Pen pen = new Pen(Color.Black);
  224. ////用这个画笔在左上角画一个矩形
  225. //g.DrawRectangle(pen, new Rectangle(10, 10, 50, 20));
  226. foreach (var itemc in item)
  227. {
  228. Dictionary<string, object> Sidc = parameter.Find(p => p["LP_NAME"].ToString().Replace(" ", "").Replace("\"", "").ToUpper() == itemc.Key.ToUpper());
  229. if (Sidc != null)
  230. {
  231. if (Sidc["LP_VALUETYPE"].ToString().Replace(" ", "").Replace("\"", "") == "text")
  232. {
  233. string itemstr = "";
  234. if (itemc.Value != null)
  235. {
  236. itemstr = itemc.Value.ToString();
  237. while (itemstr.StartsWith("\f") || itemstr.StartsWith("\v") || itemstr.StartsWith("\t") || itemstr.StartsWith("\r") || itemstr.StartsWith("\n"))
  238. {
  239. itemstr = itemstr.Remove(0, 2);
  240. }
  241. if (itemstr.StartsWith("\""))
  242. {
  243. itemstr = itemstr.Remove(0, 1);
  244. }
  245. while (itemstr.EndsWith("\f") || itemstr.EndsWith("\v") || itemstr.EndsWith("\t") || itemstr.EndsWith("\r") || itemstr.EndsWith("\n"))
  246. {
  247. itemstr = itemstr.Remove(itemstr.Length - 2);
  248. }
  249. if (itemstr.EndsWith("\""))
  250. {
  251. itemstr = itemstr.Remove(itemstr.Length - 1);
  252. }
  253. if (itemstr.Contains("\\\""))
  254. {
  255. itemstr = itemstr.Replace("\\\"", "\"");
  256. }
  257. }
  258. if (PRFR.Checked)
  259. {
  260. DataColumn DC = new DataColumn(itemc.Key, Type.GetType("System.String"));
  261. if (!dt.Columns.Contains(itemc.Key))
  262. dt.Columns.Add(DC);
  263. }
  264. if (PRPIC.Checked)
  265. {
  266. PrintHelper.Printstring(itemc.Value != null ? itemstr : " ", int.Parse(Sidc["LP_SIZE"].ToString()), g, int.Parse(Sidc["LP_LEFTRATE"].ToString()), int.Parse(Sidc["LP_TOPRATE"].ToString()));
  267. }
  268. }
  269. else if (Sidc["LP_VALUETYPE"].ToString().Replace(" ", "").Replace("\"", "") == "barcode")
  270. {
  271. if (PRFR.Checked)
  272. {
  273. DataColumn DC = new DataColumn(itemc.Key, Type.GetType("System.String"));
  274. if (!dt.Columns.Contains(itemc.Key))
  275. dt.Columns.Add(DC);
  276. }
  277. if (PRPIC.Checked)
  278. {
  279. PrintHelper.DrawBarcode(itemc.Value != null ? itemc.Value.ToString().Replace("\"", "") : " ", ref bit, double.Parse(Sidc["LP_LEFTRATE"].ToString()), double.Parse(Sidc["LP_TOPRATE"].ToString()), double.Parse(Sidc["LP_WIDTH"].ToString()), double.Parse(Sidc["LP_HEIGHT"].ToString()) - 2);
  280. PrintHelper.Printstring(itemc.Value != null ? itemc.Value.ToString().Replace("\"", "") : " ", int.Parse(Sidc["LP_SIZE"].ToString()), g, int.Parse(Sidc["LP_LEFTRATE"].ToString()), int.Parse(Sidc["LP_TOPRATE"].ToString()) + double.Parse(Sidc["LP_HEIGHT"].ToString()) - 2);
  281. }
  282. }
  283. }
  284. }
  285. }
  286. bitmaps.Add(bit);
  287. }
  288. if (PRFR.Checked)
  289. {
  290. foreach (var item in barcode)
  291. {
  292. DataRow dr = dt.NewRow();
  293. //g.CompositingQuality = CompositingQuality.HighQuality;
  294. //g.SmoothingMode = SmoothingMode.HighQuality;
  295. //g.InterpolationMode = InterpolationMode.HighQualityBicubic;
  296. ////定义一枝画笔
  297. //Pen pen = new Pen(Color.Black);
  298. ////用这个画笔在左上角画一个矩形
  299. //g.DrawRectangle(pen, new Rectangle(10, 10, 50, 20));
  300. foreach (var itemc in item)
  301. {
  302. Dictionary<string, object> Sidc = parameter.Find(p => p["LP_NAME"].ToString().Replace(" ", "").Replace("\"", "").ToUpper() == itemc.Key.ToUpper());
  303. if (Sidc != null)
  304. {
  305. if (Sidc["LP_VALUETYPE"].ToString().Replace(" ", "").Replace("\"", "") == "text")
  306. {
  307. string itemstr = "";
  308. if (itemc.Value != null)
  309. {
  310. itemstr = itemc.Value.ToString();
  311. while (itemstr.StartsWith("\f") || itemstr.StartsWith("\v") || itemstr.StartsWith("\t") || itemstr.StartsWith("\r") || itemstr.StartsWith("\n"))
  312. {
  313. itemstr = itemstr.Remove(0, 2);
  314. }
  315. if (itemstr.StartsWith("\""))
  316. {
  317. itemstr = itemstr.Remove(0, 1);
  318. }
  319. while (itemstr.EndsWith("\f") || itemstr.EndsWith("\v") || itemstr.EndsWith("\t") || itemstr.EndsWith("\r") || itemstr.EndsWith("\n"))
  320. {
  321. itemstr = itemstr.Remove(itemstr.Length - 2);
  322. }
  323. if (itemstr.EndsWith("\""))
  324. {
  325. itemstr = itemstr.Remove(itemstr.Length - 1);
  326. }
  327. if (itemstr.Contains("\\\""))
  328. {
  329. itemstr = itemstr.Replace("\\\"", "\"");
  330. Console.WriteLine(itemstr);
  331. }
  332. }
  333. dr[itemc.Key] = itemstr;
  334. }
  335. else if (Sidc["LP_VALUETYPE"].ToString().Replace(" ", "").Replace("\"", "") == "barcode")
  336. {
  337. dr[itemc.Key] = itemc.Value.ToString().Replace("\"", "");
  338. }
  339. }
  340. }
  341. dt.Rows.Add(dr);
  342. }
  343. }
  344. if (PRPIC.Checked)
  345. {
  346. if (bitmaps.Count > 0)
  347. {
  348. imagecount = bitmaps.Count;
  349. print.PrintDoc.Print();
  350. }
  351. }
  352. if (PRFR.Checked)
  353. {
  354. try
  355. {
  356. if (type == "box")
  357. {
  358. BoxReport.RegisterData(dt, "VENDORBARCODE_BOX_VIEW");
  359. BoxReport.GetDataSource("VENDORBARCODE_BOX_VIEW").Enabled = true;
  360. BoxReport.PrintSettings.ShowDialog = false;
  361. BoxReport.PrintSettings.Printer = PrinterName;
  362. BoxReport.Print();
  363. }
  364. else
  365. {
  366. BarcodeReport.RegisterData(dt, "VENDORBARCODE_VIEW");
  367. BarcodeReport.GetDataSource("VENDORBARCODE_VIEW").Enabled = true;
  368. BarcodeReport.PrintSettings.ShowDialog = false;
  369. BarcodeReport.PrintSettings.Printer = PrinterName;
  370. BarcodeReport.Print();
  371. }
  372. }
  373. catch(Exception ex)
  374. {
  375. MessageBox.Show(ex.Message+"打印出现错误,请检查标签文件选择是否正确");
  376. }
  377. dt.Clear();
  378. }
  379. }
  380. private void PrintPage(object sender, PrintPageEventArgs e)
  381. {
  382. Image i = bitmaps[index];
  383. Graphics g = e.Graphics;
  384. g.DrawImage(i, 4, 10, i.Width, i.Height);
  385. if (index < imagecount - 1)
  386. {
  387. e.HasMorePages = true;
  388. index++;
  389. }
  390. else
  391. {
  392. index = 0;
  393. e.HasMorePages = false;
  394. }
  395. }
  396. private void RequestHandler_Click(object sender, EventArgs e)
  397. {
  398. //设置打印机名称
  399. print.PrintDoc.PrinterSettings.PrinterName = print.Controls["Printer"].Text;
  400. PrinterName = print.Controls["Printer"].Text;
  401. RadioButton PRXA = (RadioButton)print.Controls["PRXA"];
  402. RadioButton PRPIC = (RadioButton)print.Controls["PRPIC"];
  403. //获取矩阵图的分辨率
  404. Graphics gr = print.PrintDoc.PrinterSettings.CreateMeasurementGraphics();
  405. print.browser.FocusedFrame.ExecuteJavaScriptAsync("(function(value,value1){dpi=value,printType=value1})('" + gr.DpiX + "','" + PrintType + "')");
  406. if (PRXA.Checked)
  407. {
  408. print.browser.FocusedFrame.ExecuteJavaScriptAsync("document.getElementById('confirmZplPrint').click();");
  409. }
  410. else
  411. {
  412. print.browser.FocusedFrame.ExecuteJavaScriptAsync("document.getElementById('confirmPicturePrint').click();");
  413. }
  414. print.Close();
  415. }
  416. void filter_NotifyData(byte[] data)
  417. {
  418. if (NotifyMsg != null)
  419. {
  420. NotifyMsg(data);
  421. }
  422. }
  423. public bool GetAuthCredentials(IWebBrowser browserControl, IBrowser browser, IFrame frame, bool isProxy, string host, int port, string realm, string scheme, IAuthCallback callback)
  424. {
  425. return false;
  426. }
  427. public bool OnBeforeBrowse(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, bool isRedirect)
  428. {
  429. return false;
  430. }
  431. public CefReturnValue OnBeforeResourceLoad(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, IRequestCallback callback)
  432. {
  433. return CefReturnValue.Continue;
  434. }
  435. public bool OnCertificateError(IWebBrowser browserControl, IBrowser browser, CefErrorCode errorCode, string requestUrl, ISslInfo sslInfo, IRequestCallback callback)
  436. {
  437. return false;
  438. }
  439. public bool OnOpenUrlFromTab(IWebBrowser browserControl, IBrowser browser, IFrame frame, string targetUrl, WindowOpenDisposition targetDisposition, bool userGesture)
  440. {
  441. return false;
  442. }
  443. public void OnPluginCrashed(IWebBrowser browserControl, IBrowser browser, string pluginPath)
  444. {
  445. }
  446. public bool OnProtocolExecution(IWebBrowser browserControl, IBrowser browser, string url)
  447. {
  448. return false;
  449. }
  450. public bool OnQuotaRequest(IWebBrowser browserControl, IBrowser browser, string originUrl, long newSize, IRequestCallback callback)
  451. {
  452. return false;
  453. }
  454. public void OnRenderProcessTerminated(IWebBrowser browserControl, IBrowser browser, CefTerminationStatus status)
  455. {
  456. }
  457. public void OnRenderViewReady(IWebBrowser browserControl, IBrowser browser)
  458. {
  459. }
  460. public void OnResourceLoadComplete(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, IResponse response, UrlRequestStatus status, long receivedContentLength)
  461. {
  462. }
  463. public void OnResourceRedirect(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, ref string newUrl)
  464. {
  465. }
  466. bool IRequestHandler.OnResourceResponse(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, IResponse response)
  467. {
  468. return false;
  469. }
  470. public void GetData()
  471. {
  472. }
  473. public static Dictionary<string, object> ToDictionary(string JsonData)
  474. {
  475. object Data = null;
  476. Dictionary<string, object> Dic = new Dictionary<string, object>();
  477. if (JsonData.StartsWith("["))
  478. {
  479. //如果目标直接就为数组类型,则将会直接输出一个Key为List的List<Dictionary<string, object>>集合
  480. //使用示例List<Dictionary<string, object>> ListDic = (List<Dictionary<string, object>>)Dic["List"];
  481. List<Dictionary<string, object>> List = new List<Dictionary<string, object>>();
  482. MatchCollection ListMatch = Regex.Matches(JsonData, @"{[\s\S]+?}");//使用正则表达式匹配出JSON数组
  483. foreach (Match ListItem in ListMatch)
  484. {
  485. List.Add(ToDictionary(ListItem.ToString()));//递归调用
  486. }
  487. Data = List;
  488. Dic.Add("List", Data);
  489. }
  490. else
  491. {
  492. MatchCollection Match = Regex.Matches(JsonData, @"""(.+?)"": {0,1}(\[[\s\S]+?\}\s*\]|null|"".+?""(,+?)|"".+?""(\s*?)(\}+?)|-{0,1}\d*)");//使用正则表达式匹配出JSON数据中的键与值
  493. foreach (Match item in Match)
  494. {
  495. try
  496. {
  497. if (item.Groups[2].ToString().StartsWith("["))
  498. {
  499. //如果目标是数组,将会输出一个Key为当前Json的List<Dictionary<string, object>>集合
  500. //使用示例List<Dictionary<string, object>> ListDic = (List<Dictionary<string, object>>)Dic["Json中的Key"];
  501. List<Dictionary<string, object>> List = new List<Dictionary<string, object>>();
  502. MatchCollection ListMatch = Regex.Matches(item.Groups[2].ToString(), @"{[\s\S]+?}");//使用正则表达式匹配出JSON数组
  503. foreach (Match ListItem in ListMatch)
  504. {
  505. List.Add(ToDictionary(ListItem.ToString()));//递归调用
  506. }
  507. Data = List;
  508. }
  509. else if (item.Groups[2].ToString().ToLower() == "null") Data = null;//如果数据为null(字符串类型),直接转换成null
  510. else if (item.Groups[2].ToString().EndsWith(","))
  511. Data = item.Groups[2].ToString().Remove(item.Groups[2].ToString().Length - 1); //数据为数字、字符串中的一类,则去掉,直接写入
  512. else if (item.Groups[2].ToString().EndsWith("}"))
  513. Data = item.Groups[2].ToString().Remove(item.Groups[2].ToString().Length - 1); //数据为数字、字符串中的一类,则去掉,直接写入
  514. else
  515. Data = item.Groups[2].ToString();
  516. Dic.Add(item.Groups[1].ToString(), Data);
  517. }
  518. catch { }
  519. }
  520. }
  521. return Dic;
  522. }
  523. }
  524. }