You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET 8控制台程序调用TSC TTP-225打印机首次打印标签错位,后续打印正常的问题求助

.NET 8控制台程序调用TSC TTP-225打印机首次打印标签错位,后续打印正常的问题求助

大家好,我最近碰到一个挺棘手的打印机问题,折腾了好一阵没找到原因,想过来请教下各位:

我开发了一个.NET 8的C#控制台应用,通过发送TSC原始指令给TTP-225打印机来打印标签。但奇怪的是,第一次启动程序打印时,标签上的所有元素(文本、条码)都会出现坐标偏移,整体错位;可如果我马上再运行一次程序,标签就会完美打印,位置完全正确,之后的每次打印也都正常。

具体症状

  • 首次运行:文本、条码的位置全部偏移错误,标签内容排版混乱,完全不符合预期
  • 后续运行:所有元素的坐标精准,对齐正确,标签排版完美

我使用的打印指令字符串

var command = "";
command += "SIZE 43 mm, 25 mm\r\n";
command += "GAP 2 mm, 0 mm\r\n";
command += "DIRECTION 1,0\r\n";
command += "CLS\r\n";
command += "TEXT 10,25,\"FONT005\",0,1,1,\"S04-19-8948589-46\"\r\n";
command += "BARCODE 1,70,\"EAN13\",60,0,0,3,3,0,\"3200000004634\"\r\n";
command += "TEXT 90,145,\"FONT005\",0,1,1,\"46042081\"\r\n";
command += "TEXT -30,180,\"FONT005\",0,1,1,\"п.4 ч.1 ст.46\"\r\n";
command += "TEXT 165,180,\"FONT005\",0,1,1,\"27.12.2023\"\r\n";
command += "PRINT 1,1\r\n";
PrinterHelper.SendStringToPrinter("TSC TTP-225", command);

完整代码示例

主程序入口

using Lib.Logging;
using Microsoft.Extensions.DependencyInjection;
using Serilog;
using System.Diagnostics;
using System.Runtime.InteropServices;

System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);

var services = new ServiceCollection();
services.AddMyLogger(options => {
    options.LogTargets = LogTarget.Console | LogTarget.File | LogTarget.Json;
    options.UseSerilogRequestLogging = false;
});

try
{
    Log.Information("Console application started");
    var stopwatch = new Stopwatch();
    stopwatch.Start();

    services.AddSingleton<PrinterLogic>();
    var provider = services.BuildServiceProvider();
    var businessLogic = provider.GetRequiredService<PrinterLogic>();

    try
    {
        await businessLogic.PrintAsync();
    }
    catch (Exception ex)
    {
        Log.Error(ex, "PrintAsync method failed");
    }

    stopwatch.Stop();
    Log.Information("All subtasks completed, elapsed time: {Elapsed}", stopwatch.Elapsed);
}
catch (Exception exception)
{
    Log.Error(exception, "Application terminated with error");
}

Log.Information("Press any key to exit ......");
Console.ReadKey();
return;

PrinterLogic 打印逻辑类

public class PrinterLogic
{
    public async Task PrintAsync()
    {
        var command = "";
        // Printer initialization and calibration
        command += "SIZE 43 mm, 25 mm\r\n";
        command += "GAP 2 mm, 0 mm\r\n";
        //Rotation / mirroring
        command += "DIRECTION 1,0\r\n";
        // Clear buffer
        command += "CLS\r\n";
        // Content (FONT005 is a custom font that has been previously downloaded (uploaded) to the printer’s memory.)
        command += "TEXT 10,25,\"FONT005\",0,1,1,\"S04-19-8948589-46\"\r\n";
        command += "BARCODE 1,70,\"EAN13\",60,0,0,3,3,0,\"3200000004634\"\r\n";
        command += "TEXT 90,145,\"FONT005\",0,1,1,\"46042081\"\r\n";
        command += "TEXT -30,180,\"FONT005\",0,1,1,\"п.4 ч.1 ст.46\"\r\n";
        command += "TEXT 165,180,\"FONT005\",0,1,1,\"27.12.2023\"\r\n";
        // Print
        command += "PRINT 1,1\r\n";

        Log.Information("Sending commands to printer: {{Commands}}", command);
        var success = PrinterHelper.SendStringToPrinter("TSC TTP-225", command);

        if (success)
        {
            Log.Information("Commands successfully sent to printer");
            // Short pause to allow printer to process commands
            await Task.Delay(500);
        }
        else
        {
            Log.Error("Failed to send commands to printer");
        }
    }
}

PrinterHelper 打印机交互工具类

public class PrinterHelper
{
    // Structure and API declarations:
    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
    public class DOCINFOA
    {
        [MarshalAs(UnmanagedType.LPStr)]
        public string pDocName;
        [MarshalAs(UnmanagedType.LPStr)]
        public string pOutputFile;
        [MarshalAs(UnmanagedType.LPStr)]
        public string pDataType;
    }

    [DllImport("winspool.Drv", EntryPoint = "OpenPrinterA", SetLastError = true, CharSet = CharSet.Ansi, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
    public static extern bool OpenPrinter([MarshalAs(UnmanagedType.LPStr)] string szPrinter, out IntPtr hPrinter, IntPtr pd);

    [DllImport("winspool.Drv", EntryPoint = "ClosePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
    public static extern bool ClosePrinter(IntPtr hPrinter);

    [DllImport("winspool.Drv", EntryPoint = "StartDocPrinterA", SetLastError = true, CharSet = CharSet.Ansi, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
    public static extern bool StartDocPrinter(IntPtr hPrinter, Int32 level, [In, MarshalAs(UnmanagedType.LPStruct)] DOCINFOA di);

    [DllImport("winspool.Drv", EntryPoint = "StartPagePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
    public static extern bool StartPagePrinter(IntPtr hPrinter);

    [DllImport("winspool.Drv", EntryPoint = "WritePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
    public static extern bool WritePrinter(IntPtr hPrinter, IntPtr pBytes, Int32 dwCount, out Int32 dwWritten);

    [DllImport("winspool.Drv", EntryPoint = "EndPagePrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
    public static extern bool EndPagePrinter(IntPtr hPrinter);

    [DllImport("winspool.Drv", EntryPoint = "EndDocPrinter", SetLastError = true, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
    public static extern bool EndDocPrinter(IntPtr hPrinter);

    // Send string to printer implementation
    public static bool SendStringToPrinter(string szPrinterName, string szString)
    {
        IntPtr hPrinter = IntPtr.Zero;
        DOCINFOA di = new DOCINFOA();
        bool bSuccess = false;
        IntPtr pBytes;
        int dwCount;

        di.pDocName = "TSC Label Print Job";
        di.pDataType = "RAW";

        if (OpenPrinter(szPrinterName.Normalize(), out hPrinter, IntPtr.Zero))
        {
            if (StartDocPrinter(hPrinter, 1, di))
            {
                if (StartPagePrinter(hPrinter))
                {
                    dwCount = szString.Length;
                    pBytes = Marshal.StringToCoTaskMemAnsi(szString);
                    if (WritePrinter(hPrinter, pBytes, dwCount, out int dwWritten))
                    {
                        bSuccess = dwWritten == dwCount;
                    }
                    Marshal.FreeCoTaskMem(pBytes);
                    EndPagePrinter(hPrinter);
                }
                EndDocPrinter(hPrinter);
            }
            ClosePrinter(hPrinter);
        }

        if (!bSuccess)
        {
            int errorCode = Marshal.GetLastWin32Error();
            // Optional: Log the error code for debugging
        }

        return bSuccess;
    }
}

内容来源于stack exchange

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.07 13:02:57