PrintHelper.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Drawing;
  4. using System.Drawing.Drawing2D;
  5. using System.Drawing.Text;
  6. using System.IO;
  7. using System.Linq;
  8. using System.Runtime.InteropServices;
  9. using System.Text;
  10. using System.Text.RegularExpressions;
  11. namespace UAS_PRINT
  12. {
  13. class PrintHelper
  14. {
  15. // 结构和API declarions
  16. [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
  17. public class DOCINFOA
  18. {
  19. [MarshalAs(UnmanagedType.LPStr)]
  20. public string pDocName;
  21. [MarshalAs(UnmanagedType.LPStr)]
  22. public string pOutputFile;
  23. [MarshalAs(UnmanagedType.LPStr)]
  24. public string pDataType;
  25. }
  26. [DllImport("winspool.Drv", EntryPoint = "OpenPrinterA", SetLastError = true, CharSet = CharSet.Ansi, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
  27. public static extern bool OpenPrinter([MarshalAs(UnmanagedType.LPStr)] string szPrinter, out IntPtr hPrinter, IntPtr pd);
  28. [DllImport("winspool.Drv", EntryPoint = "ClosePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
  29. public static extern bool ClosePrinter(IntPtr hPrinter);
  30. [DllImport("winspool.Drv", EntryPoint = "StartDocPrinterA", SetLastError = true, CharSet = CharSet.Ansi, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
  31. public static extern bool StartDocPrinter(IntPtr hPrinter, Int32 level, [In, MarshalAs(UnmanagedType.LPStruct)] DOCINFOA di);
  32. [DllImport("winspool.Drv", EntryPoint = "EndDocPrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
  33. public static extern bool EndDocPrinter(IntPtr hPrinter);
  34. [DllImport("winspool.Drv", EntryPoint = "StartPagePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
  35. public static extern bool StartPagePrinter(IntPtr hPrinter);
  36. [DllImport("winspool.Drv", EntryPoint = "EndPagePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
  37. public static extern bool EndPagePrinter(IntPtr hPrinter);
  38. [DllImport("winspool.Drv", EntryPoint = "WritePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
  39. public static extern bool WritePrinter(IntPtr hPrinter, IntPtr pBytes, Int32 dwCount, out Int32 dwWritten);
  40. // SendBytesToPrinter()
  41. //当函数是给定一个打印机名称和一个非托管数组
  42. // 如果执行成功,将返回true;如果执行失败将返回false
  43. public static bool SendBytesToPrinter(string szPrinterName, IntPtr pBytes, Int32 dwCount)
  44. {
  45. Int32 dwError = 0, dwWritten = 0;
  46. IntPtr hPrinter = new IntPtr(0);
  47. DOCINFOA di = new DOCINFOA();
  48. bool bSuccess = false; // 假设失败.
  49. di.pDocName = "My C#.NET RAW Document";
  50. di.pDataType = "RAW";
  51. // 打开打印机
  52. if (OpenPrinter(szPrinterName.Normalize(), out hPrinter, IntPtr.Zero))
  53. {
  54. // 开始一个文档.
  55. if (StartDocPrinter(hPrinter, 1, di))
  56. {
  57. // 创建新页面
  58. if (StartPagePrinter(hPrinter))
  59. {
  60. // 写你的字节
  61. bSuccess = WritePrinter(hPrinter, pBytes, dwCount, out dwWritten);
  62. EndPagePrinter(hPrinter);
  63. }
  64. EndDocPrinter(hPrinter);
  65. }
  66. ClosePrinter(hPrinter);
  67. }
  68. // 如果没有成功,可能会给更多的信息GetLastError
  69. if (bSuccess == false)
  70. {
  71. dwError = Marshal.GetLastWin32Error();
  72. }
  73. return bSuccess;
  74. }
  75. public static bool SendFileToPrinter(string szPrinterName, string szFileName)
  76. {
  77. // 打开文件.
  78. FileStream fs = new FileStream(szFileName, FileMode.Open);
  79. // 创建一个主题的文件.
  80. BinaryReader br = new BinaryReader(fs);
  81. // .
  82. Byte[] bytes = new Byte[fs.Length];
  83. bool bSuccess = false;
  84. // 非托管指针
  85. IntPtr pUnmanagedBytes = new IntPtr(0);
  86. int nLength;
  87. nLength = Convert.ToInt32(fs.Length);
  88. // 读取文件的内容放入数组中.
  89. bytes = br.ReadBytes(nLength);
  90. // 分配一些非托管内存对于那些字节
  91. pUnmanagedBytes = Marshal.AllocCoTaskMem(nLength);
  92. // 复制管理到非托管数组的字节数组
  93. Marshal.Copy(bytes, 0, pUnmanagedBytes, nLength);
  94. // 发送到打印机的非托管的字节
  95. bSuccess = SendBytesToPrinter(szPrinterName, pUnmanagedBytes, nLength);
  96. // 非托管内存分配
  97. Marshal.FreeCoTaskMem(pUnmanagedBytes);
  98. return bSuccess;
  99. }
  100. public static bool SendStringToPrinter(string szPrinterName, string szString)
  101. {
  102. IntPtr pBytes;
  103. Int32 dwCount;
  104. // 有多少字符在字符串
  105. dwCount = szString.Length;
  106. // 假设打印机期待ANSI的文本,然后将字符串ANSI文本。
  107. pBytes = Marshal.StringToCoTaskMemAnsi(szString);
  108. // 转换后的字符串发送到打印机的ANSI
  109. SendBytesToPrinter(szPrinterName, pBytes, dwCount);
  110. Marshal.FreeCoTaskMem(pBytes);
  111. return true;
  112. }
  113. //图片添加文字
  114. public static void Printstring(string str, int size, Graphics g, double x, double y)
  115. {
  116. //g.SmoothingMode = SmoothingMode.AntiAlias; //使绘图质量最高,即消除锯齿
  117. //g.InterpolationMode = InterpolationMode.HighQualityBilinear;
  118. //g.CompositingQuality = CompositingQuality.HighQuality;
  119. g.CompositingQuality = CompositingQuality.HighQuality;
  120. g.SmoothingMode = SmoothingMode.AntiAlias;
  121. g.InterpolationMode = InterpolationMode.HighQualityBicubic;
  122. g.TextRenderingHint = TextRenderingHint.SingleBitPerPixelGridFit;
  123. g.PixelOffsetMode = PixelOffsetMode.Half;
  124. //Font font = new Font(new FontFamily("宋体"), (float)(siez*1.3), FontStyle.Regular);
  125. Font font = new Font(new FontFamily("微软雅黑"), (float)(size*1.2), FontStyle.Regular, GraphicsUnit.Point);
  126. g.DrawString(str, font, Brushes.Black, new PointF((float)x * 4, (float)y * 4));
  127. }
  128. //图片添加条码
  129. public static void DrawBarcode(string str, ref Bitmap bitmap, double x, double y, double width, double height)
  130. {
  131. Code128 co128 = new Code128();
  132. Image imgTemp = co128.EncodeBarcode(str, 400, (int)height * 4, false);
  133. bitmap = (Bitmap)CombinImage(bitmap, imgTemp, (float)x, (float)y);
  134. }
  135. /// <summary>
  136. /// 调用此函数后使此两种图片合并,类似相册,有个
  137. /// 背景图,中间贴自己的目标图片
  138. /// </summary>
  139. /// <param name="imgBack">粘贴的源图片</param>
  140. /// <param name="img">粘贴的目标图片</param>
  141. public static Image CombinImage(Image imgBack, Image img, float x, float y)
  142. { //照片图片
  143. //从指定的System.Drawing.Image创建新的System.Drawing.Graphics
  144. Graphics g = Graphics.FromImage(imgBack);
  145. g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
  146. g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
  147. g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.NearestNeighbor;
  148. g.PixelOffsetMode = PixelOffsetMode.Half;
  149. //g.DrawImage(imgBack, 0, 0, 148, 124); // g.DrawImage(imgBack, 0, 0, 相框宽, 相框高);
  150. //g.FillRectangle(System.Drawing.Brushes.Black, -50, -50, (int)212, ((int)203));//相片四周刷一层黑色边框,这里没有,需要调尺寸
  151. //g.DrawImage(img, 照片与相框的左边距, 照片与相框的上边距, 照片宽, 照片高);
  152. g.DrawImage(img,5, y * 4, img.Width, img.Height);
  153. g.Save();
  154. g.Dispose();
  155. return imgBack;
  156. }
  157. public static Dictionary<string, object> ToDictionary(string JsonData)
  158. {
  159. object Data = null;
  160. Dictionary<string, object> Dic = new Dictionary<string, object>();
  161. if (JsonData.StartsWith("["))
  162. {
  163. //如果目标直接就为数组类型,则将会直接输出一个Key为List的List<Dictionary<string, object>>集合
  164. //使用示例List<Dictionary<string, object>> ListDic = (List<Dictionary<string, object>>)Dic["List"];
  165. List<Dictionary<string, object>> List = new List<Dictionary<string, object>>();
  166. MatchCollection ListMatch = Regex.Matches(JsonData, @"{[\s\S]+?}");//使用正则表达式匹配出JSON数组
  167. foreach (Match ListItem in ListMatch)
  168. {
  169. List.Add(ToDictionary(ListItem.ToString()));//递归调用
  170. }
  171. Data = List;
  172. Dic.Add("List", Data);
  173. }
  174. else
  175. {
  176. MatchCollection Match = Regex.Matches(JsonData, @"""(.+?)"": {0,1}(\[[\s\S]+?\}\s*\]|null|"".+?""(,+?)|"".+?""(\s*?)(\}+?)|-{0,1}\d*)");//使用正则表达式匹配出JSON数据中的键与值
  177. foreach (Match item in Match)
  178. {
  179. try
  180. {
  181. if (item.Groups[2].ToString().StartsWith("["))
  182. {
  183. //如果目标是数组,将会输出一个Key为当前Json的List<Dictionary<string, object>>集合
  184. //使用示例List<Dictionary<string, object>> ListDic = (List<Dictionary<string, object>>)Dic["Json中的Key"];
  185. List<Dictionary<string, object>> List = new List<Dictionary<string, object>>();
  186. MatchCollection ListMatch = Regex.Matches(item.Groups[2].ToString(), @"{[\s\S]+?}");//使用正则表达式匹配出JSON数组
  187. foreach (Match ListItem in ListMatch)
  188. {
  189. List.Add(ToDictionary(ListItem.ToString()));//递归调用
  190. }
  191. Data = List;
  192. }
  193. else if (item.Groups[2].ToString().ToLower() == "null") Data = null;//如果数据为null(字符串类型),直接转换成null
  194. else if (item.Groups[2].ToString().EndsWith(","))
  195. Data = item.Groups[2].ToString().Remove(item.Groups[2].ToString().Length - 1); //数据为数字、字符串中的一类,则去掉,直接写入
  196. else if (item.Groups[2].ToString().EndsWith("}"))
  197. Data = item.Groups[2].ToString().Remove(item.Groups[2].ToString().Length - 1); //数据为数字、字符串中的一类,则去掉,直接写入
  198. else
  199. Data = item.Groups[2].ToString();
  200. Dic.Add(item.Groups[1].ToString(), Data);
  201. }
  202. catch { }
  203. }
  204. }
  205. return Dic;
  206. }
  207. }
  208. }