RequestHandler.cs 25 KB

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