escpos

package module
v0.1.4 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 5, 2026 License: MIT Imports: 11 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

About escpos GoDoc

Go Reference

This is a Golang package that provides ESC-POS library functions to help with sending control codes to a ESC-POS thermal printer.

It implements the protocol described in this Command Manual

Current featureset

  • Initializing the Printer
  • Toggling Underline mode
  • Toggling Bold text
  • Toggling upside-down character printing
  • Toggling Reverse mode
  • Line spacing settings
  • Rotated characters
  • Align text
  • Default ASCII Charset, Western Europe and GBK encoding
  • Character size settings
  • UPC-A, UPC-E, EAN13, EAN8 Barcodes
  • QR Codes
  • Standard printing mode
  • Image Printing
  • Printing of predefined NV images
  • Cash drawer control

Installation

Install the package via the following:

go get -u github.com/schawnndev/escpos

Usage

The escpos package can be used as the following:

package main

import (
	"github.com/schawnndev/escpos"
)

func main() {
	nwPrinter, err := escpos.NewNetworkPrinter("192.168.8.40:9100")
	if err != nil {
		println(err.Error())
		return
	}
	defer nwPrinter.Close()
	
	p := escpos.New(nwPrinter)
	p.SetConfig(escpos.ConfigEpsonTMT20II)

	p.SetBold(true)
	p.SetSize(2, 2)
	p.Write("Hello World")
	p.LineFeed()
	
	p.SetBold(false)
	p.SetUnderline(escpos.UnderlineSingle)
	p.SetJustify(escpos.JustifyCenter)
	p.Write("this is underlined")
	p.LineFeed()
	p.QRCode("https://github.com/schawnndev/escpos", escpos.QRCodeModel2, 3, escpos.QRCodeErrorCorrectionLevelL)

	// You need to use either p.Print() or p.PrintAndCut() at the end to send the data to the printer.
	p.PrintAndCut()
}

Setting Printer Parameters

The library provides a consistent naming convention for functions that set parameters, using the Set prefix:

// Setting text parameters
p.SetBold(true)
p.SetUnderline(escpos.UnderlineDouble)
p.SetUpsideDown(true)
p.SetReverse(true)
p.SetJustify(escpos.JustifyCenter)
p.SetSize(2, 2)
p.SetFont(escpos.FontB)

// Setting line parameters
p.SetLineSpacing(30)
p.SetDefaultLineSpacing()

// Setting barcode parameters
p.SetBarcodeHeight(100)
p.SetBarcodeWidth(4)
p.SetHRIPosition(escpos.HRIPositionBelow)
p.SetHRIFont(true)

// Other control functions
p.SetMotionUnits(10, 20)
p.SetCodePage(escpos.CodePagePC850)

Disable features

As the library sets all the styling parameters again for each call of Write, you might run into compatibility issues. Therefore it is possible to deactivate features. To do so, use a predefined config (available for all printers listed under Compatibility) right after the escpos.New call

p := escpos.New(socket)
p.SetConfig(escpos.ConfigEpsonTMT20II) // predefined config for the Epson TM-T20II

// or for example

p.SetConfig(escpos.PrinterConfig{DisableUnderline: true})

Other Printer Sources

If you want to use other printer sources, you can implement the Printer interface provided by the library. The Printer interface defines the basic methods (Read, Write, and Close) required for communication with a printer. This allows flexibility to connect to printers using different protocols or sources, such as serial, network, or custom implementations.

For example, to implement a serial printer connection, you can do the following:

package escpos

import "go.bug.st/serial"

type serialPrinter struct {
	port serial.Port
}

func NewSerialPrinter(portName string, baudRate int) (Printer, error) {
	mode := &serial.Mode{
		BaudRate: baudRate,
	}
	port, err := serial.Open(portName, mode)
	if err != nil {
		return nil, err
	}
	return &serialPrinter{
		port: port,
	}, nil
}

func (sp *serialPrinter) Read(p []byte) (n int, err error) {
	return sp.port.Read(p)
}

func (sp *serialPrinter) Write(p []byte) (n int, err error) {
	return sp.port.Write(p)
}

func (sp *serialPrinter) Close() error {
    return sp.port.Close()
}

Compatibility

This is a (not complete) list of supported and tested devices.

Manufacturer Model Styling Barcodes QR Codes Images
Epson TM-T20II ✅ ✅ ✅ ✅
Epson TM-T88II ☑️
UpsideDown Printing not supported
✅ ✅
Munbyn ITPP047P ✅ ✅ ✅ ✅

Documentation

Overview

stolen and modified from https://github.com/mugli/png2escpos

This file is inspired by what is done in the python-escpos and escpos-php libraries.

Index

Constants

View Source
const (
	UnderlineNone   uint8 = 0 // No underline
	UnderlineSingle uint8 = 1 // Single underline
	UnderlineDouble uint8 = 2 // Double underline
)

Underline constants

View Source
const (
	FontA uint8 = 0 // Font A (12x24)
	FontB uint8 = 1 // Font B (9x24)
)

Font type constants

View Source
const (
	QRCodeErrorCorrectionLevelL uint8 = 48 // 7% recovery capacity
	QRCodeErrorCorrectionLevelM uint8 = 49 // 15% recovery capacity
	QRCodeErrorCorrectionLevelQ uint8 = 50 // 25% recovery capacity
	QRCodeErrorCorrectionLevelH uint8 = 51 // 30% recovery capacity
)

QR code error correction levels

View Source
const (
	QRCodeModel1 uint8 = 49 // Model 1 (older, smaller capacity)
	QRCodeModel2 uint8 = 50 // Model 2 (newer, enhanced functionality)
)

QR code model constants

View Source
const (
	BarcodeUPCA    uint8 = 0
	BarcodeUPCE    uint8 = 1
	BarcodeEAN13   uint8 = 2
	BarcodeEAN8    uint8 = 3
	BarcodeCode39  uint8 = 4
	BarcodeITF     uint8 = 5
	BarcodeCodabar uint8 = 6
)

Barcode types

View Source
const (
	HRIPositionNone  uint8 = 0
	HRIPositionAbove uint8 = 1
	HRIPositionBelow uint8 = 2
	HRIPositionBoth  uint8 = 3
)

HRI position constants

View Source
const (
	// Real-time status commands
	RT_STATUS_ONLINE byte = 1
	RT_STATUS_PAPER  byte = 4

	// Masks
	RT_MASK_NEAREND byte = 0x0C // bits 2 and 3
	RT_MASK_NOPAPER byte = 0x60 // bits 5 and 6
	RT_MASK_OFFLINE byte = 0x08
)

Real-time status command constants

View Source
const (
	// ImageProcessDither applies Floyd-Steinberg dithering
	ImageProcessDither uint8 = 0
	// ImageProcessThreshold applies simple threshold-based conversion
	ImageProcessThreshold uint8 = 1
)

Image processing method constants

View Source
const (
	CodePagePC437      uint8 = 0  // USA, Standard Europe
	CodePageKatakana   uint8 = 1  // Katakana
	CodePagePC850      uint8 = 2  // Multilingual
	CodePagePC860      uint8 = 3  // Portuguese
	CodePagePC863      uint8 = 4  // Canadian-French
	CodePagePC865      uint8 = 5  // Nordic
	CodePageISO8859_1  uint8 = 6  // Western European
	CodePageWPC1252    uint8 = 16 // Latin 1
	CodePagePC866      uint8 = 17 // Cyrillic #2
	CodePagePC852      uint8 = 18 // Latin 2
	CodePagePC858      uint8 = 19 // Euro
	CodePageIranII     uint8 = 20 // Iran II
	CodePageLatvian    uint8 = 21 // Latvian
	CodePageISO88596   uint8 = 22 // Arabic
	CodePageLCDTurkish uint8 = 24 // Turkish
	CodePageISO8859_15 uint8 = 25 // Latin 9
	CodePageCP1098     uint8 = 38 // Farsi
	CodePageCP864      uint8 = 40 // Arabic
	CodePageISO8859_2  uint8 = 41 // Latin 2
	CodePageCP1125     uint8 = 42 // Ukrainian
	CodePageCP1250     uint8 = 47 // Latin 2
	CodePageCP1251     uint8 = 48 // Cyrillic
	CodePageCP1253     uint8 = 49 // Greek
	CodePageCP1254     uint8 = 50 // Turkish
	CodePageCP1255     uint8 = 51 // Hebrew
	CodePageCP1256     uint8 = 52 // Arabic
	CodePageCP1257     uint8 = 53 // Baltic
	CodePageCP1258     uint8 = 54 // Vietnamese
	CodePageKZ1048     uint8 = 55 // Kazakhstan
)

Code page constants

Variables

View Source
var (
	ConfigEpsonTMT20II = PrinterConfig{}
	ConfigEpsonTMT88II = PrinterConfig{DisableUpsideDown: true}
	ConfigSOL802       = PrinterConfig{DisableUpsideDown: true}
)

Functions

func PrepareImageForPrinting

func PrepareImageForPrinting(img image.Image, highDensityVertical bool, highDensityHorizontal bool) (data []byte, err error)

PrepareImageForPrinting prepares a dithered image for printing on a thermal printer. It uses Floyd-Steinberg dithering to convert the image to black and white. highDensityVertical and highDensityHorizontal control the density of the image. The image is rasterized and converted to a byte array for printing (header included). todo: add support for fragmentHeight, center, and maxWidth

Types

type Escpos

type Escpos struct {
	Style Style
	// contains filtered or unexported fields
}

Escpos represents a ESC/POS printer connection

func New

func New(printer Printer) *Escpos

New creates a new Escpos printer instance. PC850 (code page 2 – "Multilingual") is set as the default encoding so that accented characters like é, ç, à, ù, è work correctly out of the box for Western European languages. PC850 has near-universal support on thermal ESC/POS printers; Windows-1252 (code page 16) is often silently ignored by cheaper or older printer firmware. Call SetEncoding to switch to a different character set.

func (*Escpos) Barcode

func (e *Escpos) Barcode(barcodeType uint8, code string) (int, error)

Barcode is a generic function to print barcodes barcodeType: one of the Barcode* constants code: the data to encode

func (*Escpos) CODABAR

func (e *Escpos) CODABAR(code string) (int, error)

CODABAR prints a CODABAR barcode

func (*Escpos) CODE39

func (e *Escpos) CODE39(code string) (int, error)

CODE39 prints a CODE39 barcode

func (*Escpos) Cut

func (e *Escpos) Cut() (int, error)

Cut feeds the paper to the cutting position and cuts it

func (*Escpos) EAN8

func (e *Escpos) EAN8(code string) (int, error)

EAN8 prints an EAN-8 barcode code must be 7-8 digits

func (*Escpos) EAN13

func (e *Escpos) EAN13(code string) (int, error)

EAN13 prints an EAN-13 barcode code must be 12-13 digits

func (*Escpos) ITF

func (e *Escpos) ITF(code string) (int, error)

ITF prints an ITF barcode

func (*Escpos) Initialize

func (e *Escpos) Initialize() (int, error)

Initialize resets the printer to its default settings

func (*Escpos) IsOnline

func (e *Escpos) IsOnline() (bool, error)

IsOnline queries the online status of the printer Returns true if the printer is online, false otherwise

func (*Escpos) LineFeed

func (e *Escpos) LineFeed() (int, error)

LineFeed sends a newline to the printer

func (*Escpos) LineFeedN

func (e *Escpos) LineFeedN(p uint8) (int, error)

LineFeedN prints and feeds the paper p lines

func (*Escpos) OpenDrawer

func (e *Escpos) OpenDrawer(pin uint8, time uint8) (int, error)

OpenDrawer opens the cash drawer connected to the printer pin: pin number (0 or 1) time: pulse duration (1-8) * 100ms

func (*Escpos) PaperStatus

func (e *Escpos) PaperStatus() (int, error)

PaperStatus queries the paper status using DLE EOT 4 Returns: 2 = Paper is adequate 1 = Paper is low (near end) 0 = No paper

func (*Escpos) PartialCut

func (e *Escpos) PartialCut() (int, error)

PartialCut performs a partial paper cut

func (*Escpos) Print

func (e *Escpos) Print() error

Print sends the buffered data to the printer

func (*Escpos) PrintAndCut

func (e *Escpos) PrintAndCut() error

PrintAndCut sends the buffered data to the printer and performs a cut

func (*Escpos) PrintImageWithProcessing

func (e *Escpos) PrintImageWithProcessing(image image.Image, processMethod uint8, highDensityVertical bool, highDensityHorizontal bool) (int, error)

PrintImageWithProcessing prints an image to the printer using the specified processing method Multiple parameters are available to control the image processing:

  • image: the image to print
  • processMethod: the image processing method to use (ImageProcessDither or ImageProcessThreshold)
  • highDensityVertical: if true, use high density vertical printing (only for dithered images)
  • highDensityHorizontal: if true, use high density horizontal printing (only for dithered images)

Returns the number of bytes written and any error encountered

func (*Escpos) PrintNVBitImage

func (e *Escpos) PrintNVBitImage(p uint8, mode uint8) (int, error)

PrintNVBitImage prints a pre-stored bit image with index p and mode p: image index (1-based) mode: print mode (0-3)

func (*Escpos) QRCode

func (e *Escpos) QRCode(code string, model uint8, size uint8, correctionLevel uint8) (int, error)

QRCode prints a QR code

Parameters:

  • code: the data to encode (max 7089 characters for Model 2, 1167 for Model 1)
  • model: QR code model to use (QRCodeModel1 or QRCodeModel2)
  • size: size of QR code modules in dots (1-16)
  • correctionLevel: error correction level with these options:
  • QRCodeErrorCorrectionLevelL: Recovers 7% of data
  • QRCodeErrorCorrectionLevelM: Recovers 15% of data
  • QRCodeErrorCorrectionLevelQ: Recovers 25% of data
  • QRCodeErrorCorrectionLevelH: Recovers 30% of data

Returns the number of bytes written and any error encountered. Use Model 2 for most applications as it offers better capacity and features.

func (*Escpos) QueryStatus

func (e *Escpos) QueryStatus(statusType byte) ([]byte, error)

QueryStatus sends a real-time status request to the printer and returns the response The parameter 'statusType' should be one of the RT_STATUS_* constants

func (*Escpos) SetBarcodeHeight

func (e *Escpos) SetBarcodeHeight(p uint8) (int, error)

SetBarcodeHeight sets the height for barcodes in dots (default: 162)

func (*Escpos) SetBarcodeWidth

func (e *Escpos) SetBarcodeWidth(p uint8) (int, error)

SetBarcodeWidth sets the width for barcodes (2-6, default: 3)

func (*Escpos) SetBold

func (e *Escpos) SetBold(b bool) (int, error)

SetBold sets the bold mode Use true for bold, false for normal

func (*Escpos) SetCodePage

func (e *Escpos) SetCodePage(codepage uint8) (int, error)

SetCodePage sets the code page (character set) for the printer The list of available code pages varies by printer model

func (*Escpos) SetConfig

func (e *Escpos) SetConfig(conf PrinterConfig)

SetConfig sets the printer configuration options

func (*Escpos) SetDefaultLineSpacing

func (e *Escpos) SetDefaultLineSpacing() (int, error)

SetDefaultLineSpacing sets the line spacing to the default (1/6 inch)

func (*Escpos) SetEncoding added in v0.1.4

func (e *Escpos) SetEncoding(enc encoding.Encoding, codepage uint8) (int, error)

SetEncoding sets the default character encoding used by Write() and sends the corresponding ESC t (code page) command to the printer so both sides agree on the character table. Pass nil as enc to disable encoding and revert to raw UTF-8 passthrough.

The default encoding set by New() is PC850 (CodePagePC850), which covers all Western European characters (é ç à ù è …) and is supported by virtually all thermal ESC/POS printers.

Example – switch to Windows-1252 (if your printer supports code page 16):

e.SetEncoding(charmap.Windows1252, escpos.CodePageWPC1252)

Example – disable encoding (raw bytes):

e.SetEncoding(nil, 0)

func (*Escpos) SetFont

func (e *Escpos) SetFont(f uint8) (int, error)

SetFont sets the font type Use FontA (12x24) or FontB (9x24)

func (*Escpos) SetHRIFont

func (e *Escpos) SetHRIFont(p bool) (int, error)

SetHRIFont sets the HRI font false: Font A (12x24) true: Font B (9x24)

func (*Escpos) SetHRIPosition

func (e *Escpos) SetHRIPosition(p uint8) (int, error)

SetHRIPosition sets the position of the HRI (Human Readable Interpretation) characters Use the HRIPosition constants

func (*Escpos) SetJustify

func (e *Escpos) SetJustify(j Justify) (int, error)

SetJustify sets the justification for text Use JustifyLeft, JustifyCenter, or JustifyRight constants

func (*Escpos) SetLineSpacing

func (e *Escpos) SetLineSpacing(p uint8) (int, error)

SetLineSpacing sets the line spacing to p/180 inch (ESC/POS)

func (*Escpos) SetMotionUnits

func (e *Escpos) SetMotionUnits(x, y uint8) (int, error)

SetMotionUnits sets the horizontal (x) and vertical (y) motion units x: horizontal motion unit (25.4/x mm) y: vertical motion unit (25.4/y mm)

func (*Escpos) SetReverse

func (e *Escpos) SetReverse(r bool) (int, error)

SetReverse sets the reverse printing mode Use true for reverse, false for normal

func (*Escpos) SetRotate

func (e *Escpos) SetRotate(r bool) (int, error)

SetRotate sets the 90° clockwise rotation Use true for rotated, false for normal

func (*Escpos) SetSize

func (e *Escpos) SetSize(height, width uint8) (int, error)

SetSize sets the font size by specifying both height and width (1-8) The function applies the corresponding byte value based on the formula: c = (2 << 3) * (width - 1) + (height - 1)

func (*Escpos) SetUnderline

func (e *Escpos) SetUnderline(u uint8) (int, error)

SetUnderline sets the underline mode Use 0 for no underline, 1 for single underline, and 2 for double underline

func (*Escpos) SetUpsideDown

func (e *Escpos) SetUpsideDown(u bool) (int, error)

SetUpsideDown sets the upside-down mode Use true for upside-down, false for normal

func (*Escpos) UPCA

func (e *Escpos) UPCA(code string) (int, error)

UPCA prints a UPC-A barcode code must be 11-12 digits

func (*Escpos) UPCE

func (e *Escpos) UPCE(code string) (int, error)

UPCE prints a UPC-E barcode code must be 11-12 digits

func (*Escpos) Write

func (e *Escpos) Write(data string) (int, error)

Write prints a string using the current style settings. By default (Windows-1252 encoding set in New), accented characters like é, ç, à, ù, è are automatically converted from UTF-8 to the printer's active code page. The ESC t code-page command is re-sent before each write so the correct character set is always active, even after a call to Initialize() which resets the printer.

func (*Escpos) WriteGBK

func (e *Escpos) WriteGBK(data string) (int, error)

WriteGBK writes a string to the printer using GBK encoding (Simplified Chinese). Note: GBK-capable printers handle the character set switch internally; no ESC t code-page command is sent.

func (*Escpos) WriteRaw

func (e *Escpos) WriteRaw(data []byte) (int, error)

WriteRaw writes raw bytes directly to the printer

func (*Escpos) WriteRawWithEncoding

func (e *Escpos) WriteRawWithEncoding(data []byte, enc encoding.Encoding) (int, error)

WriteRawWithEncoding writes raw bytes to the printer after converting them from UTF-8 to the specified encoding

func (*Escpos) WriteWEU

func (e *Escpos) WriteWEU(data string) (int, error)

WriteWEU writes a string to the printer using Western European encoding (CP850). It sets code page PC850 on the printer before sending the encoded bytes.

func (*Escpos) WriteWithEncoding

func (e *Escpos) WriteWithEncoding(data string, enc encoding.Encoding, codepage uint8) (int, error)

WriteWithEncoding writes text after converting it from UTF-8 to the specified encoding and setting the appropriate code page on the printer (ESC t).

type Justify

type Justify uint8
const (
	JustifyLeft   Justify = 0
	JustifyCenter Justify = 1
	JustifyRight  Justify = 2
)

Justification constants

type Printer

type Printer interface {
	Read(p []byte) (n int, err error)
	Write(p []byte) (n int, err error)
	Close() error
}

func NewNetworkPrinter

func NewNetworkPrinter(address string, opts ...PrinterOption) (Printer, error)

type PrinterConfig

type PrinterConfig struct {
	DisableUnderline  bool
	DisableBold       bool
	DisableReverse    bool
	DisableRotate     bool
	DisableUpsideDown bool
	DisableJustify    bool
}

PrinterConfig contains options to disable specific formatting features

type PrinterOption added in v0.1.1

type PrinterOption func(*networkPrinter) error

PrinterOption defines a function that configures a network printer

func WithConnectTimeout added in v0.1.3

func WithConnectTimeout(d time.Duration) PrinterOption

WithConnectTimeout sets the timeout duration for the initial connection establishment

func WithDeadline added in v0.1.1

func WithDeadline(t time.Time) PrinterOption

WithDeadline sets both read and write deadlines to an absolute time Note: This sets a one-time deadline. For recurring timeouts, use WithTimeout instead.

func WithReadDeadline added in v0.1.1

func WithReadDeadline(t time.Time) PrinterOption

WithReadDeadline sets the deadline for future Read calls to an absolute time Note: This sets a one-time deadline. For recurring timeouts, use WithReadTimeout instead.

func WithReadTimeout added in v0.1.2

func WithReadTimeout(d time.Duration) PrinterOption

WithReadTimeout sets the timeout duration for Read operations

func WithTimeout added in v0.1.2

func WithTimeout(d time.Duration) PrinterOption

WithTimeout sets a timeout duration for all Read and Write operations

func WithWriteDeadline added in v0.1.1

func WithWriteDeadline(t time.Time) PrinterOption

WithWriteDeadline sets the deadline for future Write calls to an absolute time Note: This sets a one-time deadline. For recurring timeouts, use WithWriteTimeout instead.

func WithWriteTimeout added in v0.1.2

func WithWriteTimeout(d time.Duration) PrinterOption

WithWriteTimeout sets the timeout duration for Write operations

type Style

type Style struct {
	Bold          bool
	Width, Height uint8
	Reverse       bool
	Underline     uint8 // can be 0, 1 or 2
	UpsideDown    bool
	Rotate        bool
	Justify       Justify
}

Style defines the text formatting options for the printer

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址