├── web-print-agent
├── print.ico
├── Properties
│ ├── Settings.settings
│ ├── Settings.Designer.cs
│ ├── AssemblyInfo.cs
│ ├── Resources.Designer.cs
│ └── Resources.resx
├── Model
│ └── PrintRe.cs
├── App.xaml
├── packages.config
├── Utils
│ ├── Global.cs
│ ├── LocalPrinter.cs
│ ├── Notification.cs
│ └── WindowsMin.cs
├── App.config
├── Service
│ ├── Socket
│ │ ├── ISocketService.cs
│ │ ├── SocketService.cs
│ │ ├── MySocketService.cs
│ │ └── SocketBase.cs
│ ├── MyLogService.cs
│ └── PrintService.cs
├── NotificationWindow.xaml
├── MainWindow.xaml
├── App.xaml.cs
├── log4net.config
├── MainWindow.xaml.cs
├── NotificationWindow.xaml.cs
├── web-print-agent.csproj
└── DynamicJson.cs
├── test
├── index.html
└── test.json
├── README.md
├── web-print-agent.sln
└── .gitignore
/web-print-agent/print.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AlanLang/web-print-agent/HEAD/web-print-agent/print.ico
--------------------------------------------------------------------------------
/web-print-agent/Properties/Settings.settings:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/web-print-agent/Model/PrintRe.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace web_print_agent.Model
8 | {
9 | public class PrintRe
10 | {
11 | public double id { get; set; }
12 | public int code { get; set; }
13 | public string msg {get;set;}
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/web-print-agent/App.xaml:
--------------------------------------------------------------------------------
1 |
6 |
7 |
8 |
9 |
10 |
--------------------------------------------------------------------------------
/web-print-agent/packages.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/web-print-agent/Utils/Global.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace web_print_agent.Utils
8 | {
9 | public class Global
10 | {
11 | public static bool canClose = false;
12 | public static bool canSatrt = false;
13 |
14 | public const string SYSISRUN = "系统正在运行";
15 | public const string PRINTSETSUCESS = "成功设置打印机:";
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/web-print-agent/App.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
--------------------------------------------------------------------------------
/web-print-agent/Service/Socket/ISocketService.cs:
--------------------------------------------------------------------------------
1 | using Fleck;
2 | using System;
3 | using System.Collections.Generic;
4 | using System.Linq;
5 | using System.Text;
6 | using System.Threading.Tasks;
7 |
8 | namespace web_print_agent.Service.Socket
9 | {
10 | public interface ISocketService
11 | {
12 |
13 | ///
14 | /// 当建立socket连接时,会调用此方法
15 | ///
16 | ///
17 | void OnConnected(string clientIp);
18 |
19 | void OnDisconnected();
20 |
21 | void OnMessage(string msg, IWebSocketConnection client);
22 |
23 | void OnError(Exception ex);
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/test/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | 打印测试
5 |
6 |
7 |
8 |
28 |
29 |
--------------------------------------------------------------------------------
/test/test.json:
--------------------------------------------------------------------------------
1 | {"id":1537148688,"page":{"width":210,"height":297},"content":[{"type":"text","text":"南昌故郡,\r\n洪都新府。星分翼轸,地接衡庐。襟三江而带五湖,控蛮荆而引瓯越。物华天宝,龙光射牛斗之墟;人杰地灵,徐孺下陈蕃之榻。雄州雾列,俊采星驰,台隍枕夷夏之交,宾主尽东南之美。都督阎公之雅望,棨戟遥临;宇文新州之懿范,襜帷暂驻。十旬休假,胜友如云;千里逢迎,高朋满座。腾蛟起凤,孟学士之词宗;紫电青霜,王将军之武库。家君作宰,路出名区;童子何知,躬逢胜饯。时维九月,序属三秋。潦水尽而寒潭清,烟光凝而暮山紫。俨骖騑于上路,访风景于崇阿。临帝子之长洲,得仙人之旧馆。层台耸翠,上出重霄;飞阁流丹,下临无地。鹤汀凫渚,穷岛屿之萦回;桂殿兰宫,列冈峦之体势。披绣闼,俯雕甍,山原旷其盈视,川泽盱其骇瞩。闾阎扑地,钟鸣鼎食之家;舸舰迷津,青雀黄龙之轴。虹销雨霁,彩彻区明。落霞与孤鹜齐飞,秋水共长天一色。渔舟唱晚,响穷彭蠡之滨;雁阵惊寒,声断衡阳之浦。遥襟俯畅,逸兴遄飞。爽籁发而清风生,纤歌凝而白云遏。睢园绿竹,气凌彭泽之樽;邺水朱华,光照临川之笔。四美具,二难并。穷睇眄于中天,极娱游于暇日。天高地迥,觉宇宙之无穷;兴尽悲来,识盈虚之有数。望长安于日下,指吴会于云间。地势极而南溟深,天柱高而北辰远。关山难越,谁悲失路之人?萍水相逢,尽是他乡之客。怀帝阍而不见,奉宣室以何年?嗟乎!时运不济,命运多舛。冯唐易老,李广难封。屈贾谊于长沙,非无圣主;窜梁鸿于海曲,岂乏明时。所赖君子安贫,达人知命。老当益壮,宁移白首之心?穷且益坚,不坠青云之志。酌贪泉而觉爽,处涸辙以犹欢。北海虽赊,扶摇可接;东隅已逝,桑榆非晚。孟尝高洁,空怀报国之心;阮藉猖狂,岂效穷途之哭!勃,三尺微命,一介书生。无路请缨,等终军之弱冠;有怀投笔,慕宗懿之长风。舍簪笏于百龄,奉晨昏于万里。非谢家之宝树,接孟氏之芳邻。他日趋庭,叨陪鲤对;今晨捧袂,喜托龙门。杨意不逢,抚凌云而自惜;钟期既遇,奏流水以何惭?鸣呼!胜地不常,盛筵难再。兰亭已矣,梓泽丘墟。临别赠言,幸承恩于伟饯;登高作赋,是所望于群公。敢竭鄙诚,恭疏短引。一言均赋,四韵俱成。请洒潘江,各倾陆海云尔!","size":20,"x":40,"y":5},{"type":"line","x1":1,"y1":1,"x2":1,"y2":5},{"type":"qrcode","text":"打印的内容","width":70,"height":70,"x":55,"y":15}]}
--------------------------------------------------------------------------------
/web-print-agent/Service/Socket/SocketService.cs:
--------------------------------------------------------------------------------
1 | using Fleck;
2 | using System;
3 | using System.Collections.Generic;
4 | using System.Linq;
5 | using System.Text;
6 | using System.Threading.Tasks;
7 |
8 | namespace web_print_agent.Service.Socket
9 | {
10 | ///
11 | /// Socket服务类,此类只允许被继承,不可直接实例化
12 | ///
13 | public abstract class SocketService : ISocketService
14 | {
15 | public IDictionary dic_Sockets = new Dictionary();
16 |
17 | public virtual void OnConnected(string clientIp)
18 | {
19 | }
20 |
21 | public virtual void OnDisconnected()
22 | {
23 | }
24 |
25 | public abstract void OnError(Exception ex);
26 |
27 | public virtual void OnMessage(string msg, IWebSocketConnection client)
28 | {
29 |
30 | }
31 |
32 | public void sendAll(string msg)
33 | {
34 | foreach (var item in dic_Sockets)
35 | {
36 | item.Value.Send(msg);
37 | }
38 | }
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/web-print-agent/Service/MyLogService.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace web_print_agent.Service
8 | {
9 | public class MyLogService
10 | {
11 | static readonly log4net.ILog loginfo = log4net.LogManager.GetLogger("loginfo");
12 | static readonly log4net.ILog logerror = log4net.LogManager.GetLogger("logerror");
13 | static readonly log4net.ILog logprint = log4net.LogManager.GetLogger("logprint");
14 |
15 | public static void Error(string ErrorMsg, Exception ex = null)
16 | {
17 | if (ex != null)
18 | {
19 | logerror.Error(ErrorMsg, ex);
20 | }
21 | else
22 | {
23 | logerror.Error(ErrorMsg);
24 | }
25 | }
26 | public static void Info(string Msg)
27 | {
28 | loginfo.Info(Msg);
29 | }
30 |
31 | public static void Print(string Msg)
32 | {
33 | logprint.Info(Msg);
34 | }
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/web-print-agent/Service/Socket/MySocketService.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 | using Fleck;
7 |
8 | namespace web_print_agent.Service.Socket
9 | {
10 | public class MySocketService:SocketService
11 | {
12 | PrintService printService;
13 | public MySocketService(PrintService printService)
14 | {
15 | this.printService = printService;
16 | }
17 | public override void OnError(Exception ex)
18 | {
19 | MyLogService.Error("socket调用发生错误:" + ex.Message,ex);
20 | }
21 |
22 | public override void OnMessage(string msg, IWebSocketConnection client)
23 | {
24 | if (printService.SetPrintOrder(msg))
25 | {
26 | bool re = printService.TestPrintOrder();
27 | client.Send(printService.Msg);
28 | base.OnMessage(msg, client);
29 | }
30 | else {
31 | client.Send(printService.Msg);
32 | }
33 | }
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # web打印代理
2 | ## 简介
3 | 一款静默打印代理工具,通过建立Socket服务,接收打印指令,通过解析打印指令完成打印。
4 | ## 使用方式
5 | 1. 下载源码或者release版
6 | 2. 运行.exe文件
7 | 3. 打开测试页 `index.html`
8 | 4. 点击测试页的打印按钮
9 |
10 | ### 系统功能
11 | * 最小化到状态栏
12 | * 单实例
13 | * 设置默认打印机
14 | * 保留异常日志
15 | * 保留打印日志
16 | * 打印结果反馈
17 |
18 | ### 打印功能
19 | * 自定义纸张大小
20 | * 打印条形码,二维码
21 | * 打印图片
22 |
23 | ## 指令示例
24 | * JSON格式
25 | * 类型:text/qrcoe/datamatrix/barcode/line/image
26 | * 单位:毫米
27 | * 文字换行手动使用`\r\n`
28 |
29 | web->代理
30 | ```
31 | {
32 | "id":1537148688,
33 | "page":{
34 | "width":210,
35 | "height":297
36 | },
37 | "content":
38 | [
39 | {
40 | "type":"text",
41 | "text":"改需求推荐使用支付宝",
42 | "size":20,
43 | "x":65,
44 | "y":100
45 | },
46 | {
47 | "type":"line",
48 | "x1":0,
49 | "y1":130,
50 | "x2":210,
51 | "y2":130
52 | },
53 | {
54 | "type":"qrcode",
55 | "text":"https://qr.alipay.com/tsx04136zdm6mxp7jvv4s2f",
56 | "width":70,
57 | "height":70,
58 | "x":70,
59 | "y":15
60 | }
61 | ]
62 | }
63 | ```
64 | 代理->web
65 | ```
66 | {
67 | id:1537148688,
68 | code:0,//0成功,1失败
69 | msg:"返回的消息"
70 | }
71 | ```
72 |
--------------------------------------------------------------------------------
/web-print-agent/NotificationWindow.xaml:
--------------------------------------------------------------------------------
1 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
--------------------------------------------------------------------------------
/web-print-agent.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio 15
4 | VisualStudioVersion = 15.0.27703.2035
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "web-print-agent", "web-print-agent\web-print-agent.csproj", "{A778770A-DC3C-4E34-AE53-8542DA16BAFE}"
7 | EndProject
8 | Global
9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
10 | Debug|Any CPU = Debug|Any CPU
11 | Release|Any CPU = Release|Any CPU
12 | EndGlobalSection
13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
14 | {A778770A-DC3C-4E34-AE53-8542DA16BAFE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
15 | {A778770A-DC3C-4E34-AE53-8542DA16BAFE}.Debug|Any CPU.Build.0 = Debug|Any CPU
16 | {A778770A-DC3C-4E34-AE53-8542DA16BAFE}.Release|Any CPU.ActiveCfg = Release|Any CPU
17 | {A778770A-DC3C-4E34-AE53-8542DA16BAFE}.Release|Any CPU.Build.0 = Release|Any CPU
18 | EndGlobalSection
19 | GlobalSection(SolutionProperties) = preSolution
20 | HideSolutionNode = FALSE
21 | EndGlobalSection
22 | GlobalSection(ExtensibilityGlobals) = postSolution
23 | SolutionGuid = {909701C4-0376-4058-BE0A-09BB912A9C4F}
24 | EndGlobalSection
25 | EndGlobal
26 |
--------------------------------------------------------------------------------
/web-print-agent/Properties/Settings.Designer.cs:
--------------------------------------------------------------------------------
1 | //------------------------------------------------------------------------------
2 | //
3 | // This code was generated by a tool.
4 | // Runtime Version:4.0.30319.42000
5 | //
6 | // Changes to this file may cause incorrect behavior and will be lost if
7 | // the code is regenerated.
8 | //
9 | //------------------------------------------------------------------------------
10 |
11 | namespace web_print_agent.Properties
12 | {
13 |
14 |
15 | [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
16 | [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
17 | internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
18 | {
19 |
20 | private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
21 |
22 | public static Settings Default
23 | {
24 | get
25 | {
26 | return defaultInstance;
27 | }
28 | }
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/web-print-agent/Utils/LocalPrinter.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Drawing.Printing;
4 | using System.Runtime.InteropServices;
5 |
6 | namespace web_print_agent.Utils
7 | {
8 | public class LocalPrinter
9 | {
10 | private static PrintDocument fPrintDocument = new PrintDocument();
11 | public const string NOPRINTER = "未设置打印机";
12 | //获取本机默认打印机名称
13 | public static String GetDefaultPrinter()
14 | {
15 | string printerName = fPrintDocument.PrinterSettings.PrinterName;
16 | return string.IsNullOrWhiteSpace(printerName) ? NOPRINTER : printerName;
17 | }
18 | public static List GetLocalPrinters()
19 | {
20 | List fPrinters = new List();
21 | fPrinters.Add(GetDefaultPrinter()); //默认打印机始终出现在列表的第一项
22 | foreach (String fPrinterName in PrinterSettings.InstalledPrinters)
23 | {
24 | if (!fPrinters.Contains(fPrinterName))
25 | {
26 | fPrinters.Add(fPrinterName);
27 | }
28 | }
29 | return fPrinters;
30 | }
31 |
32 | [DllImport("winspool.drv")]
33 | public static extern bool SetDefaultPrinter(String Name); //调用win api将指定名称的打印机设置为默认打印机
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/web-print-agent/MainWindow.xaml:
--------------------------------------------------------------------------------
1 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
--------------------------------------------------------------------------------
/web-print-agent/Utils/Notification.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace web_print_agent.Utils
8 | {
9 | public class Notification
10 | {
11 | public static List _dialogs = new List();
12 | public void Open(string title,string content)
13 | {
14 | App.Current.Dispatcher.Invoke((Action)(() =>
15 | {
16 | NotifyData data = new NotifyData();
17 | data.Title = title;
18 | data.Content = content;
19 | NotificationWindow dialog = new NotificationWindow();//new 一个通知
20 | dialog.Closed += Dialog_Closed;
21 | dialog.TopFrom = GetTopFrom();
22 | _dialogs.Add(dialog);
23 | dialog.DataContext = data;//设置通知里要显示的数据
24 | dialog.Show();
25 | }));
26 | }
27 | private void Dialog_Closed(object sender, EventArgs e)
28 | {
29 | var closedDialog = sender as NotificationWindow;
30 | _dialogs.Remove(closedDialog);
31 | }
32 | double GetTopFrom()
33 | {
34 | //屏幕的高度-底部TaskBar的高度。
35 | double topFrom = System.Windows.SystemParameters.WorkArea.Bottom - 10;
36 | bool isContinueFind = _dialogs.Any(o => o.TopFrom == topFrom);
37 |
38 | while (isContinueFind)
39 | {
40 | topFrom = topFrom - 110;//此处100是NotifyWindow的高 110-100剩下的10 是通知之间的间距
41 | isContinueFind = _dialogs.Any(o => o.TopFrom == topFrom);
42 | }
43 |
44 | if (topFrom <= 0)
45 | topFrom = System.Windows.SystemParameters.WorkArea.Bottom - 10;
46 |
47 | return topFrom;
48 | }
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/web-print-agent/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Resources;
3 | using System.Runtime.CompilerServices;
4 | using System.Runtime.InteropServices;
5 | using System.Windows;
6 |
7 | // 有关程序集的一般信息由以下
8 | // 控制。更改这些特性值可修改
9 | // 与程序集关联的信息。
10 | [assembly: AssemblyTitle("web-print-agent")]
11 | [assembly: AssemblyDescription("")]
12 | [assembly: AssemblyConfiguration("")]
13 | [assembly: AssemblyCompany("")]
14 | [assembly: AssemblyProduct("web-print-agent")]
15 | [assembly: AssemblyCopyright("Copyright © 2018")]
16 | [assembly: AssemblyTrademark("")]
17 | [assembly: AssemblyCulture("")]
18 | [assembly: log4net.Config.XmlConfigurator(ConfigFile = "Log4Net.config", Watch = true)]
19 |
20 | // 将 ComVisible 设置为 false 会使此程序集中的类型
21 | //对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型
22 | //请将此类型的 ComVisible 特性设置为 true。
23 | [assembly: ComVisible(false)]
24 |
25 | //若要开始生成可本地化的应用程序,请设置
26 | //.csproj 文件中的 CultureYouAreCodingWith
27 | //例如,如果您在源文件中使用的是美国英语,
28 | //使用的是美国英语,请将 设置为 en-US。 然后取消
29 | //对以下 NeutralResourceLanguage 特性的注释。 更新
30 | //以下行中的“en-US”以匹配项目文件中的 UICulture 设置。
31 |
32 | //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
33 |
34 |
35 | [assembly: ThemeInfo(
36 | ResourceDictionaryLocation.None, //主题特定资源词典所处位置
37 | //(未在页面中找到资源时使用,
38 | //或应用程序资源字典中找到时使用)
39 | ResourceDictionaryLocation.SourceAssembly //常规资源词典所处位置
40 | //(未在页面中找到资源时使用,
41 | //、应用程序或任何主题专用资源字典中找到时使用)
42 | )]
43 |
44 |
45 | // 程序集的版本信息由下列四个值组成:
46 | //
47 | // 主版本
48 | // 次版本
49 | // 生成号
50 | // 修订号
51 | //
52 | // 可以指定所有值,也可以使用以下所示的 "*" 预置版本号和修订号
53 | // 方法是按如下所示使用“*”: :
54 | // [assembly: AssemblyVersion("1.0.*")]
55 | [assembly: AssemblyVersion("1.0.0.0")]
56 | [assembly: AssemblyFileVersion("1.0.0.0")]
--------------------------------------------------------------------------------
/web-print-agent/Service/Socket/SocketBase.cs:
--------------------------------------------------------------------------------
1 | using Fleck;
2 | using System;
3 | using System.Collections.Generic;
4 | using System.Linq;
5 | using System.Text;
6 | using System.Threading.Tasks;
7 |
8 | namespace web_print_agent.Service.Socket
9 | {
10 | public class SocketBase
11 | {
12 | SocketService socketService;
13 |
14 | public SocketBase(SocketService socketService) {
15 | this.socketService = socketService;
16 | }
17 |
18 | ///
19 | /// 当前连接数
20 | ///
21 | public int connectNum {
22 | get { return this.socketService.dic_Sockets.Count; }
23 | }
24 |
25 | public void start() {
26 | var server = new WebSocketServer("ws://0.0.0.0:9401");
27 | server.RestartAfterListenError = true;
28 | server.Start(socket =>
29 | {
30 | socket.OnOpen = () => //连接建立事件
31 | {
32 | //获取客户端网页的url
33 | string clientUrl = socket.ConnectionInfo.ClientIpAddress + ":" + socket.ConnectionInfo.ClientPort;
34 | this.socketService.dic_Sockets.Add(clientUrl, socket);
35 | this.socketService.OnConnected(clientUrl);
36 | };
37 | socket.OnMessage = message => {
38 | this.socketService.OnMessage(message, socket);
39 | };
40 | socket.OnClose = () => //连接关闭事件
41 | {
42 | string clientUrl = socket.ConnectionInfo.ClientIpAddress + ":" + socket.ConnectionInfo.ClientPort;
43 | //如果存在这个客户端,那么对这个socket进行移除
44 | if (this.socketService.dic_Sockets.ContainsKey(clientUrl))
45 | {
46 | this.socketService.dic_Sockets.Remove(clientUrl);
47 | }
48 | this.socketService.OnDisconnected();
49 | };
50 | socket.OnError = (ex) =>
51 | {
52 | this.socketService.OnError(ex);
53 | };
54 | });
55 | }
56 | }
57 | }
58 |
--------------------------------------------------------------------------------
/web-print-agent/Utils/WindowsMin.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 | using System.Windows;
7 |
8 | namespace web_print_agent.Utils
9 | {
10 | public class WindowsMin
11 | {
12 | WindowState wsl;
13 | System.Windows.Forms.NotifyIcon notifyIcon;
14 | Window windows;
15 | public WindowsMin(Window windows)
16 | {
17 | setMin();
18 | this.windows = windows;
19 | wsl = this.windows.WindowState;
20 | this.windows.Hide();//启动后直接最小化
21 | }
22 |
23 | public void hide()
24 | {
25 | this.notifyIcon.Visible = false;
26 | }
27 |
28 | public void onStateChange()
29 | {
30 | WindowState ws = this.windows.WindowState;
31 | if (ws == WindowState.Minimized)
32 | {
33 | this.windows.Hide();
34 | }
35 | }
36 |
37 |
38 | private void setMin()
39 | {
40 | this.notifyIcon = new System.Windows.Forms.NotifyIcon();
41 | this.notifyIcon.BalloonTipText = "欢迎使用打印服务"; //设置程序启动时显示的文本
42 | this.notifyIcon.Text = "打印服务";//最小化到托盘时,鼠标点击时显示的文本
43 | this.notifyIcon.Icon = new System.Drawing.Icon("print.ico");//程序图标
44 | this.notifyIcon.Icon = System.Drawing.Icon.ExtractAssociatedIcon(System.Windows.Forms.Application.ExecutablePath);
45 | this.notifyIcon.Visible = true;
46 |
47 | //右键菜单--打开菜单项
48 | System.Windows.Forms.MenuItem open = new System.Windows.Forms.MenuItem("打开");
49 | open.Click += new EventHandler(ShowWindow);
50 | //右键菜单--退出菜单项
51 | System.Windows.Forms.MenuItem exit = new System.Windows.Forms.MenuItem("退出");
52 | exit.Click += new EventHandler(CloseWindow);
53 | //关联托盘控件
54 | System.Windows.Forms.MenuItem[] childen = new System.Windows.Forms.MenuItem[] { open, exit };
55 | notifyIcon.ContextMenu = new System.Windows.Forms.ContextMenu(childen);
56 |
57 | notifyIcon.MouseClick += ShowWindow;
58 | this.notifyIcon.ShowBalloonTip(1000);
59 | }
60 |
61 |
62 | private void ShowWindow(object sender, EventArgs e)
63 | {
64 | this.windows.Show();
65 | this.windows.WindowState = wsl;
66 | }
67 |
68 | private void CloseWindow(object sender, EventArgs e)
69 | {
70 | Global.canClose = true;
71 | System.Windows.Application.Current.Shutdown();
72 | }
73 | }
74 | }
75 |
--------------------------------------------------------------------------------
/web-print-agent/Properties/Resources.Designer.cs:
--------------------------------------------------------------------------------
1 | //------------------------------------------------------------------------------
2 | //
3 | // 此代码由工具生成。
4 | // 运行时版本: 4.0.30319.42000
5 | //
6 | // 对此文件的更改可能导致不正确的行为,如果
7 | // 重新生成代码,则所做更改将丢失。
8 | //
9 | //------------------------------------------------------------------------------
10 |
11 | namespace web_print_agent.Properties
12 | {
13 |
14 |
15 | ///
16 | /// 强类型资源类,用于查找本地化字符串等。
17 | ///
18 | // 此类是由 StronglyTypedResourceBuilder
19 | // 类通过类似于 ResGen 或 Visual Studio 的工具自动生成的。
20 | // 若要添加或删除成员,请编辑 .ResX 文件,然后重新运行 ResGen
21 | // (以 /str 作为命令选项),或重新生成 VS 项目。
22 | [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
23 | [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
24 | [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
25 | internal class Resources
26 | {
27 |
28 | private static global::System.Resources.ResourceManager resourceMan;
29 |
30 | private static global::System.Globalization.CultureInfo resourceCulture;
31 |
32 | [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
33 | internal Resources()
34 | {
35 | }
36 |
37 | ///
38 | /// 返回此类使用的缓存 ResourceManager 实例。
39 | ///
40 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
41 | internal static global::System.Resources.ResourceManager ResourceManager
42 | {
43 | get
44 | {
45 | if ((resourceMan == null))
46 | {
47 | global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("web_print_agent.Properties.Resources", typeof(Resources).Assembly);
48 | resourceMan = temp;
49 | }
50 | return resourceMan;
51 | }
52 | }
53 |
54 | ///
55 | /// 覆盖当前线程的 CurrentUICulture 属性
56 | /// 使用此强类型的资源类的资源查找。
57 | ///
58 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
59 | internal static global::System.Globalization.CultureInfo Culture
60 | {
61 | get
62 | {
63 | return resourceCulture;
64 | }
65 | set
66 | {
67 | resourceCulture = value;
68 | }
69 | }
70 | }
71 | }
72 |
--------------------------------------------------------------------------------
/web-print-agent/App.xaml.cs:
--------------------------------------------------------------------------------
1 | using log4net;
2 | using System;
3 | using System.Collections.Generic;
4 | using System.Configuration;
5 | using System.Data;
6 | using System.Diagnostics;
7 | using System.Linq;
8 | using System.Threading;
9 | using System.Threading.Tasks;
10 | using System.Windows;
11 | using web_print_agent.Utils;
12 |
13 | namespace web_print_agent
14 | {
15 | ///
16 | /// App.xaml 的交互逻辑
17 | ///
18 | public partial class App : Application
19 | {
20 | protected override void OnStartup(StartupEventArgs e)
21 | {
22 | // Get Reference to the current Process
23 | Process thisProc = Process.GetCurrentProcess();
24 | // Check how many total processes have the same name as the current one
25 | if (Process.GetProcessesByName(thisProc.ProcessName).Length > 1)
26 | {
27 | // If ther is more than one, than it is already running.
28 | MessageBox.Show("已有一个程序正在运行");
29 | Global.canClose = true;
30 | Application.Current.Shutdown();
31 | return;
32 | }
33 | else { Global.canSatrt = true; }
34 |
35 | log4net.Config.XmlConfigurator.Configure();
36 |
37 | Application.Current.DispatcherUnhandledException += Current_DispatcherUnhandledException;
38 | AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
39 |
40 | base.OnStartup(e);
41 | }
42 |
43 | protected override void OnExit(ExitEventArgs e)
44 | {
45 | base.OnExit(e);
46 | if (!Global.canClose) {
47 | Process m_Process = new Process();
48 | m_Process.StartInfo.FileName = Process.GetCurrentProcess().MainModule.FileName;
49 | m_Process.StartInfo.Arguments = "admin";
50 | m_Process.Start();
51 | }
52 | }
53 |
54 | //主线程异常
55 | void Current_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
56 | {
57 | try
58 | {
59 | e.Handled = true;
60 | Service.MyLogService.Error("未捕获的主线程异常" + e.Exception.Message, e.Exception);
61 | MessageBox.Show(e.Exception.Message);
62 | }
63 | catch (Exception ex)
64 | {
65 | MessageBox.Show("应用程序发生不可恢复的异常,将要退出!");
66 | }
67 |
68 | }
69 |
70 | //非主线程异常
71 | void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
72 | {
73 | Service.MyLogService.Error("未捕获的子线程异常", e.ExceptionObject as Exception);
74 | }
75 | }
76 | }
77 |
--------------------------------------------------------------------------------
/web-print-agent/log4net.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
--------------------------------------------------------------------------------
/web-print-agent/MainWindow.xaml.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Net.Sockets;
5 | using System.Text;
6 | using System.Threading.Tasks;
7 | using System.Windows;
8 | using System.Windows.Controls;
9 | using System.Windows.Data;
10 | using System.Windows.Documents;
11 | using System.Windows.Input;
12 | using System.Windows.Media;
13 | using System.Windows.Media.Imaging;
14 | using System.Windows.Navigation;
15 | using System.Windows.Shapes;
16 | using web_print_agent.Service;
17 | using web_print_agent.Service.Socket;
18 | using web_print_agent.Utils;
19 | using System.Threading;
20 |
21 | namespace web_print_agent
22 | {
23 | ///
24 | /// MainWindow.xaml 的交互逻辑
25 | ///
26 | public partial class MainWindow : Window
27 | {
28 | SocketBase socketBase;
29 | MySocketService mySocketServer;
30 | WindowsMin windowsMin;
31 | public MainWindow()
32 | {
33 | InitializeComponent();
34 | if (Global.canSatrt)
35 | {
36 | init();
37 | }
38 | }
39 |
40 | private void init()
41 | {
42 | windowsMin = new WindowsMin(this);// 设置最小化到任务栏
43 | PrintService pt = new PrintService();
44 | //配置socket服务
45 | mySocketServer = new MySocketService(pt);
46 | socketBase = new SocketBase(mySocketServer);
47 | socketBase.start();
48 | //获取打印机信息
49 | var printers = LocalPrinter.GetLocalPrinters();
50 | PrintList.ItemsSource = printers;
51 | PrintList.SelectedIndex = 0;
52 | MyLogService.Info("打印服务已启动");
53 | }
54 |
55 | private void MetroWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
56 | {
57 | e.Cancel = true;
58 | this.Hide();
59 | }
60 |
61 | private void Window_StateChanged(object sender, EventArgs e)
62 | {
63 | windowsMin.onStateChange();
64 | }
65 |
66 | private void PrintList_SelectionChanged(object sender, SelectionChangedEventArgs e)
67 | {
68 | ComboBox comboBox = (ComboBox)sender;
69 | string selectedEmployee = (string)comboBox.SelectedItem;
70 | if (!selectedEmployee.Equals(LocalPrinter.GetDefaultPrinter()))
71 | {
72 | try
73 | {
74 | LocalPrinter.SetDefaultPrinter(selectedEmployee);
75 | setMsg(Global.PRINTSETSUCESS+selectedEmployee);
76 | }
77 | catch (Exception ex)
78 | {
79 | setMsg(ex.Message);
80 | }
81 |
82 | }
83 | }
84 |
85 | private void setMsg(string msg)
86 | {
87 | SystemMsg.Content = msg;
88 | Thread t = new Thread(() =>
89 | {
90 | Thread.Sleep(3000);//次线程休眠3秒
91 | Dispatcher.Invoke(new Action(() =>
92 | {
93 | SystemMsg.Content = Global.SYSISRUN;
94 | }));
95 | });
96 | t.Start();
97 | }
98 | }
99 | }
100 |
--------------------------------------------------------------------------------
/web-print-agent/NotificationWindow.xaml.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Media;
5 | using System.Text;
6 | using System.Threading.Tasks;
7 | using System.Windows;
8 | using System.Windows.Controls;
9 | using System.Windows.Data;
10 | using System.Windows.Documents;
11 | using System.Windows.Input;
12 | using System.Windows.Media;
13 | using System.Windows.Media.Animation;
14 | using System.Windows.Media.Imaging;
15 | using System.Windows.Shapes;
16 |
17 | namespace web_print_agent
18 | {
19 | ///
20 | /// NotificationWindow.xaml 的交互逻辑
21 | ///
22 | public partial class NotificationWindow : Window
23 | {
24 | public double TopFrom
25 | {
26 | get; set;
27 | }
28 | public NotificationWindow()
29 | {
30 | InitializeComponent();
31 | this.Loaded += NotificationWindow_Loaded;
32 | }
33 |
34 | private void NotificationWindow_Loaded(object sender, RoutedEventArgs e)
35 | {
36 | NotifyData data = this.DataContext as NotifyData;
37 | if (data != null)
38 | {
39 | tbContent.Text = data.Content;
40 | tbTitle.Text = data.Title;
41 | }
42 | NotificationWindow self = sender as NotificationWindow;
43 | if (self != null)
44 | {
45 | self.UpdateLayout();
46 | //SystemSounds.Asterisk.Play();//播放提示声
47 |
48 | double right = System.Windows.SystemParameters.WorkArea.Right;//工作区最右边的值
49 | self.Top = self.TopFrom - self.ActualHeight;
50 | DoubleAnimation animation = new DoubleAnimation();
51 | animation.Duration = new Duration(TimeSpan.FromMilliseconds(500));//NotifyTimeSpan是自己定义的一个int型变量,用来设置动画的持续时间
52 | animation.From = right;
53 | animation.To = right - self.ActualWidth;//设定通知从右往左弹出
54 | self.BeginAnimation(Window.LeftProperty, animation);//设定动画应用于窗体的Left属性
55 |
56 | Task.Factory.StartNew(delegate
57 | {
58 | int seconds = 5;//通知持续5s后消失
59 | System.Threading.Thread.Sleep(TimeSpan.FromSeconds(seconds));
60 | //Invoke到主进程中去执行
61 | this.Dispatcher.Invoke(delegate
62 | {
63 | animation = new DoubleAnimation();
64 | animation.Duration = new Duration(TimeSpan.FromMilliseconds(500));
65 | animation.Completed += (s, a) => { self.Close(); };//动画执行完毕,关闭当前窗体
66 | animation.From = right - self.ActualWidth;
67 | animation.To = right;//通知从左往右收回
68 | self.BeginAnimation(Window.LeftProperty, animation);
69 | });
70 | });
71 | }
72 | }
73 |
74 | private void Button_Click(object sender, RoutedEventArgs e)
75 | {
76 | double right = System.Windows.SystemParameters.WorkArea.Right;
77 | DoubleAnimation animation = new DoubleAnimation();
78 | animation.Duration = new Duration(TimeSpan.FromMilliseconds(500));
79 |
80 | animation.Completed += (s, a) => { this.Close(); };
81 | animation.From = right - this.ActualWidth;
82 | animation.To = right;
83 | this.BeginAnimation(Window.LeftProperty, animation);
84 | }
85 | }
86 |
87 | class NotifyData
88 | {
89 | public string Title { get; set; }
90 | public string Content { get; set; }
91 | }
92 | }
93 |
--------------------------------------------------------------------------------
/web-print-agent/Properties/Resources.resx:
--------------------------------------------------------------------------------
1 |
2 |
3 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 |
98 |
99 |
100 |
101 |
102 |
103 |
104 |
105 |
106 | text/microsoft-resx
107 |
108 |
109 | 2.0
110 |
111 |
112 | System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
113 |
114 |
115 | System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
116 |
117 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | ## Ignore Visual Studio temporary files, build results, and
2 | ## files generated by popular Visual Studio add-ons.
3 | ##
4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
5 |
6 | # User-specific files
7 | *.suo
8 | *.user
9 | *.userosscache
10 | *.sln.docstates
11 |
12 | # User-specific files (MonoDevelop/Xamarin Studio)
13 | *.userprefs
14 |
15 | # Build results
16 | [Dd]ebug/
17 | [Dd]ebugPublic/
18 | [Rr]elease/
19 | [Rr]eleases/
20 | x64/
21 | x86/
22 | bld/
23 | [Bb]in/
24 | [Oo]bj/
25 | [Ll]og/
26 |
27 | # Visual Studio 2015/2017 cache/options directory
28 | .vs/
29 | # Uncomment if you have tasks that create the project's static files in wwwroot
30 | #wwwroot/
31 |
32 | # Visual Studio 2017 auto generated files
33 | Generated\ Files/
34 |
35 | # MSTest test Results
36 | [Tt]est[Rr]esult*/
37 | [Bb]uild[Ll]og.*
38 |
39 | # NUNIT
40 | *.VisualState.xml
41 | TestResult.xml
42 |
43 | # Build Results of an ATL Project
44 | [Dd]ebugPS/
45 | [Rr]eleasePS/
46 | dlldata.c
47 |
48 | # Benchmark Results
49 | BenchmarkDotNet.Artifacts/
50 |
51 | # .NET Core
52 | project.lock.json
53 | project.fragment.lock.json
54 | artifacts/
55 | **/Properties/launchSettings.json
56 |
57 | # StyleCop
58 | StyleCopReport.xml
59 |
60 | # Files built by Visual Studio
61 | *_i.c
62 | *_p.c
63 | *_i.h
64 | *.ilk
65 | *.meta
66 | *.obj
67 | *.pch
68 | *.pdb
69 | *.pgc
70 | *.pgd
71 | *.rsp
72 | *.sbr
73 | *.tlb
74 | *.tli
75 | *.tlh
76 | *.tmp
77 | *.tmp_proj
78 | *.log
79 | *.vspscc
80 | *.vssscc
81 | .builds
82 | *.pidb
83 | *.svclog
84 | *.scc
85 |
86 | # Chutzpah Test files
87 | _Chutzpah*
88 |
89 | # Visual C++ cache files
90 | ipch/
91 | *.aps
92 | *.ncb
93 | *.opendb
94 | *.opensdf
95 | *.sdf
96 | *.cachefile
97 | *.VC.db
98 | *.VC.VC.opendb
99 |
100 | # Visual Studio profiler
101 | *.psess
102 | *.vsp
103 | *.vspx
104 | *.sap
105 |
106 | # Visual Studio Trace Files
107 | *.e2e
108 |
109 | # TFS 2012 Local Workspace
110 | $tf/
111 |
112 | # Guidance Automation Toolkit
113 | *.gpState
114 |
115 | # ReSharper is a .NET coding add-in
116 | _ReSharper*/
117 | *.[Rr]e[Ss]harper
118 | *.DotSettings.user
119 |
120 | # JustCode is a .NET coding add-in
121 | .JustCode
122 |
123 | # TeamCity is a build add-in
124 | _TeamCity*
125 |
126 | # DotCover is a Code Coverage Tool
127 | *.dotCover
128 |
129 | # AxoCover is a Code Coverage Tool
130 | .axoCover/*
131 | !.axoCover/settings.json
132 |
133 | # Visual Studio code coverage results
134 | *.coverage
135 | *.coveragexml
136 |
137 | # NCrunch
138 | _NCrunch_*
139 | .*crunch*.local.xml
140 | nCrunchTemp_*
141 |
142 | # MightyMoose
143 | *.mm.*
144 | AutoTest.Net/
145 |
146 | # Web workbench (sass)
147 | .sass-cache/
148 |
149 | # Installshield output folder
150 | [Ee]xpress/
151 |
152 | # DocProject is a documentation generator add-in
153 | DocProject/buildhelp/
154 | DocProject/Help/*.HxT
155 | DocProject/Help/*.HxC
156 | DocProject/Help/*.hhc
157 | DocProject/Help/*.hhk
158 | DocProject/Help/*.hhp
159 | DocProject/Help/Html2
160 | DocProject/Help/html
161 |
162 | # Click-Once directory
163 | publish/
164 |
165 | # Publish Web Output
166 | *.[Pp]ublish.xml
167 | *.azurePubxml
168 | # Note: Comment the next line if you want to checkin your web deploy settings,
169 | # but database connection strings (with potential passwords) will be unencrypted
170 | *.pubxml
171 | *.publishproj
172 |
173 | # Microsoft Azure Web App publish settings. Comment the next line if you want to
174 | # checkin your Azure Web App publish settings, but sensitive information contained
175 | # in these scripts will be unencrypted
176 | PublishScripts/
177 |
178 | # NuGet Packages
179 | *.nupkg
180 | # The packages folder can be ignored because of Package Restore
181 | **/[Pp]ackages/*
182 | # except build/, which is used as an MSBuild target.
183 | !**/[Pp]ackages/build/
184 | # Uncomment if necessary however generally it will be regenerated when needed
185 | #!**/[Pp]ackages/repositories.config
186 | # NuGet v3's project.json files produces more ignorable files
187 | *.nuget.props
188 | *.nuget.targets
189 |
190 | # Microsoft Azure Build Output
191 | csx/
192 | *.build.csdef
193 |
194 | # Microsoft Azure Emulator
195 | ecf/
196 | rcf/
197 |
198 | # Windows Store app package directories and files
199 | AppPackages/
200 | BundleArtifacts/
201 | Package.StoreAssociation.xml
202 | _pkginfo.txt
203 | *.appx
204 |
205 | # Visual Studio cache files
206 | # files ending in .cache can be ignored
207 | *.[Cc]ache
208 | # but keep track of directories ending in .cache
209 | !*.[Cc]ache/
210 |
211 | # Others
212 | ClientBin/
213 | ~$*
214 | *~
215 | *.dbmdl
216 | *.dbproj.schemaview
217 | *.jfm
218 | *.pfx
219 | *.publishsettings
220 | orleans.codegen.cs
221 |
222 | # Including strong name files can present a security risk
223 | # (https://github.com/github/gitignore/pull/2483#issue-259490424)
224 | #*.snk
225 |
226 | # Since there are multiple workflows, uncomment next line to ignore bower_components
227 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
228 | #bower_components/
229 |
230 | # RIA/Silverlight projects
231 | Generated_Code/
232 |
233 | # Backup & report files from converting an old project file
234 | # to a newer Visual Studio version. Backup files are not needed,
235 | # because we have git ;-)
236 | _UpgradeReport_Files/
237 | Backup*/
238 | UpgradeLog*.XML
239 | UpgradeLog*.htm
240 |
241 | # SQL Server files
242 | *.mdf
243 | *.ldf
244 | *.ndf
245 |
246 | # Business Intelligence projects
247 | *.rdl.data
248 | *.bim.layout
249 | *.bim_*.settings
250 |
251 | # Microsoft Fakes
252 | FakesAssemblies/
253 |
254 | # GhostDoc plugin setting file
255 | *.GhostDoc.xml
256 |
257 | # Node.js Tools for Visual Studio
258 | .ntvs_analysis.dat
259 | node_modules/
260 |
261 | # TypeScript v1 declaration files
262 | typings/
263 |
264 | # Visual Studio 6 build log
265 | *.plg
266 |
267 | # Visual Studio 6 workspace options file
268 | *.opt
269 |
270 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
271 | *.vbw
272 |
273 | # Visual Studio LightSwitch build output
274 | **/*.HTMLClient/GeneratedArtifacts
275 | **/*.DesktopClient/GeneratedArtifacts
276 | **/*.DesktopClient/ModelManifest.xml
277 | **/*.Server/GeneratedArtifacts
278 | **/*.Server/ModelManifest.xml
279 | _Pvt_Extensions
280 |
281 | # Paket dependency manager
282 | .paket/paket.exe
283 | paket-files/
284 |
285 | # FAKE - F# Make
286 | .fake/
287 |
288 | # JetBrains Rider
289 | .idea/
290 | *.sln.iml
291 |
292 | # CodeRush
293 | .cr/
294 |
295 | # Python Tools for Visual Studio (PTVS)
296 | __pycache__/
297 | *.pyc
298 |
299 | # Cake - Uncomment if you are using it
300 | # tools/**
301 | # !tools/packages.config
302 |
303 | # Tabs Studio
304 | *.tss
305 |
306 | # Telerik's JustMock configuration file
307 | *.jmconfig
308 |
309 | # BizTalk build output
310 | *.btp.cs
311 | *.btm.cs
312 | *.odx.cs
313 | *.xsd.cs
314 |
315 | # OpenCover UI analysis results
316 | OpenCover/
317 |
318 | # Azure Stream Analytics local run output
319 | ASALocalRun/
320 |
321 | # MSBuild Binary and Structured Log
322 | *.binlog
323 | /test
324 |
--------------------------------------------------------------------------------
/web-print-agent/web-print-agent.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Debug
6 | AnyCPU
7 | {A778770A-DC3C-4E34-AE53-8542DA16BAFE}
8 | WinExe
9 | web_print_agent
10 | web-print-agent
11 | v4.5
12 | 512
13 | {60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}
14 | 4
15 |
16 |
17 | AnyCPU
18 | true
19 | full
20 | false
21 | bin\Debug\
22 | DEBUG;TRACE
23 | prompt
24 | 4
25 |
26 |
27 | AnyCPU
28 | pdbonly
29 | true
30 | bin\Release\
31 | TRACE
32 | prompt
33 | 4
34 |
35 |
36 | print.ico
37 |
38 |
39 |
40 | ..\packages\Fleck.1.0.3\lib\net45\Fleck.dll
41 |
42 |
43 | ..\packages\log4net.2.0.8\lib\net45-full\log4net.dll
44 |
45 |
46 | ..\packages\Newtonsoft.Json.11.0.2\lib\net45\Newtonsoft.Json.dll
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 | ..\packages\FormMin.1.0.0\lib\System.Windows.Forms.dll
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 | 4.0
65 |
66 |
67 |
68 |
69 |
70 | ..\packages\ZXing.Net.0.16.4\lib\net45\zxing.dll
71 |
72 |
73 | ..\packages\ZXing.Net.0.16.4\lib\net45\zxing.presentation.dll
74 |
75 |
76 |
77 |
78 | MSBuild:Compile
79 | Designer
80 |
81 |
82 |
83 |
84 | NotificationWindow.xaml
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 | MSBuild:Compile
98 | Designer
99 |
100 |
101 | App.xaml
102 | Code
103 |
104 |
105 | MainWindow.xaml
106 | Code
107 |
108 |
109 | Designer
110 | MSBuild:Compile
111 |
112 |
113 |
114 |
115 | Code
116 |
117 |
118 | True
119 | True
120 | Resources.resx
121 |
122 |
123 | True
124 | Settings.settings
125 | True
126 |
127 |
128 | ResXFileCodeGenerator
129 | Resources.Designer.cs
130 |
131 |
132 | PreserveNewest
133 |
134 |
135 |
136 | SettingsSingleFileGenerator
137 | Settings.Designer.cs
138 |
139 |
140 |
141 |
142 | Designer
143 |
144 |
145 |
146 |
147 | Always
148 |
149 |
150 |
151 |
152 |
--------------------------------------------------------------------------------
/web-print-agent/Service/PrintService.cs:
--------------------------------------------------------------------------------
1 | using Codeplex.Data;
2 | using System;
3 | using System.Collections.Generic;
4 | using System.Drawing;
5 | using System.Drawing.Printing;
6 | using System.IO;
7 | using System.Linq;
8 | using System.Text;
9 | using System.Threading.Tasks;
10 | using ZXing;
11 | using ZXing.Common;
12 | using ZXing.QrCode;
13 |
14 | namespace web_print_agent.Service
15 | {
16 | public class PrintService
17 | {
18 | protected dynamic printOrder;
19 | protected string msg;
20 | protected PrintDocument pd;
21 | protected string fontFamily = "正常";
22 | protected int Pixel;
23 | public string Msg { get { return msg; } }
24 |
25 | public bool SetPrintOrder(string printOrder)
26 | {
27 | try
28 | {
29 | new Utils.Notification().Open("打印通知", "已接到打印指令,正在打印");
30 | this.printOrder = DynamicJson.Parse(printOrder);
31 | MyLogService.Print(printOrder);
32 | return true;
33 | }
34 | catch (Exception ex)
35 | {
36 | this.msg = ex.Message;
37 | MyLogService.Error("反序列化打印指令出错", ex);
38 | new Utils.Notification().Open("打印通知", "反序列化打印指令出错");
39 | return false;
40 | }
41 |
42 | }
43 | public bool TestPrintOrder()
44 | {
45 | Double id = printOrder.id;
46 | pd = new PrintDocument();
47 | this.setPageSize();
48 | Model.PrintRe printRe = new Model.PrintRe();
49 | printRe.id = id;
50 | try
51 | {
52 | Pixel = pd.DefaultPageSettings.PrinterResolution.X;// 获取分辨率
53 | pd.PrintPage += pd_PrintPage;
54 | pd.PrintController = new StandardPrintController(); //去掉打印弹出框
55 | pd.Print();
56 | printRe.code = 0;
57 | new Utils.Notification().Open("打印通知", "打印完成");
58 | printRe.msg = "打印成功";
59 | }
60 | catch (Exception ex)
61 | {
62 | printRe.code = 1;
63 | printRe.msg = ex.Message;
64 | MyLogService.Error("解析打印指令出错", ex);
65 | new Utils.Notification().Open("打印通知", "解析打印指令出错");
66 | return false;
67 | }
68 | finally {
69 | this.msg = DynamicJson.Serialize(printRe);
70 | MyLogService.Print(this.msg);
71 | }
72 |
73 | return true;
74 | }
75 | void pd_PrintPage(object sender, PrintPageEventArgs e)
76 | {
77 | Graphics g = e.Graphics;
78 | var content = printOrder.content;
79 | foreach (var item in content)
80 | {
81 | string type = item.type;
82 | switch (type.ToLower())
83 | {
84 | case "text":
85 | printText(g,item);
86 | break;
87 | case "line":
88 | printLine(g, item);
89 | break;
90 | case "qrcode":
91 | printBarCode(g, item, BarcodeFormat.QR_CODE);
92 | break;
93 | case "datamatrix":
94 | printBarCode(g, item, BarcodeFormat.DATA_MATRIX);
95 | break;
96 | case "barcode":
97 | printBarCode(g, item, BarcodeFormat.CODE_128);
98 | break;
99 | case "image":
100 | printImage(g, item);
101 | break;
102 | default:
103 | MyLogService.Print("无法识别的打印命令:" + type);
104 | break;
105 | }
106 | }
107 | }
108 |
109 | private void printImage(Graphics g, dynamic item)
110 | {
111 | string text = item.text;
112 | float width = toInches(item.width);
113 | float height = toInches(item.height);
114 | float x = toInches(item.x);
115 | float y = toInches(item.y);
116 | System.Net.WebRequest webreq = System.Net.WebRequest.Create(text);
117 | System.Net.WebResponse webres = webreq.GetResponse();
118 | Stream stream = webres.GetResponseStream();
119 | Image image = Image.FromStream(stream);
120 | stream.Close();
121 | g.DrawImage(image, x, y, width, height);
122 | }
123 |
124 | ///
125 | /// 打印二维码
126 | ///
127 | ///
128 | ///
129 | private void printBarCode(Graphics g, dynamic item, BarcodeFormat format)
130 | {
131 | float width = toInches(item.width);
132 | float height = toInches(item.height);
133 | float x = toInches(item.x);
134 | float y = toInches(item.y);
135 | string text = item.text;
136 | g.DrawImage(newBarcode(format, text,(int)width,(int)height),x, y, width, height);
137 | }
138 |
139 | ///
140 | /// 打印线条
141 | ///
142 | ///
143 | ///
144 | private void printLine(Graphics g, dynamic item)
145 | {
146 | float x1 = toInches(item.x1);
147 | float y1 = toInches(item.y1);
148 | float x2 = toInches(item.x2);
149 | float y2 = toInches(item.y2);
150 | Pen pen = new Pen(Color.Black, 1);
151 | g.DrawLine(pen, x1,y1,x2,y2);
152 | }
153 |
154 | ///
155 | /// 打印文字
156 | ///
157 | ///
158 | ///
159 | private void printText(Graphics g, dynamic item)
160 | {
161 | string text = item.text;
162 | int size = toInt(item.size);
163 | float x = toInches(item.x);
164 | float y = toInches(item.y);
165 | g.DrawString(text, new Font(fontFamily, size), System.Drawing.Brushes.Black, x, y);
166 | }
167 |
168 | ///
169 | /// 生成条码
170 | ///
171 | /// 条码类型
172 | /// 内容
173 | /// 宽度
174 | /// 高度
175 | ///
176 | protected Bitmap newBarcode(BarcodeFormat format, string text, int width, int height)
177 | {
178 | BarcodeWriter writer = new BarcodeWriter();
179 | writer.Format = format;
180 | QrCodeEncodingOptions options = new QrCodeEncodingOptions()
181 | {
182 | DisableECI = true,//设置内容编码
183 | CharacterSet = "UTF-8", //设置二维码的宽度和高度
184 | Width = width,
185 | Height = height,
186 | Margin = 1//设置二维码的边距,单位不是固定像素
187 | };
188 | writer.Options = options;
189 | Bitmap map = writer.Write(text);
190 | return map;
191 | }
192 |
193 | ///
194 | /// 设置页面尺寸
195 | ///
196 | protected void setPageSize()
197 | {
198 | string pageName = printOrder.id.ToString();
199 | int width = tomInches(printOrder.page.width);
200 | int height = tomInches(printOrder.page.height);
201 | PaperSize ps = new PaperSize("Custum", width, height);
202 | pd.DocumentName = pageName;
203 | pd.DefaultPageSettings.PaperSize = ps;
204 | //使用自定义页面设置
205 | pd.DefaultPageSettings.PaperSize.RawKind = 256;
206 | }
207 |
208 | public int tomInches(double mm)
209 | {
210 | return (int)Math.Round(mm*3.937);
211 | }
212 |
213 | public float toInches(double num)
214 | {
215 | return Convert.ToSingle(num * 3.937008);
216 | }
217 |
218 | public int toInt(dynamic i)
219 | {
220 | return Convert.ToInt32(i);
221 | }
222 | }
223 | }
224 |
--------------------------------------------------------------------------------
/web-print-agent/DynamicJson.cs:
--------------------------------------------------------------------------------
1 | /*--------------------------------------------------------------------------
2 | * DynamicJson
3 | * ver 1.2.0.0 (May. 21th, 2010)
4 | *
5 | * created and maintained by neuecc
6 | * licensed under Microsoft Public License(Ms-PL)
7 | * http://neue.cc/
8 | * http://dynamicjson.codeplex.com/
9 | *--------------------------------------------------------------------------*/
10 | using System;
11 | using System.Collections;
12 | using System.Collections.Generic;
13 | using System.Diagnostics;
14 | using System.Dynamic;
15 | using System.IO;
16 | using System.Linq;
17 | using System.Reflection;
18 | using System.Runtime.Serialization.Json;
19 | using System.Text;
20 | using System.Xml;
21 | using System.Xml.Linq;
22 |
23 | namespace Codeplex.Data
24 | {
25 | public class DynamicJson : DynamicObject
26 | {
27 | private enum JsonType
28 | {
29 | @string, number, boolean, @object, array, @null
30 | }
31 |
32 | // public static methods
33 |
34 | /// from JsonSring to DynamicJson
35 | public static dynamic Parse(string json)
36 | {
37 | return Parse(json, Encoding.Unicode);
38 | }
39 |
40 | /// from JsonSring to DynamicJson
41 | public static dynamic Parse(string json, Encoding encoding)
42 | {
43 | using (var reader = JsonReaderWriterFactory.CreateJsonReader(encoding.GetBytes(json), XmlDictionaryReaderQuotas.Max))
44 | {
45 | return ToValue(XElement.Load(reader));
46 | }
47 | }
48 |
49 | /// from JsonSringStream to DynamicJson
50 | public static dynamic Parse(Stream stream)
51 | {
52 | using (var reader = JsonReaderWriterFactory.CreateJsonReader(stream, XmlDictionaryReaderQuotas.Max))
53 | {
54 | return ToValue(XElement.Load(reader));
55 | }
56 | }
57 |
58 | /// from JsonSringStream to DynamicJson
59 | public static dynamic Parse(Stream stream, Encoding encoding)
60 | {
61 | using (var reader = JsonReaderWriterFactory.CreateJsonReader(stream, encoding, XmlDictionaryReaderQuotas.Max, _ => { }))
62 | {
63 | return ToValue(XElement.Load(reader));
64 | }
65 | }
66 |
67 | /// create JsonSring from primitive or IEnumerable or Object({public property name:property value})
68 | public static string Serialize(object obj)
69 | {
70 | return CreateJsonString(new XStreamingElement("root", CreateTypeAttr(GetJsonType(obj)), CreateJsonNode(obj)));
71 | }
72 |
73 | // private static methods
74 |
75 | private static dynamic ToValue(XElement element)
76 | {
77 | var type = (JsonType)Enum.Parse(typeof(JsonType), element.Attribute("type").Value);
78 | switch (type)
79 | {
80 | case JsonType.boolean:
81 | return (bool)element;
82 | case JsonType.number:
83 | return (double)element;
84 | case JsonType.@string:
85 | return (string)element;
86 | case JsonType.@object:
87 | case JsonType.array:
88 | return new DynamicJson(element, type);
89 | case JsonType.@null:
90 | default:
91 | return null;
92 | }
93 | }
94 |
95 | private static JsonType GetJsonType(object obj)
96 | {
97 | if (obj == null) return JsonType.@null;
98 |
99 | switch (Type.GetTypeCode(obj.GetType()))
100 | {
101 | case TypeCode.Boolean:
102 | return JsonType.boolean;
103 | case TypeCode.String:
104 | case TypeCode.Char:
105 | case TypeCode.DateTime:
106 | return JsonType.@string;
107 | case TypeCode.Int16:
108 | case TypeCode.Int32:
109 | case TypeCode.Int64:
110 | case TypeCode.UInt16:
111 | case TypeCode.UInt32:
112 | case TypeCode.UInt64:
113 | case TypeCode.Single:
114 | case TypeCode.Double:
115 | case TypeCode.Decimal:
116 | case TypeCode.SByte:
117 | case TypeCode.Byte:
118 | return JsonType.number;
119 | case TypeCode.Object:
120 | return (obj is IEnumerable) ? JsonType.array : JsonType.@object;
121 | case TypeCode.DBNull:
122 | case TypeCode.Empty:
123 | default:
124 | return JsonType.@null;
125 | }
126 | }
127 |
128 | private static XAttribute CreateTypeAttr(JsonType type)
129 | {
130 | return new XAttribute("type", type.ToString());
131 | }
132 |
133 | private static object CreateJsonNode(object obj)
134 | {
135 | var type = GetJsonType(obj);
136 | switch (type)
137 | {
138 | case JsonType.@string:
139 | case JsonType.number:
140 | return obj;
141 | case JsonType.boolean:
142 | return obj.ToString().ToLower();
143 | case JsonType.@object:
144 | return CreateXObject(obj);
145 | case JsonType.array:
146 | return CreateXArray(obj as IEnumerable);
147 | case JsonType.@null:
148 | default:
149 | return null;
150 | }
151 | }
152 |
153 | private static IEnumerable CreateXArray(T obj) where T : IEnumerable
154 | {
155 | return obj.Cast