RequestHandler.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  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. namespace UAS_Web.tool
  11. {
  12. class RequestHandler : IRequestHandler
  13. {
  14. public event Action<byte[]> NotifyMsg;
  15. //打印图片集合
  16. List<Bitmap> bitmaps = new List<Bitmap>();
  17. //图片打印中间变量
  18. int imagecount = 0;
  19. int index = 0;
  20. string PrinterName = "";
  21. string PrintType = "";
  22. PrinterList print;
  23. /// <summary>
  24. /// 拦截指定请求
  25. /// </summary>
  26. /// <param name="browserControl"></param>
  27. /// <param name="browser"></param>
  28. /// <param name="frame"></param>
  29. /// <param name="request"></param>
  30. /// <param name="response"></param>
  31. /// <returns></returns>
  32. IResponseFilter IRequestHandler.GetResourceResponseFilter(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, IResponse response)
  33. {
  34. MessageFilter filter;
  35. switch (request.Url.Substring(request.Url.LastIndexOf("/") + 1))
  36. {
  37. case "zplPrinter":
  38. filter = FilterManager.CreateFilter(request.Identifier.ToString()) as MessageFilter;
  39. return filter;
  40. case "zplPrint.action":
  41. filter = FilterManager.CreateFilter(request.Identifier.ToString()) as MessageFilter;
  42. return filter;
  43. case "getPrintType.action":
  44. filter = FilterManager.CreateFilter(request.Identifier.ToString()) as MessageFilter;
  45. return filter;
  46. case "vendorZplPrint.action":
  47. filter = FilterManager.CreateFilter(request.Identifier.ToString()) as MessageFilter;
  48. return filter;
  49. default:
  50. break;
  51. }
  52. return null;
  53. }
  54. /// <summary>
  55. /// 完成响应后获取Js返回的数据
  56. /// </summary>
  57. /// <param name="browserControl"></param>
  58. /// <param name="browser"></param>
  59. /// <param name="frame"></param>
  60. /// <param name="request"></param>
  61. /// <param name="response"></param>
  62. /// <param name="status"></param>
  63. /// <param name="receivedContentLength"></param>
  64. void IRequestHandler.OnResourceLoadComplete(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, IResponse response, UrlRequestStatus status, long receivedContentLength)
  65. {
  66. MessageFilter filter;
  67. string str;
  68. Dictionary<string, object> data;
  69. switch (request.Url.Substring(request.Url.LastIndexOf("/") + 1))
  70. {
  71. case "zplPrinter":
  72. //弹出打印机选择列表
  73. print = new PrinterList(browser) { StartPosition = FormStartPosition.CenterScreen,TopMost=true };
  74. print.Controls["Confirm"].Click += RequestHandler_Click;
  75. print.ShowDialog();
  76. break;
  77. case "zplPrint.action":
  78. filter = FilterManager.GetFileter(request.Identifier.ToString()) as MessageFilter;
  79. str = System.Text.Encoding.UTF8.GetString(filter.dataAll.ToArray());
  80. data = ToDictionary(str);
  81. //获取所有的打印格式数据
  82. if (data.ContainsKey("data"))
  83. {
  84. string PrintCode = data["data"].ToString().Replace(" ", "").Replace("\"", "");
  85. List<string> PrintList = new List<string>();
  86. int PrintTime = Regex.Matches(PrintCode, "XA").Count;
  87. for (int i = 0; i < PrintTime; i++)
  88. {
  89. PrintList.Add(PrintCode.Substring(0, PrintCode.IndexOf("XZ") + 2));
  90. PrintCode = PrintCode.Substring(PrintCode.IndexOf("XZ") + 2);
  91. }
  92. for (int i = 0; i < PrintList.Count; i++)
  93. {
  94. PrintHelper.SendStringToPrinter(PrinterName, PrintList[i]);
  95. }
  96. data.Clear();
  97. }
  98. else if (data.ContainsKey("exceptionInfo"))
  99. {
  100. //string PrintCode = data["exceptionInfo"].ToString();
  101. //MessageBox.Show(PrintCode);
  102. }
  103. break;
  104. case "getPrintType.action":
  105. filter = FilterManager.GetFileter(request.Identifier.ToString()) as MessageFilter;
  106. str = System.Text.Encoding.UTF8.GetString(filter.dataAll.ToArray());
  107. data = ToDictionary(str);
  108. PrintType = data["data"].ToString().Replace("\"", "");
  109. break;
  110. case "vendorZplPrint.action":
  111. filter = FilterManager.GetFileter(request.Identifier.ToString()) as MessageFilter;
  112. str = System.Text.Encoding.UTF8.GetString(filter.dataAll.ToArray());
  113. data = ToDictionary(str);
  114. List<Dictionary<string, object>> parameter = new List<Dictionary<string, object>>();
  115. List<Dictionary<string, object>> barcode = new List<Dictionary<string, object>>();
  116. parameter = (List<Dictionary<string, object>>)data["parameter"];
  117. barcode = (List<Dictionary<string, object>>)data["barcode"];
  118. int la_width = int.Parse(parameter.First()["LA_WIDTH"].ToString());
  119. int la_height = int.Parse(parameter.First()["LA_HEIGHT"].ToString());
  120. foreach (var item in barcode)
  121. {
  122. Bitmap bit = new Bitmap(la_width * 6, la_height * 4);
  123. using (Graphics g = Graphics.FromImage(bit))
  124. {
  125. //g.CompositingQuality = CompositingQuality.HighQuality;
  126. //g.SmoothingMode = SmoothingMode.HighQuality;
  127. //g.InterpolationMode = InterpolationMode.HighQualityBicubic;
  128. ////定义一枝画笔
  129. //Pen pen = new Pen(Color.Black);
  130. ////用这个画笔在左上角画一个矩形
  131. //g.DrawRectangle(pen, new Rectangle(10, 10, 50, 20));
  132. foreach (var itemc in item)
  133. {
  134. Dictionary<string, object> Sidc = parameter.Find(p => p["LP_NAME"].ToString().Replace(" ", "").Replace("\"", "").ToUpper() == itemc.Key.ToUpper());
  135. if (Sidc["LP_VALUETYPE"].ToString().Replace(" ", "").Replace("\"", "") == "text")
  136. {
  137. string itemstr = "";
  138. if (itemc.Value != null)
  139. {
  140. itemstr = itemc.Value.ToString();
  141. while (itemstr.StartsWith("\f") || itemstr.StartsWith("\v") || itemstr.StartsWith("\t") || itemstr.StartsWith("\r") || itemstr.StartsWith("\n"))
  142. {
  143. itemstr = itemstr.Remove(0, 2);
  144. }
  145. if (itemstr.StartsWith("\""))
  146. {
  147. itemstr = itemstr.Remove(0, 1);
  148. }
  149. while (itemstr.EndsWith("\f") || itemstr.EndsWith("\v") || itemstr.EndsWith("\t") || itemstr.EndsWith("\r") || itemstr.EndsWith("\n"))
  150. {
  151. itemstr = itemstr.Remove(itemstr.Length - 2);
  152. }
  153. if (itemstr.EndsWith("\""))
  154. {
  155. itemstr = itemstr.Remove(itemstr.Length - 1);
  156. }
  157. if (itemstr.Contains("\\\""))
  158. {
  159. itemstr = itemstr.Replace("\\\"", "\"");
  160. Console.WriteLine(itemstr);
  161. }
  162. }
  163. 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()));
  164. }
  165. else if (Sidc["LP_VALUETYPE"].ToString().Replace(" ", "").Replace("\"", "") == "barcode")
  166. {
  167. 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);
  168. 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);
  169. }
  170. }
  171. }
  172. bitmaps.Add(bit);
  173. }
  174. imagecount = bitmaps.Count;
  175. ////设置打印机名称
  176. print.PrintDoc.PrintPage += PrintPage;
  177. print.PrintDoc.Print();
  178. break;
  179. default:
  180. break;
  181. }
  182. }
  183. private void PrintPage(object sender, PrintPageEventArgs e)
  184. {
  185. Image i = bitmaps[index];
  186. Graphics g = e.Graphics;
  187. g.CompositingQuality = CompositingQuality.HighQuality;
  188. g.SmoothingMode = SmoothingMode.HighQuality;
  189. g.InterpolationMode = InterpolationMode.NearestNeighbor;
  190. g.PixelOffsetMode = PixelOffsetMode.Half;
  191. g.ScaleTransform(0.7F, 1F);
  192. g.DrawImage(i, 0, -5, i.Width, i.Height);
  193. if (index < imagecount - 1)
  194. {
  195. e.HasMorePages = true;
  196. index++;
  197. }
  198. else
  199. {
  200. index = 0;
  201. e.HasMorePages = false;
  202. bitmaps.Clear();
  203. }
  204. }
  205. private void RequestHandler_Click(object sender, EventArgs e)
  206. {
  207. //设置打印机名称
  208. print.PrintDoc.PrinterSettings.PrinterName = print.Controls["Printer"].Text;
  209. PrinterName = print.Controls["Printer"].Text;
  210. RadioButton PRXA = (RadioButton)print.Controls["PRXA"];
  211. RadioButton PRPIC = (RadioButton)print.Controls["PRPIC"];
  212. //获取矩阵图的分辨率
  213. Graphics gr = print.PrintDoc.PrinterSettings.CreateMeasurementGraphics();
  214. print.browser.FocusedFrame.ExecuteJavaScriptAsync("(function(value,value1){dpi=value,printType=value1})('" + gr.DpiX + "','" + PrintType + "')");
  215. if (PRPIC.Checked) {
  216. print.browser.FocusedFrame.ExecuteJavaScriptAsync("document.getElementById('confirmPicturePrint').click();");
  217. }
  218. else
  219. print.browser.FocusedFrame.ExecuteJavaScriptAsync("document.getElementById('confirmZplPrint').click();");
  220. print.Close();
  221. }
  222. void filter_NotifyData(byte[] data)
  223. {
  224. if (NotifyMsg != null)
  225. {
  226. NotifyMsg(data);
  227. }
  228. }
  229. public bool GetAuthCredentials(IWebBrowser browserControl, IBrowser browser, IFrame frame, bool isProxy, string host, int port, string realm, string scheme, IAuthCallback callback)
  230. {
  231. return false;
  232. }
  233. public bool OnBeforeBrowse(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, bool isRedirect)
  234. {
  235. return false;
  236. }
  237. public CefReturnValue OnBeforeResourceLoad(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, IRequestCallback callback)
  238. {
  239. return CefReturnValue.Continue;
  240. }
  241. public bool OnCertificateError(IWebBrowser browserControl, IBrowser browser, CefErrorCode errorCode, string requestUrl, ISslInfo sslInfo, IRequestCallback callback)
  242. {
  243. return false;
  244. }
  245. public bool OnOpenUrlFromTab(IWebBrowser browserControl, IBrowser browser, IFrame frame, string targetUrl, WindowOpenDisposition targetDisposition, bool userGesture)
  246. {
  247. return false;
  248. }
  249. public void OnPluginCrashed(IWebBrowser browserControl, IBrowser browser, string pluginPath)
  250. {
  251. }
  252. public bool OnProtocolExecution(IWebBrowser browserControl, IBrowser browser, string url)
  253. {
  254. return false;
  255. }
  256. public bool OnQuotaRequest(IWebBrowser browserControl, IBrowser browser, string originUrl, long newSize, IRequestCallback callback)
  257. {
  258. return false;
  259. }
  260. public void OnRenderProcessTerminated(IWebBrowser browserControl, IBrowser browser, CefTerminationStatus status)
  261. {
  262. }
  263. public void OnRenderViewReady(IWebBrowser browserControl, IBrowser browser)
  264. {
  265. }
  266. public void OnResourceLoadComplete(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, IResponse response, UrlRequestStatus status, long receivedContentLength)
  267. {
  268. }
  269. public void OnResourceRedirect(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, ref string newUrl)
  270. {
  271. }
  272. bool IRequestHandler.OnResourceResponse(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, IResponse response)
  273. {
  274. return false;
  275. }
  276. public void GetData()
  277. {
  278. }
  279. public static Dictionary<string, object> ToDictionary(string JsonData)
  280. {
  281. object Data = null;
  282. Dictionary<string, object> Dic = new Dictionary<string, object>();
  283. if (JsonData.StartsWith("["))
  284. {
  285. //如果目标直接就为数组类型,则将会直接输出一个Key为List的List<Dictionary<string, object>>集合
  286. //使用示例List<Dictionary<string, object>> ListDic = (List<Dictionary<string, object>>)Dic["List"];
  287. List<Dictionary<string, object>> List = new List<Dictionary<string, object>>();
  288. MatchCollection ListMatch = Regex.Matches(JsonData, @"{[\s\S]+?}");//使用正则表达式匹配出JSON数组
  289. foreach (Match ListItem in ListMatch)
  290. {
  291. List.Add(ToDictionary(ListItem.ToString()));//递归调用
  292. }
  293. Data = List;
  294. Dic.Add("List", Data);
  295. }
  296. else
  297. {
  298. MatchCollection Match = Regex.Matches(JsonData, @"""(.+?)"": {0,1}(\[[\s\S]+?\}\s*\]|null|"".+?""(,+?)|"".+?""(\s*?)(\}+?)|-{0,1}\d*)");//使用正则表达式匹配出JSON数据中的键与值
  299. foreach (Match item in Match)
  300. {
  301. try
  302. {
  303. if (item.Groups[2].ToString().StartsWith("["))
  304. {
  305. //如果目标是数组,将会输出一个Key为当前Json的List<Dictionary<string, object>>集合
  306. //使用示例List<Dictionary<string, object>> ListDic = (List<Dictionary<string, object>>)Dic["Json中的Key"];
  307. List<Dictionary<string, object>> List = new List<Dictionary<string, object>>();
  308. MatchCollection ListMatch = Regex.Matches(item.Groups[2].ToString(), @"{[\s\S]+?}");//使用正则表达式匹配出JSON数组
  309. foreach (Match ListItem in ListMatch)
  310. {
  311. List.Add(ToDictionary(ListItem.ToString()));//递归调用
  312. }
  313. Data = List;
  314. }
  315. else if (item.Groups[2].ToString().ToLower() == "null") Data = null;//如果数据为null(字符串类型),直接转换成null
  316. else if (item.Groups[2].ToString().EndsWith(","))
  317. Data = item.Groups[2].ToString().Remove(item.Groups[2].ToString().Length - 1); //数据为数字、字符串中的一类,则去掉,直接写入
  318. else if (item.Groups[2].ToString().EndsWith("}"))
  319. Data = item.Groups[2].ToString().Remove(item.Groups[2].ToString().Length - 1); //数据为数字、字符串中的一类,则去掉,直接写入
  320. else
  321. Data = item.Groups[2].ToString();
  322. Dic.Add(item.Groups[1].ToString(), Data);
  323. }
  324. catch { }
  325. }
  326. }
  327. return Dic;
  328. }
  329. }
  330. }