escposimg

package module
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: May 10, 2026 License: MIT Imports: 11 Imported by: 0

README

escposimg

Go library and CLI tool for printing images with ESC/POS-compatible receipt printers.

Background / Motivation

Many receipt printers require control via Epson's ESC/POS protocol. Unlike most modern office printers, this approach doesn't involve sending complete document layouts (such as PDF or PostScript files), but rather individual control commands like "output text" or "cut paper". The actual rendering takes place on the device itself. Consequently, the usual document creation tools (Typst, Word, LaTeX, Affinity Publisher, etc.) cannot be employed for layout purposes.

A viable workaround is to rasterise the desired document into a monochrome (black and white) image and transmit it to the printer in this format. This is precisely what this library accomplishes. Since thermal printers can only produce black output, image files containing colours or greyscale tones must first be converted to monochrome format. To this end, the tool provides a selection of different dithering algorithms. The print data can be transmitted to the printer via network connection.

Whilst printer drivers exist for all common platforms that perform the same function, experience demonstrates that these are sometimes implemented differently (e.g., employing different dithering algorithms), resulting in the same document being printed differently across various platforms.

Usage

The escposimg tool provides both a command-line interface and a Go library for processing images and generating ESC/POS printer commands. Choose the approach that best suits your workflow.

Command-Line Interface

The CLI tool offers straightforward image processing with configurable options for various printer types and use cases.

Basic Usage

Process an image with default settings (80mm paper, 203 DPI, Floyd-Steinberg dithering):

escposimg -image photo.jpg

This command converts a photograph to ESC/POS format using standard settings and outputs the printer commands to the terminal.

Advanced Examples

High-quality printing with Atkinson dithering:

escposimg -image artwork.png -dithering atkinson -dpi 300 -debug-output

This example processes artwork at high resolution with Atkinson dithering, which preserves fine details, and saves a debug image to verify the result.

Legacy printer compatibility:

escposimg -image receipt.jpg -print-mode column -dpi 180 -paper-width 58

This command configures the tool for older thermal printers using column mode, lower resolution, and narrow 58mm paper format.

Output Methods

The CLI supports three distinct output methods for different deployment scenarios:

File Output (for batch processing or USB printers):

# Generate ESC/POS file
escposimg -image logo.png -output file -file-path printer_data.escpos

# Send to USB printer (Linux/macOS)
cat printer_data.escpos > /dev/usb/lp0

# Send to USB printer (alternative method)
lp -d thermal_printer -o raw printer_data.escpos

These commands first generate an ESC/POS file containing the printer commands, then demonstrate two methods for sending the file to a USB-connected thermal printer.

Network Output (direct TCP connection):

# Print directly to network printer
escposimg -image invoice.jpg -output network -network-addr 192.168.1.100:9100

This command establishes a direct TCP connection to a network printer and immediately sends the processed image data for printing.

Standard Output (for shell integration):

# Pipe to netcat for network printing
escposimg -image receipt.png | nc 192.168.1.100 9100

# Redirect to file for later use
escposimg -image document.jpg -cut > batch_print.escpos

# Chain with other commands
escposimg -image header.png -debug-text "Order #12345" | tee order_header.escpos | nc printer.local 9100

These examples demonstrate shell integration: piping directly to a network printer, saving output for later use, and creating a command chain that both saves and prints simultaneously.

Go Library

The library provides fine-grained control over image processing and printer communication within Go applications.

Basic Library Usage
package main

import (
    "log"
    "github.com/72nd/escposimg"
)

func main() {
    // Load default configuration (80mm, 203 DPI, Floyd-Steinberg)
    config := escposimg.DefaultConfig()
    
    // Create output method
    output := escposimg.NewStdoutOutput()
    
    // Process and print
    if err := escposimg.ProcessImage("receipt.jpg", config, output); err != nil {
        log.Fatal(err)
    }
}

This basic example demonstrates how to process an image with default settings and output the ESC/POS commands to standard output within a Go application.

Advanced Configuration
package main

import (
    "log"
    "github.com/72nd/escposimg"
)

func main() {
    // Custom configuration for 58mm receipt printer
    config := &escposimg.Config{
        PaperWidthMM:   escposimg.PaperWidth58mm,
        DPI:            escposimg.DPI203,
        DitheringAlgo:  escposimg.DitheringAtkinson,
        PrintMode:      escposimg.PrintModeRaster,
        DebugOutput:    true,
        DebugImagePath: "processed_image.png",
        DebugText:      "Store Receipt #1234",
        CutPaper:       true,
    }
    
    // Network printer output
    output, err := escposimg.NewNetworkOutput("192.168.1.100:9100")
    if err != nil {
        log.Fatal(err)
    }
    defer output.Close()
    
    // Process multiple images in sequence
    images := []string{"header.png", "content.jpg", "footer.png"}
    
    for _, imagePath := range images {
        if err := escposimg.ProcessImage(imagePath, config, output); err != nil {
            log.Printf("Failed to process %s: %v", imagePath, err)
        }
    }
}

This advanced example shows how to configure the library for a specific printer type (58mm), enable debug features, and process multiple images sequentially over a network connection.

Production Integration Example
package main

import (
    "fmt"
    "log"
    "github.com/72nd/escposimg"
)

func PrintOrderReceipt(orderID string, logoPath string, printerIP string) error {
    // Configure for standard receipt printer
    config := &escposimg.Config{
        PaperWidthMM:  escposimg.PaperWidth80mm,
        DPI:           escposimg.DPI203,
        DitheringAlgo: escposimg.DitheringFloydSteinberg,
        PrintMode:     escposimg.PrintModeRaster,
        DebugText:     fmt.Sprintf("Order: %s", orderID),
        CutPaper:      true,
    }
    
    // Establish printer connection
    printer, err := escposimg.NewNetworkOutput(printerIP + ":9100")
    if err != nil {
        return fmt.Errorf("printer connection failed: %w", err)
    }
    defer printer.Close()
    
    // Process company logo
    if err := escposimg.ProcessImage(logoPath, config, printer); err != nil {
        return fmt.Errorf("logo printing failed: %w", err)
    }
    
    return nil
}

This production-ready function demonstrates error handling, configuration management, and network printer integration for printing order receipts with company logos in a commercial application.

Available Options

Command-Line Parameters
Parameter Type Default Description
-image string required Path to the input image file
-paper-width int 80 Paper width in millimetres (58, 80, etc.)
-dpi int 203 Printer resolution in dots per inch
-dithering string floyd-steinberg Dithering algorithm (see table below)
-print-mode string raster ESC/POS printing mode (raster, graphics, column)
-debug-output bool false Save processed image for debugging
-debug-image string debug_output.png Path for debug image output
-debug-text string `` Optional text printed before image
-cut bool false Send paper cut command after printing
-output string stdout Output method (stdout, network, file)
-network-addr string `` Network address for network output
-file-path string `` File path for file output
-verbose bool false Enable detailed logging
-version bool false Display version information
Library Configuration Options
Field Type Default Description
PaperWidthMM int 80 Paper width in millimetres
DPI int 203 Printer dots per inch
DitheringAlgo DitheringType DitheringFloydSteinberg Algorithm for monochrome conversion
PrintMode PrintMode PrintModeRaster ESC/POS command structure
DebugOutput bool false Generate debug image files
DebugImagePath string debug_output.png Debug image save location
DebugText string `` Text printed before image
CutPaper bool false Automatic paper cutting
Dithering Algorithms
Algorithm CLI Value Description Best For
Floyd-Steinberg floyd-steinberg Error diffusion with excellent quality Photographs, general use
Atkinson atkinson Lighter error diffusion, preserves highlights Fine details, line art
Threshold threshold Simple binary conversion, fastest processing High-contrast images, speed
Bayer bayer Ordered dithering with regular patterns Textures, consistent patterns
Burkes burkes Error diffusion with wider distribution Complex images, varied tones
Sierra Lite sierra-lite Balanced error diffusion General purpose, moderate quality
Jarvis-Judice-Ninke jarvis-judice-ninke Comprehensive error diffusion High-quality output, detailed images
Shadura shadura Optimised for thermal printer characteristics Thermal printing, bitmap graphics
Print Modes
Mode CLI Value Description Compatibility
Raster raster Modern GS v 0 command, efficient single-command printing Modern thermal printers (post-2010)
Graphics graphics Advanced GS ( L command, extended features Modern ESC/POS printers with graphics support
Column column Legacy ESC * command, line-by-line processing All ESC/POS printers, including vintage models
Common DPI Values
DPI Description Use Case
180 Lower resolution Older printers, faster processing
203 Standard resolution Most thermal printers, balanced quality
300 High resolution Photo-quality printing, detailed graphics
Paper Widths
Width (mm) Description Typical Use
58 Narrow format Small receipt printers, mobile devices
80 Standard format Retail receipts, standard thermal printers

Documentation

Overview

Package escposimg provides functionality to process images for ESC/POS thermal printers. It supports loading PNG, JPEG, and Netpbm images; applying dithering (skipped for PBM); scaling to paper width; and generating ESC/POS commands for printing.

Index

Constants

View Source
const (
	ESC = 0x1B // Escape character
	GS  = 0x1D // Group separator
	LF  = 0x0A // Line feed
	CR  = 0x0D // Carriage return
)

ESC/POS command constants

View Source
const (
	DPI203 = 203 // Standard thermal printer DPI
	DPI300 = 300 // High quality thermal printer DPI
	DPI180 = 180 // Older thermal printer models
)

Common DPI values for thermal printers

View Source
const (
	PaperWidth58mm = 58
	PaperWidth72mm = 72
	PaperWidth80mm = 80
)

Common paper widths in millimeters

Variables

This section is empty.

Functions

func ApplyDithering

func ApplyDithering(img image.Image, algo DitheringType) (image.Image, error)

ApplyDithering applies the specified dithering algorithm to the image

func GenerateESCPOS

func GenerateESCPOS(img image.Image, config *Config) ([]byte, error)

GenerateESCPOS generates ESC/POS commands from a dithered image Supports raster mode (GS v 0), graphics mode (GS ( L), and column mode (ESC *)

func GenerateTestPattern

func GenerateTestPattern(width, height int) []byte

GenerateTestPattern generates a simple test pattern for debugging

func LoadImage

func LoadImage(imagePath string) (image.Image, error)

LoadImage loads an image from the specified file path. Supports PNG, JPEG, and Netpbm (pbm, pgm, ppm, pam).

func ProcessImage

func ProcessImage(imagePath string, config *Config, output OutputMethod) error

ProcessImage is the main function that processes an image and sends it to the specified output. It performs the complete pipeline: load → scale → dither → generate ESC/POS → output. PBM inputs skip dithering and use nearest-neighbor scaling to preserve bitmap edges.

func SaveDebugImage

func SaveDebugImage(img image.Image, path string) error

SaveDebugImage saves an image to the specified path for debugging purposes

func ScaleImage

func ScaleImage(img image.Image, targetWidth int) (image.Image, error)

ScaleImage scales an image to the specified width while maintaining aspect ratio. Uses Lanczos3 interpolation for high quality scaling.

func ScaleImageInterp

func ScaleImageInterp(img image.Image, targetWidth int, interp resize.InterpolationFunction) (image.Image, error)

ScaleImageInterp scales an image to the target width while maintaining aspect ratio, using the given nfnt/resize interpolation (e.g. Lanczos3 or NearestNeighbor).

func Version

func Version() string

Version returns the current version of the escposimg library

Types

type Config

type Config struct {
	// Paper width in millimeters (default: 80mm)
	PaperWidthMM int

	// Printer DPI (default: 203 DPI)
	DPI int

	// Dithering algorithm to use
	DitheringAlgo DitheringType

	// ESC/POS printing mode for images (default: PrintModeRaster).
	//
	// Determines which ESC/POS command sequence to use for image printing:
	// - PrintModeRaster: Modern GS v 0 command, efficient, single command
	// - PrintModeGraphics: Advanced GS ( L command, extended features
	// - PrintModeColumn: Legacy ESC * command, compatible, line-by-line
	//
	// Use PrintModeRaster for modern printers, PrintModeGraphics for advanced
	// features, or PrintModeColumn for legacy compatibility.
	PrintMode PrintMode

	// Save dithered image for debugging
	DebugOutput bool

	// Path to save debug image (if DebugOutput is true)
	DebugImagePath string

	// Optional debug text to print before image
	DebugText string

	// Send paper cut command after printing
	CutPaper bool
}

Config holds the configuration for image processing and printing

func DefaultConfig

func DefaultConfig() *Config

DefaultConfig returns a configuration with sensible defaults

func (*Config) CalculatePixelWidth

func (c *Config) CalculatePixelWidth() int

CalculatePixelWidth calculates the pixel width based on paper width and DPI

type DitheringType

type DitheringType int

DitheringType represents the available dithering algorithms

const (
	DitheringFloydSteinberg DitheringType = iota
	DitheringAtkinson
	DitheringThreshold
	DitheringBayer
	DitheringBurkes
	DitheringSierraLite
	DitheringJarvisJudiceNinke
	DitheringShadura
	// DitheringNone converts each pixel to black or white with a fixed threshold only
	// (no error diffusion, no ordered dither matrix). Same implementation as DitheringThreshold.
	DitheringNone
)

func (DitheringType) String

func (d DitheringType) String() string

String returns the string representation of the dithering type

type FileOutput

type FileOutput struct {
	// contains filtered or unexported fields
}

FileOutput writes data to a file

func NewFileOutput

func NewFileOutput(filePath string) (*FileOutput, error)

NewFileOutput creates a new file output method

func (*FileOutput) Close

func (f *FileOutput) Close() error

Close closes the file

func (*FileOutput) Write

func (f *FileOutput) Write(data []byte) error

Write writes data to the file

type LoadImageResult

type LoadImageResult struct {
	// Image is the decoded bitmap.
	Image image.Image

	// Format is the string returned by image.Decode (e.g. "png", "jpeg", "pbm").
	Format string

	// SkipDithering is true when the source is portable bitmap (PBM); error diffusion is not applied.
	SkipDithering bool
}

LoadImageResult holds a decoded image and hints derived from the file format.

func LoadImageDetails

func LoadImageDetails(imagePath string) (LoadImageResult, error)

LoadImageDetails loads an image and reports format-specific processing hints. Supports PNG, JPEG, and Netpbm family (pbm, pgm, ppm, pam) via github.com/spakin/netpbm.

type NetworkOutput

type NetworkOutput struct {
	// contains filtered or unexported fields
}

NetworkOutput writes data to a network connection

func NewNetworkOutput

func NewNetworkOutput(address string) (*NetworkOutput, error)

NewNetworkOutput creates a new network output method

func (*NetworkOutput) Close

func (n *NetworkOutput) Close() error

Close closes the network connection

func (*NetworkOutput) Write

func (n *NetworkOutput) Write(data []byte) error

Write writes data to the network connection

type OutputMethod

type OutputMethod interface {
	Write(data []byte) error
	Close() error
}

OutputMethod defines the interface for different output methods

type PrintMode

type PrintMode int

PrintMode defines the ESC/POS printing mode for images.

ESC/POS supports three main approaches for printing bitmap images: - Raster mode (GS v 0): Modern, efficient, single command per image - Graphics mode (GS ( L): Advanced graphics with extended features - Column mode (ESC *): Legacy compatible, line-by-line processing

All modes produce identical visual output when using the same dithering algorithm, but differ in command structure and printer compatibility.

const (
	// PrintModeRaster uses the GS v 0 command (Print Raster Bit Image).
	//
	// This is the modern standard for thermal printers and is recommended
	// for most use cases. The entire image is sent as a single command,
	// making it more efficient for large images and network printing.
	//
	// Command format: GS v 0 m xL xH yL yH [data]
	//
	// Best for:
	// - Modern thermal printers (post-2010)
	// - Network/Ethernet connections
	// - High-volume printing
	// - Large or high-resolution images
	//
	// Compatibility: Most modern ESC/POS printers support this mode.
	PrintModeRaster PrintMode = iota

	// PrintModeGraphics uses the GS ( L command (Graphics Mode).
	//
	// This is an advanced graphics mode that provides extended functionality
	// for modern thermal printers. It supports more complex graphics operations
	// and may offer better quality or performance on compatible printers.
	//
	// Command format: GS ( L pL pH fn [parameters] [data]
	//
	// Best for:
	// - Modern thermal printers with graphics support
	// - Advanced formatting requirements
	// - Applications requiring extended graphics features
	//
	// Compatibility: Supported by modern ESC/POS printers that implement
	// the extended graphics command set.
	PrintModeGraphics

	// PrintModeColumn uses the ESC * command (Column/Bit Image Mode).
	//
	// This is the traditional approach that processes images in 8-pixel
	// height bands, sending one command per band. While less efficient
	// than raster mode, it offers better compatibility with older printers.
	//
	// Command format: ESC * m nL nH [data] (repeated for each 8-pixel band)
	//
	// Best for:
	// - Legacy thermal printers (pre-2010)
	// - Serial/RS232 connections
	// - Compatibility troubleshooting
	// - Printers that don't support GS v 0 or GS ( L
	//
	// Compatibility: Supported by virtually all ESC/POS printers,
	// including very old models.
	PrintModeColumn
)

func (PrintMode) String

func (p PrintMode) String() string

String returns the string representation of the print mode. Returns "raster" for PrintModeRaster, "graphics" for PrintModeGraphics, "column" for PrintModeColumn, or "unknown" for invalid values.

type StdoutOutput

type StdoutOutput struct{}

StdoutOutput writes data to stdout

func NewStdoutOutput

func NewStdoutOutput() *StdoutOutput

NewStdoutOutput creates a new stdout output method

func (*StdoutOutput) Close

func (s *StdoutOutput) Close() error

Close is a no-op for stdout

func (*StdoutOutput) Write

func (s *StdoutOutput) Write(data []byte) error

Write writes data to stdout

Directories

Path Synopsis
cmd
escposimg command
Package main demonstrates basic usage of the escposimg library.
Package main demonstrates basic usage of the escposimg library.

Jump to

Keyboard shortcuts

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