RequestHandler.cs 23 KB

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