PrintHelper.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  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. /// <summary>
  129. /// 调用此函数后使此两种图片合并,类似相册,有个
  130. /// 背景图,中间贴自己的目标图片
  131. /// </summary>
  132. /// <param name="imgBack">粘贴的源图片</param>
  133. /// <param name="img">粘贴的目标图片</param>
  134. public static Image CombinImage(Image imgBack, Image img, float x, float y)
  135. { //照片图片
  136. //从指定的System.Drawing.Image创建新的System.Drawing.Graphics
  137. Graphics g = Graphics.FromImage(imgBack);
  138. g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
  139. g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
  140. g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.NearestNeighbor;
  141. g.PixelOffsetMode = PixelOffsetMode.Half;
  142. //g.DrawImage(imgBack, 0, 0, 148, 124); // g.DrawImage(imgBack, 0, 0, 相框宽, 相框高);
  143. //g.FillRectangle(System.Drawing.Brushes.Black, -50, -50, (int)212, ((int)203));//相片四周刷一层黑色边框,这里没有,需要调尺寸
  144. //g.DrawImage(img, 照片与相框的左边距, 照片与相框的上边距, 照片宽, 照片高);
  145. g.DrawImage(img,5, y * 4, img.Width, img.Height);
  146. g.Save();
  147. g.Dispose();
  148. return imgBack;
  149. }
  150. public static Dictionary<string, object> ToDictionary(string JsonData)
  151. {
  152. object Data = null;
  153. Dictionary<string, object> Dic = new Dictionary<string, object>();
  154. if (JsonData.StartsWith("["))
  155. {
  156. //如果目标直接就为数组类型,则将会直接输出一个Key为List的List<Dictionary<string, object>>集合
  157. //使用示例List<Dictionary<string, object>> ListDic = (List<Dictionary<string, object>>)Dic["List"];
  158. List<Dictionary<string, object>> List = new List<Dictionary<string, object>>();
  159. MatchCollection ListMatch = Regex.Matches(JsonData, @"{[\s\S]+?}");//使用正则表达式匹配出JSON数组
  160. foreach (Match ListItem in ListMatch)
  161. {
  162. List.Add(ToDictionary(ListItem.ToString()));//递归调用
  163. }
  164. Data = List;
  165. Dic.Add("List", Data);
  166. }
  167. else
  168. {
  169. MatchCollection Match = Regex.Matches(JsonData, @"""(.+?)"": {0,1}(\[[\s\S]+?\}\s*\]|null|"".+?""(,+?)|"".+?""(\s*?)(\}+?)|-{0,1}\d*)");//使用正则表达式匹配出JSON数据中的键与值
  170. foreach (Match item in Match)
  171. {
  172. try
  173. {
  174. if (item.Groups[2].ToString().StartsWith("["))
  175. {
  176. //如果目标是数组,将会输出一个Key为当前Json的List<Dictionary<string, object>>集合
  177. //使用示例List<Dictionary<string, object>> ListDic = (List<Dictionary<string, object>>)Dic["Json中的Key"];
  178. List<Dictionary<string, object>> List = new List<Dictionary<string, object>>();
  179. MatchCollection ListMatch = Regex.Matches(item.Groups[2].ToString(), @"{[\s\S]+?}");//使用正则表达式匹配出JSON数组
  180. foreach (Match ListItem in ListMatch)
  181. {
  182. List.Add(ToDictionary(ListItem.ToString()));//递归调用
  183. }
  184. Data = List;
  185. }
  186. else if (item.Groups[2].ToString().ToLower() == "null") Data = null;//如果数据为null(字符串类型),直接转换成null
  187. else if (item.Groups[2].ToString().EndsWith(","))
  188. Data = item.Groups[2].ToString().Remove(item.Groups[2].ToString().Length - 1); //数据为数字、字符串中的一类,则去掉,直接写入
  189. else if (item.Groups[2].ToString().EndsWith("}"))
  190. Data = item.Groups[2].ToString().Remove(item.Groups[2].ToString().Length - 1); //数据为数字、字符串中的一类,则去掉,直接写入
  191. else
  192. Data = item.Groups[2].ToString();
  193. Dic.Add(item.Groups[1].ToString(), Data);
  194. }
  195. catch { }
  196. }
  197. }
  198. return Dic;
  199. }
  200. }
  201. }