ThermalPrinter’s documentation

Python module to manage the DP-EH600 thermal printer (the one sold by AdaFruit).

Content

Printers

Known printers to be supported:

  • DP-EH600

  • DP-EH400/1 (via #17)

If you had success with another printer, please tell us :)

Installation

Quite simple:

python -m pip install -U thermalprinter

From sources

Alternatively, you can get a copy of the module from GitHub.

  1. Clone the repository:

git clone https://github.com/BoboTiG/thermalprinter.git
cd thermalprinter
  1. Install them module:

python -m pip install -e .

Setup

Raspberry Pi

Note : tested on Raspberry Pi 2 and 3.

  1. Ensure that ttyAMA0 is not used for serial console access. Edit the file /boot/cmdline.txt to remove all name-value pairs containing ttyAMA0.

  2. Add the user to the dialout group:

sudo usermod -a -G dialout $USER
  1. Reboot.

Beagle Bone

Note : documentation retrieved from luopio/py-thermal-printer and has not been tested.

# Mux settings
echo 1 > /sys/kernel/debug/omap_mux/spi0_sclk
echo 1 > /sys/kernel/debug/omap_mux/spi0_d0

Other?

If you work with another hardware, please tell us :)

Usage

An example is better than thousands words:

from PIL import Image
from ThermalPrinter import *

with ThermalPrinter(port="/dev/ttyAMA0") as printer:
    # Picture
    printer.image(Image.open("gnu.png"))

    # Bar codes
    printer.barcode_height(80)
    printer.barcode_position(BarCodePosition.BELOW)
    printer.barcode_width(3)
    printer.barcode("012345678901", BarCode.EAN13)

    # Styles
    printer.out("Bold", bold=True)
    printer.out("Double height", double_height=True)
    printer.out("Double width", double_width=True)
    printer.out("Inverse", inverse=True)
    printer.out("Rotate 90°", rotate=True, codepage=CodePage.ISO_8859_1)
    printer.out("Strike", strike=True)
    printer.out("Underline", underline=1)
    printer.out("Upside down", upside_down=True)

    # Chinese (almost all alphabets exist)
    printer.out("现代汉语通用字表", chinese=True,
                chinese_format=Chinese.UTF_8)

    # Greek (excepted the ΐ character)
    printer.out("Στην υγειά μας!", codepage=CodePage.CP737)

    # Other characters
    printer.out(b"Cards \xe8 \xe9 \xea \xeb", codepage=CodePage.CP932)

    # Accents
    printer.out("Voilà !", justify="C", strike=True,
                underline=2, codepage=CodePage.ISO_8859_1)

    # Line feeds
    printer.feed(2)

Instance the class

Import the module:

from thermalprinter import ThermalPrinter

So the module can be used as simply as:

with ThermalPrinter() as printer:
    # ...

Or:

printer = ThermalPrinter()

Tools

Few helpers, and they are free :)

Constants

thermalprinter.tools.ls(*constants: Any) None

Print constants values.

Parameters

*constants (list) – constant(s) to print.

Examples.

Print all constants:

>>> ls()

You can print only constants you want too:

>>> from thermalprinter.constants import Chinese, CodePage
>>> # Print Chinese values
>>> ls(Chinese)
>>> # Print Chinese and CodePage values
>>> ls(Chinese, CharSet)

Tests

thermalprinter.tools.printer_tests(printer: Optional[ThermalPrinter] = None, raise_on_error: bool = True) None

Send to the printer several insctructions to test every printing functions.

Parameters
  • printer (ThermalPrinter) – optional printer to use for printer_tests.

  • raise_on_error (bool) – raise on error.

Changed in version 0.2.0: Removed port and heat_time arguments. Added printer and raise_on_error arguments.

Example:

>>> from thermalprinter.tools import printer_tests
>>> printer_tests()
>>> printer = ThermalPrinter(port='/dev/ttyS0', heat_time=120)
>>> printer_tests(printer=printer)

Code pages

thermalprinter.tools.print_char(char: str, printer: Optional[ThermalPrinter] = None) None

Test one character with all possible code page.

Parameters
  • char (str) – character to print.

  • printer (ThermalPrinter) – optional printer to use for printer_tests.

Say you are looking for the good code page to print a sequence, you can print it using every code pages:

>>> print_char("现")

This function is as simple as:

>>> for codepage in list(CodePage):
...    printer.out(printer.out(f"{codepage.name}: {char}"))

Changed in version 0.2.0: Added printer argument.

Data validation

These are special functions to handle data validation. As it could take a lot of lines and logic, we prefered create them outsite the class to keep a light code for every ThermalPrinter’s methods.

thermalprinter.validate.validate_barcode(data: str, barcode_type: BarCode) None

Validate data against the bar code type.

Parameters
  • data (str) – data to print.

  • barecode_type (BarCode) – bar code type to use.

Raises
thermalprinter.validate.validate_barcode_position(position: BarCodePosition) None

Validate a bar code position.

Parameters

position (BarCodePosition) – the position to use.

Raises

ThermalPrinterConstantError – On bad position’s type.

thermalprinter.validate.validate_charset(charset: CharSet) None

Validate a charset.

Parameters

charset (CharSet) – new charset to use.

Raises

ThermalPrinterConstantError – On bad charset’s type.

thermalprinter.validate.validate_chinese_format(fmt: Chinese) None

Validate a Chinese format.

Parameters

fmt (Chinese) – new format to use.

Raises

ThermalPrinterConstantError – On bad fmt’s type.

thermalprinter.validate.validate_codepage(codepage: CodePage) None

Validate a code page.

Parameters

codepage (CodePage) – new code page to use.

Raises

ThermalPrinterConstantError – On bad codepage’s type.

API

Class

class thermalprinter.ThermalPrinter(port: str = '/dev/ttyAMA0', baudrate: int = 19200, command_timeout: float = 0.05, **kwargs: Any)
Parameters
  • port (str) – Serial port to use, known as the device name.

  • baudrate (int) – Baud rate such as 9600, or 115200 etc.

  • command_timeout (float) – Command timeout, in seconds.

  • **kwargs (dict) –

    Additionnal optional arguments:

    • heat_time (int): printer heat time (default: 80);

    • heat_interval (int): printer heat time interval (default: 12);

    • most_heated_point (int): for the printer, the most heated point (default: 3).

Raises

ThermalPrinterValueError – On incorrect argument’s type or value.

Methods

Bar codes

ThermalPrinter.barcode(data: str, barcode_type: BarCode) None

Bar code printing. All checks are done to ensure the data validity.

Parameters
  • data (str) – data to print.

  • barecode_type (BarCode) – bar code type to use.

Raises
ThermalPrinter.barcode_height(height: int = 162) None

Set bar code height.

Parameters

height (int) – bar code height (min=1, max=255).

Raises

ThermalPrinterValueError – On incorrect height’s type or value.

ThermalPrinter.barcode_left_margin(margin: int = 0) None

Set the left margin of the bar code.

Parameters

margin (int) – left margin (min=0, max=255).

Raises

ThermalPrinterValueError – On incorrect margin’s type or value.

ThermalPrinter.barcode_position(position: BarCodePosition = BarCodePosition.HIDDEN) None

Set the position of the text relative to the bar code.

Parameters

position (BarCodePosition) – the position to use.

Raises

ThermalPrinterConstantError – On bad position’s type.

ThermalPrinter.barcode_width(width: int = 3) None

Set the bar code width.

Parameters

width (int) – bar code with (min=2, max=6).

Raises

ThermalPrinterValueError – On incorrect width’s type or value.

Images

ThermalPrinter.image(image: Image) None

Print Image. Requires Python Imaging Library (pillow). Image will be cropped to 384 pixels width if necessary, and converted to 1-bit w/diffusion dithering. For any other behavior (scale, B&W threshold, etc.), use the Imaging Library to perform such operations before passing the result to this function.

Max width: 384px.

Parameters

image (Image) – the PIL Image to use.

Example:

>>> from PIL import Image
>>> printer.image(Image.open("picture.png"))

Text styling

ThermalPrinter.bold(state: bool = False) None

Turn emphasized mode on/off.

Parameters

state (bool) – new state.

ThermalPrinter.char_spacing(spacing: int = 0) None

Set the right character spacing.

Parameters

spacing (int) – spacing to use (min=0, max=255).

Raises

ThermalPrinterValueError – On incorrect spacing’s type or value.

ThermalPrinter.double_height(state: bool = False) None

Set double height mode.

Parameters

state (bool) – new state.

ThermalPrinter.double_width(state: bool = False) None

Select double width mode.

Parameters

state (bool) – new state.

ThermalPrinter.inverse(state: bool = False) None

Turn white/black reverse printing mode.

Parameters

state (bool) – new state.

ThermalPrinter.justify(value: str = 'L') None

Set text justification.

Parameters

value (str) – the new justification. L to align left. C to align center. R to align right.

Raises

ThermalPrinterValueError – On incorrect value’s type or value.

ThermalPrinter.left_margin(margin: int = 0) None

Set the left margin.

Parameters

margin (int) – the new margin (min=0, max=47).

Raises

ThermalPrinterValueError – On incorrect margin’s type or value.

ThermalPrinter.line_spacing(spacing: int = 30) None

Set line spacing.

Parameters

spacing (int) – the new spacing (min=0, max=255).

Raises

ThermalPrinterValueError – On incorrect spacing’s type or value.

ThermalPrinter.rotate(state: bool = False) None

Turn on/off clockwise rotation of 90°.

Parameters

state (bool) – new state.

ThermalPrinter.size(value: str = 'S') None

Set text size.

Parameters

value (str) – the new text size. S for small. M for medium (double height). L for large (double width and height).

Raises

ThermalPrinterValueError – On incorrect value’s type or value.

Note

This method affects max_column.

ThermalPrinter.strike(state: bool = False) None

Turn on/off double-strike mode.

Parameters

state (bool) – new state.

ThermalPrinter.underline(weight: int = 0) None

Turn underline mode on/off.

Parameters

weight (int) – the underline’s weight. 0 will turn off underline mode. 1 will turn on underline mode (1 dot thick). 2 will turns on underline mode (2 dots thick).

Raises

ThermalPrinterValueError – On incorrect weight’s type or value.

ThermalPrinter.upside_down(state: bool = False) None

Turns on/off upside-down printing mode.

Parameters

state (bool) – new state.

Encoding and charsets

ThermalPrinter.charset(charset: CharSet = CharSet.USA) None

Select an internal character set.

Parameters

charset (CharSet) – new charset to use.

Raises

ThermalPrinterConstantError – On bad charset’s type.

ThermalPrinter.codepage(codepage: CodePage = CodePage.CP437) None

Select character code table.

Parameters

codepage (CodePage) – new code page to use.

Raises

ThermalPrinterConstantError – On bad codepage’s type.

Chinese

ThermalPrinter.chinese(state: bool = False) None

Select/cancel Chinese mode.

Parameters

state (bool) – new state.

ThermalPrinter.chinese_format(fmt: Chinese = Chinese.GBK) None

Selection of the Chinese format.

Parameters

fmt (Chinese) – new format to use.

Raises

ThermalPrinterConstantError – On bad fmt’s type.

Printing

ThermalPrinter.feed(number: int = 1) None

Feeds by the specified number of lines.

Parameters

number (int) – number of lines (min=0, max=255).

Raises

ThermalPrinterValueError – On incorrect number’s type or value.

ThermalPrinter.out(data: Any, line_feed: bool = True, **kwargs: Any) None

Send one line to the printer.

Parameters
  • data (mixed) – the data to print.

  • line_feed (bool) – send a line break after the printed data.

  • kwargs (dict) – additional styles to apply.

You can pass formatting instructions directly via arguments:

>>> printer.out(data, justify="C", inverse=True)

This is a quicker way to do:

>>> printer.justify("C")
>>> printer.inverse(True)
>>> printer.out(data)
>>> printer.inverse(False)
>>> printer.justify("L")

Printer state

ThermalPrinter.offline() None

Take the printer offline. Print commands sent after this will be ignored until online() is called.

ThermalPrinter.online() None

Take the printer online. Subsequent print commands will be obeyed.

ThermalPrinter.sleep(seconds: int = 1) None

Put the printer into a low-energy state.

Parameters

seconds (int) – value to pass to the printer (min=0).

Raises

ThermalPrinterValueError – On incorrect seconds’s type or value.

ThermalPrinter.status(raise_on_error: bool = True) Dict[str, bool]

Check the printer status.

Parameters

raise_on_error (bool) – raise on error.

Raises

ThermalPrinterCommunicationError – If RX pin is not connected and if raise_on_error is True.

Return type

dict[str, bool]

Returns

A dict containing:

  • movement: False if the movement is not connected

  • paper: False if no paper

  • temp: False if the temperature exceeds 60°C

  • voltage: False if the voltage is higher than 9.5V

Changed in version 0.2.0: Added raise_on_error keyword argument.

ThermalPrinter.reset() None

Reset the printer to factory defaults.

ThermalPrinter.test() None

Print the test page (contains printer’s settings).

ThermalPrinter.wake() None

Wake up the printer.

Special methods

ThermalPrinter.flush(clear: bool = False) None

Remove the print data in buffer.

Parameters

clear (bool) – set to True to also clear the receive buffer.

ThermalPrinter.send_command(command: Command, *data: int) None

Raw byte-writing.

Parameters
  • command – command for the printer.

  • data – command arguments.

ThermalPrinter.to_bytes(data: Any) bytes

Convert data before sending to the printer.

Parameters

data (mixed) – any type of data to print.

Return bytes

the converted data in bytes

Attributes

All these attributes are read-only.

property ThermalPrinter.feeds: int

Number of printed line feeds since the start of the script.

property ThermalPrinter.is_online: bool

The printer online status.

property ThermalPrinter.is_sleeping: bool

The printer sleep status.

property ThermalPrinter.lines: int

Number of printed lines since the start of the script.

property ThermalPrinter.max_column: int

Number of printable characters on one line.

Exceptions

exception thermalprinter.exceptions.ThermalPrinterError

Base class for thermal printer exceptions..

exception thermalprinter.exceptions.ThermalPrinterCommunicationError

Exception that is raised on communication error with the printer.

exception thermalprinter.exceptions.ThermalPrinterConstantError

Exception that is raised on inexistant or out of range constant.

exception thermalprinter.exceptions.ThermalPrinterValueError

Exception that is raised on incorrect type or value passed to any method.

Constants

Bar codes types

enum thermalprinter.constants.BarCode(value)

Bar code types.

Valid values are as follows:

UPC_A = UPC_A  value: 65, 11 <= len(data) <=  12
UPC_E = UPC_E  value: 66, 11 <= len(data) <=  12
JAN13 = JAN13  value: 67, 12 <= len(data) <=  13
JAN8 = JAN8   value: 68,  7 <= len(data) <=   8
CODE39 = CODE39 value: 69,  1 <= len(data) <= 255
ITF = ITF    value: 70,  1 <= len(data) <= 255
CODABAR = CODABARvalue: 71,  1 <= len(data) <= 255
CODE93 = CODE93 value: 72,  1 <= len(data) <= 255
CODE128 = CODE128value: 73,  2 <= len(data) <= 255

Bar codes positions

enum thermalprinter.constants.BarCodePosition(value)

Bar code positions.

Valid values are as follows:

HIDDEN = HIDDEN value: 0
ABOVE = ABOVE  value: 1
BELOW = BELOW  value: 2
BOTH = BOTH   value: 3

Characters sets

enum thermalprinter.constants.CharSet(value)

Character sets.

Valid values are as follows:

USA = USA            value:  0
FRANCE = FRANCE         value:  1
GERMANY = GERMANY        value:  2
UK = UK             value:  3
DENMARK = DENMARK        value:  4
SWEDEN = SWEDEN         value:  5
ITALY = ITALY          value:  6
SPAIN = SPAIN          value:  7
JAPAN = JAPAN          value:  8
NORWAY = NORWAY         value:  9
DENMARK2 = DENMARK2       value: 10
SPAIN2 = SPAIN2         value: 11
LATIN_AMERICAN = LATIN_AMERICAN value: 12
KOREA = KOREA          value: 13
SLOVENIA = SLOVENIA       value: 14
CHINA = CHINA          value: 15

Chinese formats

enum thermalprinter.constants.Chinese(value)

Chinese formats.

Valid values are as follows:

GBK = GBK   value: 0
UTF_8 = UTF_8 value: 1
BIG5 = BIG5  value: 3

Code pages

enum thermalprinter.constants.CodePage(value)

Character code tables.

Valid values are as follows:

CP437 = CP437       value:  0, desc: the United States of America, European standard
CP932 = CP932       value:  1, desc: Katakana
CP850 = CP850       value:  2, desc: Multi language
CP860 = CP860       value:  3, desc: Portuguese
CP863 = CP863       value:  4, desc: Canada, French
CP865 = CP865       value:  5, desc: Western Europe
CYRILLIC = CYRILLIC    value:  6, desc: The Slavic language
CP866 = CP866       value:  7, desc: The Slavic 2
MIK = MIK         value:  8, desc: The Slavic / Bulgaria
CP755 = CP755       value:  9, desc: Eastern Europe, Latvia 2
IRAN = IRAN        value: 10, desc: Iran, Persia
CP862 = CP862       value: 15, desc: Hebrew
CP1252 = CP1252      value: 16, desc: Latin 1 [WCP1252]
CP1253 = CP1253      value: 17, desc: Greece [WCP1253]
CP852 = CP852       value: 18, desc: Latina 2
CP858 = CP858       value: 19, desc: A variety of language Latin 1 + Europe
IRAN2 = IRAN2       value: 20, desc: Persian
LATVIA = LATVIA      value: 21, desc:
CP864 = CP864       value: 22, desc: Arabic
ISO_8859_1 = ISO_8859_1  value: 23, desc: Western Europe
CP737 = CP737       value: 24, desc: Greece
CP1257 = CP1257      value: 25, desc: The Baltic Sea
THAI = THAI        value: 26, desc: Thai Wen
CP720 = CP720       value: 27, desc: Arabic
CP855 = CP855       value: 28, desc:
CP857 = CP857       value: 29, desc: Turkish
CP1250 = CP1250      value: 30, desc: Central Europe [WCP1250]
CP775 = CP775       value: 31, desc:
CP1254 = CP1254      value: 32, desc: Turkish [WCP1254]
CP1255 = CP1255      value: 33, desc: Hebrew [WCP1255]
CP1256 = CP1256      value: 34, desc: Arabic [WCP1256]
CP1258 = CP1258      value: 35, desc: Vietnamese [WCP1258]
ISO_8859_2 = ISO_8859_2  value: 36, desc: Latin 2
ISO_8859_3 = ISO_8859_3  value: 37, desc: Latin 3
ISO_8859_4 = ISO_8859_4  value: 38, desc: Baltic languages
ISO_8859_5 = ISO_8859_5  value: 39, desc: The Slavic language
ISO_8859_6 = ISO_8859_6  value: 40, desc: Arabic
ISO_8859_7 = ISO_8859_7  value: 41, desc: Greece
ISO_8859_8 = ISO_8859_8  value: 42, desc: Hebrew
ISO_8859_9 = ISO_8859_9  value: 43, desc: Turkish
ISO_8859_15 = ISO_8859_15 value: 44, desc: Latin 9
THAI2 = THAI2       value: 45, desc: Thai Wen 2
CP856 = CP856       value: 46, desc:
CP874 = CP874       value: 47, desc:

Code pages fallback

enum thermalprinter.constants.CodePageConverted(value)

Some code pages are not available on Python, so we use a little translation table.

Valid values are as follows:

MIK = MIK         fallback: iso8859-5
CP755 = CP755       fallback: utf-8
IRAN = IRAN        fallback: cp1256
LATVIA = LATVIA      fallback: iso8859-4
THAI = THAI        fallback: iso8859-11

If you find a better fit for one of the code page below, open an issue please (or send a patch).

Developers

Setup

  1. First, you need to fork the GitHub repository.

    Note : always work on a specific branch dedicated to your patch.

  2. Then, you could need the Embedded printer DP-EH600 Technical Manual and take a look at the features advancement.

  3. Finally, be sure to add/update tests and documentation within your patch.

Testing

Dependencies

Install required packages:

python -m pip install -e '.[tests]'

How to test?

python -m pytest

And you can test printing functions (if you added a styling method, you can add it to this function).

Validating the code

It is important to keep a clean base code. Use tools like flake8 and Pylint.

Dependencies

Install required packages:

python -m pip install -e '.[dev]'

How to validate?

./checks.sh

Documentation

Dependencies

Install required packages:

python -m pip install -e '.[docs]'

How to build?

sphinx-build --color -W -bhtml docs/source docs/output

Indices and tables