RequestHandler.cs 24 KB

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