C# (C Sharp)

Send bytes to thermal printer with C# and ESC POS

In this article I will show you how to use native C# to open a thermal printer as a file and send it bytes or data including ESC POS commands.

Remember that I already have a plugin that allows you to print on thermal printers and exposes a consumable HTTP API from any programming language so that you can use it and not implement your own library, but if you want to see how it’s done, keep reading.

Connecting to thermal printer in C#

In order to communicate (and send bytes) with the thermal printer in Visual Studio we must open it as if it were a file.

Before we open the POS printer, we must share it. This is because we are going to use it as if it were a network printer.

Then we import the SafeFileHandle function from kernel32.dll and open our printer:

SafeFileHandle fh = CreateFile(ubicacionCompletaImpresora, FileAccess.Write, 0, IntPtr.Zero, FileMode.OpenOrCreate, 0, IntPtr.Zero);

In this case the full location of the printer is the concatenation of the hostname and the name of the shared printer using double backslashes \\.

Print to thermal printer from C#

Now that we have the printer opened as a file we can write data to it and if that data follows the ESC POS protocol then we can exploit the potential of the printer.

var impresoraComoArchivo = new FileStream(fh, FileAccess.ReadWrite);
impresoraComoArchivo.WriteByte(0x1b); // ESC
impresoraComoArchivo.WriteByte(0x40); // @
impresoraComoArchivo.Write(Encoding.ASCII.GetBytes(textoParaImprimir), 0, textoParaImprimir.Length);
impresoraComoArchivo.WriteByte(0x1b); // Feed
impresoraComoArchivo.WriteByte(Convert.ToByte('d'));
impresoraComoArchivo.WriteByte(Convert.ToByte(1)); // 1 línea
impresoraComoArchivo.Dispose();

We just have to write bytes. For example, to start, the ESC and @ bytes are sent. Then we can write text and make a paper feed with 0x1b, the letter d, and the number of lines we want.

From this point on, we can now read the ESC POS specifications and write bytes to our thermal printers from C#.

Putting it all together

C# and Thermal printer – print text and feed

Earlier I showed you the basic code to send raw bytes to a thermal printer from C#, now I’ll show you the full code to send a Hello world to a POS printer from C#.

using System;
using System.IO;
using System.Text;
using Microsoft.Win32.SafeHandles;
using System.Runtime.InteropServices;

public class ImpresoraTermica
{

    [DllImport("kernel32.dll", SetLastError = true)]
    static extern SafeFileHandle CreateFile(string lpFileName, FileAccess dwDesiredAccess, uint dwShareMode, IntPtr lpSecurityAttributes, FileMode dwCreationDisposition, uint dwFlagsAndAttributes, IntPtr hTemplateFile);

    public static void Main()
    {
        string nombreImpresora = "PT210";
        string textoParaImprimir = "Hola impresora desde C#!";
        string hostname = System.Environment.MachineName;
        string ubicacionCompletaImpresora = string.Format("\\\\{0}\\{1}", System.Environment.MachineName, nombreImpresora);
        SafeFileHandle fh = CreateFile(ubicacionCompletaImpresora, FileAccess.Write, 0, IntPtr.Zero, FileMode.OpenOrCreate, 0, IntPtr.Zero);
        if (fh.IsInvalid)
        {
            Console.WriteLine("Error abriendo impresora");
            return;
        }
        var impresoraComoArchivo = new FileStream(fh, FileAccess.ReadWrite);
        impresoraComoArchivo.WriteByte(0x1b); // ESC
        impresoraComoArchivo.WriteByte(0x40); // @
        impresoraComoArchivo.Write(Encoding.ASCII.GetBytes(textoParaImprimir), 0, textoParaImprimir.Length);
        impresoraComoArchivo.WriteByte(0x1b); // Feed
        impresoraComoArchivo.WriteByte(Convert.ToByte('d'));
        impresoraComoArchivo.WriteByte(Convert.ToByte(1)); // 1 línea
        impresoraComoArchivo.Dispose();
    }
}

Please note: my printer’s name is PT210. Remember to change that name on line 15.

When you run that code, and if your thermal printer is already installed, shared and connected by USB then the message you see in the photo will be printed.

From here you can read the protocol and implement everything you need for your thermal printer.

If you want, you can use my free plugin that already has several functions such as text styles, image printing, qr codes, custom character definition, network printing, Bluetooth version and much more.


I am available for hiring if you need help! I can help you with your project or homework feel free to contact me.
If you liked the post, show your appreciation by sharing it, or making a donation

parzibyte

Freelancer programmer ready to work with you. Web, mobile and desktop applications. PHP, Java, Go, Python, JavaScript, Kotlin and more :) https://parzibyte.me/

Entradas recientes

Receipt designer for thermal printers – Free and open source

In the last months I have been working on a ticket designer to print on…

12 months hace

JavaScript: store and read files with the Origin Private File System

In this post you will learn how to use the Origin Private File System with…

1 year hace

JavaScript: download file with fetch

In this post you will learn how to download a file in the background using…

1 year hace

SQLite3 with vanilla JavaScript and OPFS – Hello world

In this post I will show you how to use SQLite3 directly in the web…

1 year hace

Python Thermal Printing: A Comprehensive Guide for Printing on Thermal Printers

In this tutorial, we'll explore how to effortlessly print receipts, invoices, and tickets on a…

1 year hace

Image printing on Thermal printer

When printing receipts on thermal printers (ESC POS) sometimes it is needed to print images…

1 year hace

Esta web usa cookies.