RequestHandler.cs 24 KB

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