Python Escpos
Python Escpos
Release 3.0a1.dev1+ng5078c49
1 Description 1
2 Dependencies 3
4 Contributing 7
5 Content 9
i
ii
CHAPTER 1
Description
Python ESC/POS is a library which lets the user have access to all those printers handled by ESC/POS commands, as
defined by Epson, from a Python application.
The library tries to implement the functions provided by the ESC/POS-commandset and supports sending text, images,
barcodes and qr-codes to the printer.
Text can be aligned/justified and fonts can be changed by size, type and weight.
Also, this module handles some hardware functionalities like cutting paper, control characters, printer reset and similar
functions.
Since supported commands differ from printer to printer the software tries to automatically apply the right settings for
the printer that you set. These settings are handled by escpos-printer-db which is also used in escpos-php.
1
python-escpos Documentation, Release 3.0a1.dev1+ng5078c49
2 Chapter 1. Description
CHAPTER 2
Dependencies
3
python-escpos Documentation, Release 3.0a1.dev1+ng5078c49
4 Chapter 2. Dependencies
CHAPTER 3
5
python-escpos Documentation, Release 3.0a1.dev1+ng5078c49
Contributing
This project is open for any contribution! Please see CONTRIBUTING.rst for more information.
7
python-escpos Documentation, Release 3.0a1.dev1+ng5078c49
8 Chapter 4. Contributing
CHAPTER 5
Content
5.1 Installation
Installation should be rather straight-forward. python-escpos is on PyPi, so you can simply enter:
pip install python-escpos
This should install all necessary dependencies. Apart from that python-escpos should also be available as a Debian
package. If you want to always benefit from the newest stable releases you should probably install from PyPi.
1. Get the Product ID and Vendor ID from the lsusb command # lsusb Bus 002 Device 001: ID
1a2b:1a2b Device name
2. Create a udev rule to let users belonging to dialout group use the printer. You can create the file
/etc/udev/rules.d/99-escpos.rules and add the following: SUBSYSTEM=="usb",
ATTRS{idVendor}=="1a2b", ATTRS{idProduct}=="1a2b", MODE="0664",
GROUP="dialout" Replace idVendor and idProduct hex numbers with the ones that you got from
the previous step. Note that you can either, add yourself to “dialout” group, or use another group you already
belongs instead “dialout” and set it in the GROUP parameter in the above rule.
3. Restart udev # sudo service udev restart In some new systems it is done with # sudo udevadm
control --reload
python-escpos has a CLI with tab-completion. This is realised with argcomplete. In order for this to work you
have to enable tab-completion, which is described in the manual of argcomplete.
If you only want to enable it for python-escpos, or global activation does not work, try this:
eval "$(register-python-argcomplete python-escpos)"
9
python-escpos Documentation, Release 3.0a1.dev1+ng5078c49
5.2 Methods
The core part of this libraries API is the Escpos class. You use it by instantiating a printer which is a child of Escpos.
The following methods are available:
class escpos.escpos.Escpos(profile=None, magic_encode_args=None, **kwargs)
ESC/POS Printer object
This class is the abstract base class for an esc/pos-printer. The printer implementations are children of this class.
image(img_source, high_density_vertical=True, high_density_horizontal=True,
impl=u’bitImageRaster’, fragment_height=960)
Print an image
You can select whether the printer should print in high density or not. The default value is high density.
When printing in low density, the image will be stretched.
Esc/Pos supplies several commands for printing. This function supports three of them. Please try to vary
the implementations if you have any problems. For example the printer IT80-002 will have trouble aligning
images that are not printed in Column-mode.
The available printing implementations are:
•bitImageRaster: prints with the GS v 0-command
•graphics: prints with the GS ( L-command
•bitImageColumn: prints with the ESC *-command
Parameters
• img_source – PIL image or filename to load: jpg, gif, png or bmp
• high_density_vertical – print in high density in vertical direction default: True
• high_density_horizontal – print in high density in horizontal direction default:
True
• impl – choose image printing mode between bitImageRaster, graphics or bitImageCol-
umn
• fragment_height – Images larger than this will be split into multiple fragments de-
fault: 960
qr(content, ec=0, size=3, model=2, native=False)
Print QR Code for the provided string
Parameters
• content – The content of the code. Numeric data will be more efficiently compacted.
• ec – Error-correction level to use. One of QR_ECLEVEL_L (default),
QR_ECLEVEL_M, QR_ECLEVEL_Q or QR_ECLEVEL_H. Higher error correc-
tion results in a less compact code.
• size – Pixel size to use. Must be 1-16 (default 3)
• model – QR code model to use. Must be one of QR_MODEL_1, QR_MODEL_2 (de-
fault) or QR_MICRO (not supported by all printers).
10 Chapter 5. Content
python-escpos Documentation, Release 3.0a1.dev1+ng5078c49
• native – True to render the code on the printer, False to render the code as an image and
send it to the printer (Default)
charcode(code=u’AUTO’)
Set Character Code Table
Sets the control sequence from CHARCODE in escpos.constants as active. It will be sent with
the next text sequence. If you set the variable code to AUTO it will try to automatically guess the right
codepage. (This is the standard behaviour.)
Parameters code – Name of CharCode
Raises CharCodeError
barcode(code, bc, height=64, width=3, pos=u’BELOW’, font=u’A’, align_ct=True, func-
tion_type=None)
Print Barcode
This method allows to print barcodes. The rendering of the barcode is done by the printer and therefore
has to be supported by the unit. Currently you have to check manually whether your barcode text is
correct. Uncorrect barcodes may lead to unexpected printer behaviour. There are two forms of the barcode
function. Type A is default but has fewer barcodes, while type B has some more to choose from.
Todo
Add a method to check barcode codes. Alternatively or as an addition write explanations about each
barcode-type. Research whether the check digits can be computed autmatically.
Use the parameters height and width for adjusting of the barcode size. Please take notice that the barcode
will not be printed if it is outside of the printable area. (Which should be impossible with this method, so
this information is probably more useful for debugging purposes.)
Todo
On TM-T88II width from 1 to 6 is accepted. Try to acquire command reference and correct the code.
Todo
Supplying pos does not have an effect for every barcode type. Check and document for which types this is
true.
If you do not want to center the barcode you can call the method with align_ct=False, which will disable
automatic centering. Please note that when you use center alignment, then the alignment of text will be
changed automatically to centered. You have to manually restore the alignment if necessary.
Todo
If further barcode-types are needed they could be rendered transparently as an image. (This could also be
of help if the printer does not support types that others do.)
Parameters
• code – alphanumeric data to be printed as bar code
• bc – barcode format, possible values are for type A are:
5.2. Methods 11
python-escpos Documentation, Release 3.0a1.dev1+ng5078c49
– UPC-A
– UPC-E
– EAN13
– EAN8
– CODE39
– ITF
– NW7
Possible values for type B:
– All types from function type A
– CODE93
– CODE128
– GS1-128
– GS1 DataBar Omnidirectional
– GS1 DataBar Truncated
– GS1 DataBar Limited
– GS1 DataBar Expanded
If none is specified, the method raises BarcodeTypeError.
• height (int) – barcode height, has to be between 1 and 255 default: 64
• width (int) – barcode width, has to be between 2 and 6 default: 3
• pos – where to place the text relative to the barcode, default: BELOW
– ABOVE
– BELOW
– BOTH
– OFF
• font – select font (see ESC/POS-documentation, the device often has two fonts), default:
A
– A
– B
• align_ct (bool) – If this parameter is True the barcode will be centered. Otherwise
no alignment command will be issued.
• function_type – Choose between ESCPOS function type A or B, depending on
printer support and desired barcode. If not given, the printer will attempt to automati-
cally choose the correct function based on the current profile. default: A
Raises BarcodeSizeError, BarcodeTypeError, BarcodeCodeError
text(txt)
Print alpha-numeric text
The text has to be encoded in the currently selected codepage. The input text has to be encoded in unicode.
Parameters txt – text to be printed
12 Chapter 5. Content
python-escpos Documentation, Release 3.0a1.dev1+ng5078c49
Raises TextError
block_text(txt, font=None, columns=None)
Text is printed wrapped to specified columns
Text has to be encoded in unicode.
Parameters
• txt – text to be printed
• font – font to be used, can be a or :code‘b‘
• columns – amount of columns
Returns None
set(align=u’left’, font=u’a’, text_type=u’normal’, width=1, height=1, density=9, invert=False,
smooth=False, flip=False)
Set text properties by sending them to the printer
Parameters
• align – horizontal position for text, possible values are:
– CENTER
– LEFT
– RIGHT
default: LEFT
• font – font given as an index, a name, or one of the special values ‘a’ or ‘b’, refering to
fonts 0 and 1.
• text_type – text type, possible values are:
– B for bold
– U for underlined
– U2 for underlined, version 2
– BU for bold and underlined
– BU2 for bold and underlined, version 2
– NORMAL for normal text
default: NORMAL
• width – text width multiplier, decimal range 1-8, default: 1
• height – text height multiplier, decimal range 1-8, default: 1
• density – print density, value from 0-8, if something else is supplied the density remains
unchanged
• invert (bool) – True enables white on black printing, default: False
• smooth – True enables text smoothing. Effective on 4x4 size text and larger, default:
False
• flip – True enables upside-down printing, default: False
line_spacing(spacing=None, divisor=180)
Set line character spacing.
If no spacing is given, we reset it to the default.
5.2. Methods 13
python-escpos Documentation, Release 3.0a1.dev1+ng5078c49
There are different commands for setting the line spacing, using a different denominator:
‘+” line_spacing/360 of an inch, 0 <= line_spacing <= 255 ‘3’ line_spacing/180 of an inch, 0 <=
line_spacing <= 255 ‘A’ line_spacing/60 of an inch, 0 <= line_spacing <= 85
Some printers may not support all of them. The most commonly available command (using a divisor of
180) is chosen.
cut(mode=u’‘)
Cut paper.
Without any arguments the paper will be cut completely. With ‘mode=PART’ a partial cut will be at-
tempted. Note however, that not all models can do a partial cut. See the documentation of your printer for
details.
Todo
Check this function on TM-T88II.
14 Chapter 5. Content
python-escpos Documentation, Release 3.0a1.dev1+ng5078c49
panel_buttons(enable=True)
Controls the panel buttons on the printer (e.g. FEED)
When enable is set to False the panel buttons on the printer will be disabled. Calling the method with
enable=True or without argument will enable the panel buttons.
If panel buttons are enabled, the function of the panel button, such as feeding, will be executed upon
pressing the button. If the panel buttons are disabled, pressing them will not have any effect.
This command is effective until the printer is initialized, reset or power-cycled. The default is enabled
panel buttons.
Some panel buttons will always work, especially when printer is opened. See for more information the
manual of your printer and the escpos-command-reference.
Parameters enable – controls the panel buttons
Return type None
5.3 Printers
5.3.1 USB
The USB-class uses pyusb and libusb to communicate with USB-based printers. Note that this driver is not suited for
USB-to-Serial-adapters and similiar devices, but only for those implementing native USB.
class escpos.printer.Usb(idVendor, idProduct, timeout=0, in_ep=130, out_ep=1, *args, **kwargs)
USB printer
This class describes a printer that natively speaks USB.
inheritance:
Escpos Usb
5.3. Printers 15
python-escpos Documentation, Release 3.0a1.dev1+ng5078c49
open()
Search device on USB tree and set it as escpos device
close()
Release USB interface
5.3.2 Serial
This driver uses pyserial in order to communicate with serial devices. If you are using an USB-based adapter to
connect to the serial port, then you should also use this driver. The configuration is often based on DIP-switches that
you can set on your printer. For the hardware-configuration please refer to your printer’s manual.
class escpos.printer.Serial(devfile=u’/dev/ttyS0’, baudrate=9600, bytesize=8, timeout=1, par-
ity=’N’, stopbits=1, xonxoff=False, dsrdtr=True, *args, **kwargs)
Serial printer
This class describes a printer that is connected by serial interface.
inheritance:
Escpos Serial
5.3.3 Network
16 Chapter 5. Content
python-escpos Documentation, Release 3.0a1.dev1+ng5078c49
Then you should be able to attach to port 4242 with this class. Otherwise the normal usecase would be to have
a printer with ethernet interface. This type of printer should work the same with this class. For the address of
the printer check its manuals.
inheritance:
Escpos Network
Troubleshooting
Problems with a network-attached printer can have numerous causes. Make sure that your device has a proper IP
address. Often you can check the IP address by triggering the self-test of the device. As a next step try to send text
manually to the device. You could use for example:
echo "OK\n" | nc IPADDRESS 9100
# the port number is often 9100
As a last resort try to reset the interface of the printer. This should be described in its manual.
5.3.4 File
This printer “prints” just into a file-handle. Especially on *nix-systems this comes very handy.
class escpos.printer.File(devfile=u’/dev/usb/lp0’, auto_flush=True, *args, **kwargs)
Generic file printer
5.3. Printers 17
python-escpos Documentation, Release 3.0a1.dev1+ng5078c49
This class is used for parallel port printer or other printers that are directly attached to the filesystem. Note
that you should stay away from using USB-to-Parallel-Adapter since they are unreliable and produce arbitrary
errors.
inheritance:
Escpos File
5.3.5 Dummy
The Dummy-printer is mainly for testing- and debugging-purposes. It stores all of the “output” as raw ESC/POS in a
string and returns that.
class escpos.printer.Dummy(*args, **kwargs)
Dummy printer
This class is used for saving commands to a variable, for use in situations where there is no need to send
commands to an actual printer. This includes generating print jobs for later use, or testing output.
inheritance:
Escpos Dummy
output
Get the data that was sent to this printer
5.4 Raspberry Pi
18 Chapter 5. Content
python-escpos Documentation, Release 3.0a1.dev1+ng5078c49
Warning: You should never directly connect an printer with RS232-interface (serial port) directly to a Raspberry
PI or similar interface (e.g. those simple USB-sticks without encasing). Those interfaces are based on 5V- or
3,3V-logic (the latter in the case of Raspberry PI). Classical RS232 uses 12V-logic and would thus destroy your
interface. Connect both systems with an appropriate level shifter.
5.4.1 Dependencies
5.4.2 Installation
5.4.3 Run
Now you can attach your printer and and test it with the example code in the project’s set of examples. You can find
that in the project-repository.
For more details on this check the installation-manual.
5.5 TODO
5.5.1 Introduction
python-escpos is the initial idea, from here we can start to build a robust library to get most of the ESC/POS printers
working with this library.
Eventually, this library must be able to cover almost all the defined models detailed in the ESC/POS Command
Specification Manual.
5.5.2 Details
Testing
5.5. TODO 19
python-escpos Documentation, Release 3.0a1.dev1+ng5078c49
Design
• Add all those sequences which are not common, but part of the ESC/POS Command Specifications.
– Port to Python 3
– Windows compatibility (hidapi instead libusb?)
– PDF417 support
• use something similar to the capabilities in escpos-php
Todo
Add a method to check barcode codes. Alternatively or as an addition write explanations about each barcode-type.
Research whether the check digits can be computed autmatically.
Todo
On TM-T88II width from 1 to 6 is accepted. Try to acquire command reference and correct the code.
Todo
Supplying pos does not have an effect for every barcode type. Check and document for which types this is true.
Todo
If further barcode-types are needed they could be rendered transparently as an image. (This could also be of help if
the printer does not support types that others do.)
Todo
Check this function on TM-T88II.
20 Chapter 5. Content
python-escpos Documentation, Release 3.0a1.dev1+ng5078c49
Todo
Add a method to check barcode codes. Alternatively or as an addition write explanations about each barcode-type.
Research whether the check digits can be computed autmatically.
Todo
On TM-T88II width from 1 to 6 is accepted. Try to acquire command reference and correct the code.
Todo
Supplying pos does not have an effect for every barcode type. Check and document for which types this is true.
Todo
If further barcode-types are needed they could be rendered transparently as an image. (This could also be of help if
the printer does not support types that others do.)
Todo
Add a method to check barcode codes. Alternatively or as an addition write explanations about each barcode-type.
Research whether the check digits can be computed autmatically.
Todo
On TM-T88II width from 1 to 6 is accepted. Try to acquire command reference and correct the code.
5.5. TODO 21
python-escpos Documentation, Release 3.0a1.dev1+ng5078c49
Todo
Supplying pos does not have an effect for every barcode type. Check and document for which types this is true.
Todo
If further barcode-types are needed they could be rendered transparently as an image. (This could also be of help if
the printer does not support types that others do.)
Todo
Check this function on TM-T88II.
5.6 Usage
USB printer
Before creating your Python ESC/POS printer instance, consult the system to obtain the printer parameters. This is
done with the ‘lsusb’ command.
Run the command and look for the “Vendor ID” and “Product ID” and write down the values. These values are
displayed just before the name of the device with the following format:
xxxx:xxxx
Example:
# lsusb
Bus 002 Device 001: ID 04b8:0202 Epson ...
Write down the the values in question, then issue the following command so you can get the “Interface” number and
“End Point”
22 Chapter 5. Content
python-escpos Documentation, Release 3.0a1.dev1+ng5078c49
The first command will yield the “Interface” number that must be handy to have and the second yields the “Output
Endpoint” address.
USB Printer initialization
Epson = printer.Usb(0x04b8,0x0202)
By default the “Interface” number is “0” and the “Output Endpoint” address is “0x01”. If you have other values
then you can define them on your instance. So, assuming that we have another printer where in_ep is on 0x81 and
out_ep=0x02, then the printer definition should look like:
Generic USB Printer initialization
Generic = printer.Usb(0x1a2b,0x1a2b,0,0x81,0x02)
Network printer
You only need the IP of your printer, either because it is getting its IP by DHCP or you set it manually.
Network Printer initialization
Epson = printer.Network("192.168.1.99")
Serial printer
Most of the default values set by the DIP switches for the serial printers, have been set as default on the serial printer
class, so the only thing you need to know is which serial port the printer is connected to.
Serial printer initialization
Epson = printer.Serial("/dev/tty0")
Other printers
Some printers under /dev can’t be used or initialized with any of the methods described above. Usually, those are
printers used by printcap, however, if you know the device name, you could try to initialize by passing the device node
name.
Epson = printer.File("/dev/usb/lp1")
The default is “/dev/usb/lp0”, so if the printer is located on that node, then you don’t necessary need to pass the node
name.
The following example demonstrates how to initialize the Epson TM-TI88IV on a USB interface.
5.6. Usage 23
python-escpos Documentation, Release 3.0a1.dev1+ng5078c49
You can create a configuration file for python-escpos. This will allow you to use the CLI, and skip some setup when
using the library programmatically.
The default configuration file is named config.yaml and uses the YAML format. For windows it is probably at:
%appdata%/python-escpos/config.yaml
If it can’t find the configuration file in the default location, it will tell you where it’s looking. You can always pass a
path, or a list of paths, to the load() method.
To load the configured printer, run:
from escpos import config
c = config.Config()
printer = c.printer()
24 Chapter 5. Content
python-escpos Documentation, Release 3.0a1.dev1+ng5078c49
printer:
type: network
host: 127.0.0.1
port: 9000
Python-escpos is designed to accept unicode. So make sure that you use u’strings’ or import
unicode_literals from __future__ if you are on Python 2. On Python 3 you should be fine.
For normal usage you can simply pass your text to the printers text()-function. It will automatically guess the right
codepage and then send the encoded data to the printer. If this feature does not work, please try to isolate the error and
then create an issue on the Github project page.
If you want or need to you can manually set the codepage. For this please use the charcode()-function. You
can set any key-value that is in CHARCODE. If something is wrong, an CharCodeError will be raised. After you
have manually set the codepage the printer won’t change it anymore. You can revert to normal behaviour by setting
charcode to AUTO.
Imagine you have a file with ESC/POS-commands in binary form. This could be useful for testing capabilities of your
printer with a known working combination of commands. You can print this data with the following code, using the
standard methods of python-escpos. (This is an advantage of the fact that _raw() accepts binary strings.)
from escpos import printer
p = printer.Serial() # adapt this to your printer model
file = open("binary-blob.bin", "rb") # read in the file containing your commands in binary-mode
data = file.read()
file.close()
p._raw(data)
That’s all, the printer should then print your data. You can also use this technique to let others reproduce an issue that
you have found. (Just “print” your commands to a File-printer on your local filesystem.) However, please keep in
mind, that often it is easier and better to just supply the code that you are using.
Here you can download an example, that will print a set of common barcodes:
• barcode.bin by @mike42
Printing images directly to the printer is rather slow. One factor that slows down the process is the transmission over
e.g. serial port.
Apart from configuring your printer to use the maximum baudrate (in the case of serial-printers), there is not much
that you can do. However you could use the escpos.printer.Dummy-printer to preprocess your image. This is
probably best explained by an example:
from escpos.printer import Serial, Dummy
p = Serial()
d = Dummy()
5.6. Usage 25
python-escpos Documentation, Release 3.0a1.dev1+ng5078c49
# create ESC/POS for the print job, this should go really fast
d.text("This is my image:\n")
d.image("funny_cat.png")
d.cut()
This way you could also store the code in a file and print it later. You could then for example print the code from
another process than your main-program and thus reduce the waiting time. (Of course this will not make the printer
print faster.)
5.7.1 barcode-method
The barcode-method is rather low-level and orients itself on the implementation of ESC/POS. In the future this class
could be supplemented by a high-level class that helps the user generating the payload.
Escpos.barcode(code, bc, height=64, width=3, pos=u’BELOW’, font=u’A’, align_ct=True, func-
tion_type=None)
Print Barcode
This method allows to print barcodes. The rendering of the barcode is done by the printer and therefore has to
be supported by the unit. Currently you have to check manually whether your barcode text is correct. Uncorrect
barcodes may lead to unexpected printer behaviour. There are two forms of the barcode function. Type A is
default but has fewer barcodes, while type B has some more to choose from.
Todo
Add a method to check barcode codes. Alternatively or as an addition write explanations about each barcode-
type. Research whether the check digits can be computed autmatically.
Use the parameters height and width for adjusting of the barcode size. Please take notice that the barcode will
not be printed if it is outside of the printable area. (Which should be impossible with this method, so this
information is probably more useful for debugging purposes.)
Todo
On TM-T88II width from 1 to 6 is accepted. Try to acquire command reference and correct the code.
Todo
Supplying pos does not have an effect for every barcode type. Check and document for which types this is true.
26 Chapter 5. Content
python-escpos Documentation, Release 3.0a1.dev1+ng5078c49
If you do not want to center the barcode you can call the method with align_ct=False, which will disable
automatic centering. Please note that when you use center alignment, then the alignment of text will be changed
automatically to centered. You have to manually restore the alignment if necessary.
Todo
If further barcode-types are needed they could be rendered transparently as an image. (This could also be of
help if the printer does not support types that others do.)
Parameters
• code – alphanumeric data to be printed as bar code
• bc – barcode format, possible values are for type A are:
– UPC-A
– UPC-E
– EAN13
– EAN8
– CODE39
– ITF
– NW7
Possible values for type B:
– All types from function type A
– CODE93
– CODE128
– GS1-128
– GS1 DataBar Omnidirectional
– GS1 DataBar Truncated
– GS1 DataBar Limited
– GS1 DataBar Expanded
If none is specified, the method raises BarcodeTypeError.
• height (int) – barcode height, has to be between 1 and 255 default: 64
• width (int) – barcode width, has to be between 2 and 6 default: 3
• pos – where to place the text relative to the barcode, default: BELOW
– ABOVE
– BELOW
– BOTH
– OFF
• font – select font (see ESC/POS-documentation, the device often has two fonts), default:
A
– A
– B
• align_ct (bool) – If this parameter is True the barcode will be centered. Otherwise no
alignment command will be issued.
• function_type – Choose between ESCPOS function type A or B, depending on printer
support and desired barcode. If not given, the printer will attempt to automatically choose
the correct function based on the current profile. default: A
Raises BarcodeSizeError, BarcodeTypeError, BarcodeCodeError
5.7.2 CODE128
Code128 barcodes need a certain format. For now the user has to make sure that the payload is correct. For alphanu-
meric CODE128 you have to preface your payload with {B.
from escpos.printer import Dummy, Serial
p = Serial()
# print CODE128 012ABCDabcd
p.barcode("{B012ABCDabcd", "CODE128", function_type="B")
5.8 Contributing
This project is open to any kind of contribution. You can help with improving the documentation, adding fixes to the
code, providing test cases in code or as a description or just spreading the word. Please feel free to create an issue or
pull request. In order to reduce the amount of work for everyone please try to adhere to good practice.
The pull requests and issues will be prefilled with templates. Please fill in your information where applicable.
This project uses semantic versioning and tries to adhere to the proposed rules as well as possible.
5.8.1 Style-Guide
Python 2 and 3
We have rewritten the code in order to maintain compatibility with both Python 2 and Python 3. In order to ensure that
we do not miss any accidental degradation, please add these imports to the top of every file of code:
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
Furthermore please be aware of the differences between Python 2 and 3. For example this guide is helpful. Special
care has to be taken when dealing with strings and byte-strings. Please note that the _raw()-method only accepts
byte-strings. Often you can achieve compatibility quite easily with a tool from the six-package.
28 Chapter 5. Content
python-escpos Documentation, Release 3.0a1.dev1+ng5078c49
PEP8
This is not yet consequently done in every piece of code, but please try to ensure that your code honors PEP8. The
checks by Landscape and QuantifiedCode that run on every PR will provide you with hints.
GIT
The master-branch contains code that has been released to PyPi. A release is marked with a tag corresponding to the
version. Issues are closed when they have been resolved in the development-branch.
When you have a change to make, begin by creating a new branch from the HEAD of python-escpos/development.
Name your branch to indicate what you are trying to achieve. Good branch names might be improve/text-handling,
feature/enable-color-printing.
Please try to group your commits into logical units. If you need to tidy up your branch, you can make use of a git
feature called an ‘interactive rebase’ before making a pull request. A small, self-contained change-set is easier to
review, and improves the chance of your code being merged. Please also make sure that before creating your PR, your
branch is rebased on a recent commit or you merged a recent commit into your branch. This way you can ensure that
your PR is without merge conflicts.
Docstrings
This project tries to have a good documentation. Please add a docstring to every method and class. Have a look at
existing methods and classes for the style. We use basically standard rst-docstrings for Sphinx.
Test
Try to write tests whenever possible. Our goal for the future is 100% coverage. We are currently using nose but might
change in the future. You can copy the structure from other testcases. Please remember to adapt the docstrings.
Further reading
For further best practices and hints on contributing please see the contribution-guide. Should there be any contradic-
tions between this guide and the linked one, please stick to this text. Aside from that feel free to create an issue or
write an email if anything is unclear.
Thank you for your contribution!
5.9 Changelog
This release is the first alpha release of the new version 3.0. Please be aware that the API will still change until v3.0 is
released.
changes
• change the project’s license to MIT in accordance with the contributors (see python-escpos/python-escpos#171)
• feature: add “capabilities” which are shared with escpos-php, capabilities are stored in escpos-printer-db
5.9. Changelog 29
python-escpos Documentation, Release 3.0a1.dev1+ng5078c49
• feature: the driver tries now to guess the appropriate codepage and sets it automatically (called “magic encode”)
• as an alternative you can force the codepage with the old API
• updated and improved documentation
• changed constructor of main class due to introduction of capablities
• changed interface of method blocktext, changed behavior of multiple methods, for details refer to the documen-
tation on python-escpos.readthedocs.io
• add support for custom cash drawer sequence
• enforce flake8 on the src-files, test py36 and py37 on travis
contributors
• Michael Billington
• Michael Elsdörfer
• Patrick Kanzler (with code by Frédéric Van der Essen)
• Asuki Kono
• Benito López
• Curtis // mashedkeyboard
• Thijs Triemstra
• ysuolmai
changes
contributors
• Michael Elsdörfer
• Patrick Kanzler
changes
30 Chapter 5. Content
python-escpos Documentation, Release 3.0a1.dev1+ng5078c49
contributors
• Patrick Kanzler
changes
contributors
• Patrick Kanzler
changes
contributors
• Patrick Kanzler
• Renato Lorenzi
changes
contributors
• Patrick Kanzler
5.9. Changelog 31
python-escpos Documentation, Release 3.0a1.dev1+ng5078c49
This version is based on the original version of python-escpos by Manuel F Martinez. However, many contributions
have greatly improved the old codebase. Since this version does not completely match the interface of the version
published on PyPi and has many improvements, it will be released as version 2.0.0.
changes
contributors
32 Chapter 5. Content
python-escpos Documentation, Release 3.0a1.dev1+ng5078c49
• Updated README
5.9. Changelog 33
python-escpos Documentation, Release 3.0a1.dev1+ng5078c49
5.10 Esc/Pos
device = None
image(img_source, high_density_vertical=True, high_density_horizontal=True,
impl=u’bitImageRaster’, fragment_height=960)
Print an image
You can select whether the printer should print in high density or not. The default value is high density.
When printing in low density, the image will be stretched.
Esc/Pos supplies several commands for printing. This function supports three of them. Please try to vary
the implementations if you have any problems. For example the printer IT80-002 will have trouble aligning
images that are not printed in Column-mode.
The available printing implementations are:
•bitImageRaster: prints with the GS v 0-command
•graphics: prints with the GS ( L-command
•bitImageColumn: prints with the ESC *-command
Parameters
• img_source – PIL image or filename to load: jpg, gif, png or bmp
• high_density_vertical – print in high density in vertical direction default: True
• high_density_horizontal – print in high density in horizontal direction default:
True
• impl – choose image printing mode between bitImageRaster, graphics or bitImageCol-
umn
34 Chapter 5. Content
python-escpos Documentation, Release 3.0a1.dev1+ng5078c49
• fragment_height – Images larger than this will be split into multiple fragments de-
fault: 960
Todo
Add a method to check barcode codes. Alternatively or as an addition write explanations about each
barcode-type. Research whether the check digits can be computed autmatically.
Use the parameters height and width for adjusting of the barcode size. Please take notice that the barcode
will not be printed if it is outside of the printable area. (Which should be impossible with this method, so
this information is probably more useful for debugging purposes.)
Todo
On TM-T88II width from 1 to 6 is accepted. Try to acquire command reference and correct the code.
Todo
5.10. Esc/Pos 35
python-escpos Documentation, Release 3.0a1.dev1+ng5078c49
Supplying pos does not have an effect for every barcode type. Check and document for which types this is
true.
If you do not want to center the barcode you can call the method with align_ct=False, which will disable
automatic centering. Please note that when you use center alignment, then the alignment of text will be
changed automatically to centered. You have to manually restore the alignment if necessary.
Todo
If further barcode-types are needed they could be rendered transparently as an image. (This could also be
of help if the printer does not support types that others do.)
Parameters
• code – alphanumeric data to be printed as bar code
• bc – barcode format, possible values are for type A are:
– UPC-A
– UPC-E
– EAN13
– EAN8
– CODE39
– ITF
– NW7
Possible values for type B:
– All types from function type A
– CODE93
– CODE128
– GS1-128
– GS1 DataBar Omnidirectional
– GS1 DataBar Truncated
– GS1 DataBar Limited
– GS1 DataBar Expanded
If none is specified, the method raises BarcodeTypeError.
• height (int) – barcode height, has to be between 1 and 255 default: 64
• width (int) – barcode width, has to be between 2 and 6 default: 3
• pos – where to place the text relative to the barcode, default: BELOW
– ABOVE
– BELOW
– BOTH
– OFF
36 Chapter 5. Content
python-escpos Documentation, Release 3.0a1.dev1+ng5078c49
• font – select font (see ESC/POS-documentation, the device often has two fonts), default:
A
– A
– B
• align_ct (bool) – If this parameter is True the barcode will be centered. Otherwise
no alignment command will be issued.
• function_type – Choose between ESCPOS function type A or B, depending on
printer support and desired barcode. If not given, the printer will attempt to automati-
cally choose the correct function based on the current profile. default: A
Raises BarcodeSizeError, BarcodeTypeError, BarcodeCodeError
text(txt)
Print alpha-numeric text
The text has to be encoded in the currently selected codepage. The input text has to be encoded in unicode.
Parameters txt – text to be printed
Raises TextError
block_text(txt, font=None, columns=None)
Text is printed wrapped to specified columns
Text has to be encoded in unicode.
Parameters
• txt – text to be printed
• font – font to be used, can be a or :code‘b‘
• columns – amount of columns
Returns None
set(align=u’left’, font=u’a’, text_type=u’normal’, width=1, height=1, density=9, invert=False,
smooth=False, flip=False)
Set text properties by sending them to the printer
Parameters
• align – horizontal position for text, possible values are:
– CENTER
– LEFT
– RIGHT
default: LEFT
• font – font given as an index, a name, or one of the special values ‘a’ or ‘b’, refering to
fonts 0 and 1.
• text_type – text type, possible values are:
– B for bold
– U for underlined
– U2 for underlined, version 2
– BU for bold and underlined
5.10. Esc/Pos 37
python-escpos Documentation, Release 3.0a1.dev1+ng5078c49
Todo
Check this function on TM-T88II.
cashdraw(pin)
Send pulse to kick the cash drawer
Kick cash drawer on pin 2 or pin 5 according to default parameter. For non default parameter send a
decimal sequence i.e. [27,112,48] or [27,112,0,25,255]
Parameters pin – pin number, 2 or 5 or list of decimals
Raises CashDrawerError
hw(hw)
Hardware operations
Parameters hw – hardware action, may be:
• INIT
• SELECT
38 Chapter 5. Content
python-escpos Documentation, Release 3.0a1.dev1+ng5078c49
• RESET
control(ctl, pos=4)
Feed control sequences
Parameters
• ctl – string for the following control sequences:
– LF for Line Feed
– FF for Form Feed
– CR for Carriage Return
– HT for Horizontal Tab
– VT for Vertical Tab
• pos – integer between 1 and 16, controls the horizontal tab position
Raises TabPosError
panel_buttons(enable=True)
Controls the panel buttons on the printer (e.g. FEED)
When enable is set to False the panel buttons on the printer will be disabled. Calling the method with
enable=True or without argument will enable the panel buttons.
If panel buttons are enabled, the function of the panel button, such as feeding, will be executed upon
pressing the button. If the panel buttons are disabled, pressing them will not have any effect.
This command is effective until the printer is initialized, reset or power-cycled. The default is enabled
panel buttons.
Some panel buttons will always work, especially when printer is opened. See for more information the
manual of your printer and the escpos-command-reference.
Parameters enable – controls the panel buttons
Return type None
class escpos.escpos.EscposIO(printer, autocut=True, autoclose=True, **kwargs)
Bases: object
ESC/POS Printer IO object
Allows the class to be used together with the with-statement. You have to define a printer instance and assign it
to the EsposIO-class. This example explains the usage:
with EscposIO(printer.Serial('/dev/ttyUSB0')) as p:
p.set(font='a', height=2, align='center', text_type='bold')
p.printer.set(align='left')
p.printer.image('logo.gif')
p.writelines('Big line\n', font='b')
p.writelines('')
p.writelines('BIG TEXT', width=2)
After the with-statement the printer automatically cuts the paper if autocut is True.
set(**kwargs)
Set the printer-parameters
Controls which parameters will be passed to Escpos.set(). For more information on the parameters
see the set()-methods documentation. These parameters can also be passed with this class’ constructor
or the writelines()-method.
5.10. Esc/Pos 39
python-escpos Documentation, Release 3.0a1.dev1+ng5078c49
Module escpos.printer This module contains the implementations of abstract base class Escpos.
author Manuel F Martinez and others
organization Bashlinux and python-escpos
copyright Copyright (c) 2012-2017 Bashlinux and python-escpos
license MIT
class escpos.printer.Usb(idVendor, idProduct, timeout=0, in_ep=130, out_ep=1, *args, **kwargs)
Bases: escpos.escpos.Escpos
USB printer
This class describes a printer that natively speaks USB.
inheritance:
Escpos Usb
open()
Search device on USB tree and set it as escpos device
close()
Release USB interface
class escpos.printer.Serial(devfile=u’/dev/ttyS0’, baudrate=9600, bytesize=8, timeout=1, par-
ity=’N’, stopbits=1, xonxoff=False, dsrdtr=True, *args, **kwargs)
Bases: escpos.escpos.Escpos
Serial printer
This class describes a printer that is connected by serial interface.
inheritance:
Escpos Serial
40 Chapter 5. Content
python-escpos Documentation, Release 3.0a1.dev1+ng5078c49
open()
Setup serial port and set is as escpos device
close()
Close Serial interface
class escpos.printer.Network(host, port=9100, timeout=60, *args, **kwargs)
Bases: escpos.escpos.Escpos
Network printer
This class is used to attach to a networked printer. You can also use this in order to attach to a printer that is
forwarded with socat.
If you have a local printer on parallel port /dev/usb/lp0 then you could start socat with:
socat -u TCP4-LISTEN:4242,reuseaddr,fork OPEN:/dev/usb/lp0
Then you should be able to attach to port 4242 with this class. Otherwise the normal usecase would be to have
a printer with ethernet interface. This type of printer should work the same with this class. For the address of
the printer check its manuals.
inheritance:
Escpos Network
open()
Open TCP socket with socket-library and set it as escpos device
close()
Close TCP connection
class escpos.printer.File(devfile=u’/dev/usb/lp0’, auto_flush=True, *args, **kwargs)
Bases: escpos.escpos.Escpos
Generic file printer
This class is used for parallel port printer or other printers that are directly attached to the filesystem. Note
that you should stay away from using USB-to-Parallel-Adapter since they are unreliable and produce arbitrary
errors.
inheritance:
Escpos File
open()
Open system file
flush()
Flush printing content
close()
Close system file
class escpos.printer.Dummy(*args, **kwargs)
Bases: escpos.escpos.Escpos
Dummy printer
This class is used for saving commands to a variable, for use in situations where there is no need to send
commands to an actual printer. This includes generating print jobs for later use, or testing output.
inheritance:
Escpos Dummy
output
Get the data that was sent to this printer
close()
5.12 Constants
5.13 Exceptions
42 Chapter 5. Content
python-escpos Documentation, Release 3.0a1.dev1+ng5078c49
5.13. Exceptions 43
python-escpos Documentation, Release 3.0a1.dev1+ng5078c49
exception escpos.exceptions.TextError(msg=u’‘)
Bases: escpos.exceptions.Error
Text string must be supplied to the text() method.
This exception is raised when an empty string is passed to escpos.escpos.Escpos.text(). The return-
code for this exception is 50.
exception escpos.exceptions.CashDrawerError(msg=u’‘)
Bases: escpos.exceptions.Error
Valid pin must be set in order to send pulse.
A valid pin number has to be passed onto the method escpos.escpos.Escpos.cashdraw(). The re-
turncode for this exception is 60.
exception escpos.exceptions.TabPosError(msg=u’‘)
Bases: escpos.exceptions.Error
Valid tab positions must be in the range 0 to 16.
This exception is raised by escpos.escpos.Escpos.control(). The returncode for this exception is
70.
exception escpos.exceptions.CharCodeError(msg=u’‘)
Bases: escpos.exceptions.Error
Valid char code must be set.
The supplied charcode-name in escpos.escpos.Escpos.charcode() is unknown. Ths returncode for
this exception is 80.
exception escpos.exceptions.USBNotFoundError(msg=u’‘)
Bases: escpos.exceptions.Error
Device wasn’t found (probably not plugged in)
The USB device seems to be not plugged in. Ths returncode for this exception is 90.
exception escpos.exceptions.SetVariableError(msg=u’‘)
Bases: escpos.exceptions.Error
A set method variable was out of range
Check set variables against minimum and maximum values Ths returncode for this exception is 100.
exception escpos.exceptions.ConfigNotFoundError(msg=u’‘)
Bases: escpos.exceptions.Error
The configuration file was not found
The default or passed configuration file could not be read Ths returncode for this exception is 200.
exception escpos.exceptions.ConfigSyntaxError(msg=u’‘)
Bases: escpos.exceptions.Error
The configuration file is invalid
The syntax is incorrect Ths returncode for this exception is 210.
exception escpos.exceptions.ConfigSectionMissingError(msg=u’‘)
Bases: escpos.exceptions.Error
The configuration file is missing a section
The part of the config asked for doesn’t exist in the loaded configuration Ths returncode for this exception is
220.
44 Chapter 5. Content
python-escpos Documentation, Release 3.0a1.dev1+ng5078c49
5.14 Capabilities
Module escpos.capabilities
exception escpos.capabilities.NotSupported
Bases: exceptions.Exception
Raised if a requested feature is not suppored by the printer profile.
args
message
class escpos.capabilities.BaseProfile
Bases: object
This respresents a printer profile.
A printer profile knows about the number of columns, supported features, colors and more.
profile_data = {}
get_font(font)
Return the escpos index for font. Makes sure that the requested font is valid.
get_columns(font)
Return the number of columns for the given font.
supports(feature)
Return true/false for the given feature.
get_code_pages()
Return the support code pages as a {name: index} dict.
escpos.capabilities.get_profile(name=None, **kwargs)
Get the profile by name; if no name is given, return the default profile.
escpos.capabilities.get_profile_class(name)
For the given profile name, load the data from the external database, then generate dynamically a class.
escpos.capabilities.clean(s)
class escpos.capabilities.Profile(columns=None, features=None)
Bases: escpos.capabilities.DefaultProfile
For users, who want to provide their profile
get_columns(font)
get_code_pages()
Return the support code pages as a {name: index} dict.
get_font(font)
Return the escpos index for font. Makes sure that the requested font is valid.
profile_data = {‘vendor’: ‘Generic’, ‘features’: {‘bitImageColumn’: True, ‘starCommands’: False, ‘highDensity’: Tr
supports(feature)
Return true/false for the given feature.
5.14. Capabilities 45
python-escpos Documentation, Release 3.0a1.dev1+ng5078c49
5.15 Config
46 Chapter 5. Content
python-escpos Documentation, Release 3.0a1.dev1+ng5078c49
split(fragment_height)
Split an image into multiple fragments after fragment_height pixels
Parameters fragment_height – height of fragment
Returns list of PIL objects
5.17 CLI
5.17. CLI 47
python-escpos Documentation, Release 3.0a1.dev1+ng5078c49
$ python -m timeit -s “{u’ö’:’a’}.get(u’ö’)” 100000000 loops, best of 3: 0.0133 usec per loop
$ python -m timeit -s “u’ö’.encode(‘latin1’)” 100000000 loops, best of 3: 0.0141 usec per loop
get_sequence(encoding)
get_encoding_name(encoding)
Given an encoding provided by the user, will return a canonical encoding name; and also validate that the
encoding is supported.
TODO: Support encoding aliases: pc437 instead of cp437.
can_encode(encoding, char)
Determine if a character is encodeable in the given code page.
Parameters
• encoding – The name of the encoding.
• char – The character to attempt to encode.
encode(text, encoding, defaultchar=u’?’)
Encode text under the given encoding
Parameters
• text – Text to encode
• encoding – Encoding name to use (must be defined in capabilities)
• defaultchar – Fallback for non-encodable characters
find_suitable_encoding(char)
The order of our search is a specific one:
1.code pages that we already tried before; there is a good chance they might work again, reducing the
search space, and by re-using already used encodings we might also reduce the number of codepage
change instructiosn we have to send. Still, any performance gains will presumably be fairly minor.
2.code pages in lower ESCPOS slots first. Presumably, they are more likely to be supported, so if a
printer profile is missing or incomplete, we might increase our change that the code page we pick for
this character is actually supported.
escpos.magicencode.split_writable_text(encoder, text, encoding)
Splits off as many characters from the begnning of text as are writable with “encoding”. Returns a 2-tuple
(writable, rest).
class escpos.magicencode.MagicEncode(driver, encoding=None, disabled=False, defaultsym-
bol=u’?’, encoder=None)
Bases: object
A helper that helps us to automatically switch to the right code page to encode any given Unicode character.
This will consider the printers supported codepages, according to the printer profile, and if a character cannot
be encoded with the current profile, it will attempt to find a suitable one.
If the printer does not support a suitable code page, it can insert an error character.
force_encoding(encoding)
Sets a fixed encoding. The change is emitted right away.
From now one, this buffer will switch the code page anymore. However, it will still keep track of the
current code page.
write(text)
Write the text, automatically switching encodings.
48 Chapter 5. Content
python-escpos Documentation, Release 3.0a1.dev1+ng5078c49
write_with_encoding(encoding, text)
5.19 Codepages
Module escpos.codepages
class escpos.codepages.CodePageManager(data)
Holds information about all the code pages (as defined in escpos-printer-db).
get_all()
static get_encoding_name(encoding)
get_encoding(encoding)
5.20 Katakana
• genindex
• modindex
• search
5.19. Codepages 49
python-escpos Documentation, Release 3.0a1.dev1+ng5078c49
50 Chapter 5. Content
Python Module Index
e
escpos.capabilities, 45
escpos.cli, 47
escpos.codepages, 49
escpos.config, 46
escpos.constants, 42
escpos.escpos, 34
escpos.exceptions, 42
escpos.image, 46
escpos.katakana, 49
escpos.magicencode, 47
escpos.printer, 40
51
python-escpos Documentation, Release 3.0a1.dev1+ng5078c49
53
python-escpos Documentation, Release 3.0a1.dev1+ng5078c49
O
open() (escpos.printer.File method), 41
open() (escpos.printer.Network method), 41
open() (escpos.printer.Serial method), 40
open() (escpos.printer.Usb method), 40
output (escpos.printer.Dummy attribute), 42
P
panel_buttons() (escpos.escpos.Escpos method), 39
printer() (escpos.config.Config method), 46
Profile (class in escpos.capabilities), 45
profile_data (escpos.capabilities.BaseProfile attribute), 45
profile_data (escpos.capabilities.Profile attribute), 45
Q
qr() (escpos.escpos.Escpos method), 35
S
Serial (class in escpos.printer), 40
set() (escpos.escpos.Escpos method), 37
set() (escpos.escpos.EscposIO method), 39
SET_FONT() (in module escpos.constants), 42
SetVariableError, 44
54 Index