Files
MesPrintService/Print.Application/Print/GoDEXPrint.cs
2025-07-12 16:20:14 +08:00

132 lines
4.4 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JingGong.Abp.Print.GoDEX
{
public class GoDEXPrint : IDisposable
{
private static object printLock = new object();
/// <summary>
/// 连接打印机
/// </summary>
/// <returns></returns>
public bool Open(GoDEXCommunication goDEXCommunication)
{
return EzioInterop.Open(goDEXCommunication.Host, goDEXCommunication.Port);
}
/// <summary>
/// 关闭打印机
/// </summary>
/// <returns></returns>
public bool Close()
{
return EzioInterop.closeport() == 1;
}
/// <summary>
/// 打印
/// </summary>
/// <returns></returns>
public bool Print(IGoDEXPrintData goDEXPrintData)
{
bool printSuccess = false;
//_logger.LogInformation("3.进入打印机方法,锁外");
try
{
// 打印任务执行,可能是阻塞的,因此考虑异步执行
Task.Run(() =>
{
try
{
//GoDEX库因无法识别打印机当前只适应用单任务打印
//lock (printLock)
//{
if (Open(goDEXPrintData.Communication))
{
LabelSetup(goDEXPrintData);
//^L標籤起始符號設定^L 正常列印,^LI 反白列印,^LM 鏡像列印,^LRn 整張旋轉 n=0, 0°列印 ; n=1, 90°列印 ; n=2, 180°列印 ; n=3, 270°列印
EzioInterop.sendcommand($"^L");
// 尝试执行打印操作,成功返回
if (goDEXPrintData.Print())
{
printSuccess = true;
}
else
{
throw new Exception("打印失败!");
}
//结束,打印机收到后开始打印
EzioInterop.sendcommand("E");
}
else
{
Console.WriteLine("6.打印机连接失败");
throw new Exception("打印机连接失败!");
}
}
catch (Exception ex)
{
// 记录异常日志
//_logger.LogInformation($"5.打印操作异常:{ex.Message}");
Console.WriteLine($"打印操作异常:{ex.Message}");
}
finally
{
Close();
}
});
}
catch(Exception ex)
{
// 捕获整个过程中的异常
//_logger.LogInformation($"打印失败,异常:{ex.Message}");
Console.WriteLine($"打印失败:{ex.Message}");
}
return printSuccess;
}
/// <summary>
/// 设定参数
/// </summary>
/// <param name="goDEXPrintData"></param>
private void LabelSetup(IGoDEXPrintData goDEXPrintData)
{
//標籤長度設定 x长y不指定z每张间隔
EzioInterop.sendcommand($"^Q{goDEXPrintData.LabelSetup.Height},0,{goDEXPrintData.LabelSetup.Speed}");
//^W54標籤寬度設定
EzioInterop.sendcommand($"^W{goDEXPrintData.LabelSetup.Width}");
//^H10列印黑度設定x = 00 ~ 19
EzioInterop.sendcommand($"^H{goDEXPrintData.LabelSetup.Dark}");
//^S3列印速度設定x = 2 ~ 10
EzioInterop.sendcommand($"^H{goDEXPrintData.LabelSetup.Speed}");
//^P1連續列印
EzioInterop.sendcommand($"^P1");
//^C1複製張數x = 1 ~ 32767
EzioInterop.sendcommand($"^C1");
}
/// <summary>
/// 关闭打印机
/// </summary>
public void Dispose()
{
Close();
}
}
}