### Install pyxmlescpos Python Library
Source: https://context7.com/fvdsn/py-xml-escpos/llms.txt
Installs the pyxmlescpos library using pip. This is a prerequisite for using the library's functionalities.
```bash
sudo pip install pyxmlescpos
```
--------------------------------
### Basic XML Receipt Structure Example
Source: https://github.com/fvdsn/py-xml-escpos/blob/master/README.md
Demonstrates the fundamental structure of an XML document used for generating receipts with the XML-ESC/POS library. It includes common elements like headers, lines, and special tags for barcodes and cash drawers.
```xml
Receipt!
div,span,p,ul,ol are also supported
:w
Product
0.15€
TOTAL
0.15€
5449000000996
```
--------------------------------
### Generate a Complete Receipt with Various Elements
Source: https://context7.com/fvdsn/py-xml-escpos/llms.txt
This snippet demonstrates the creation of a comprehensive receipt using XML. It includes headers, styled text lines for items and totals, a footer message, a barcode, cash drawer control, and a paper cut command. The USB connection is used for this example.
```python
from xmlescpos.printer import Usb
printer = Usb(0x04b8, 0x0e03)
receipt_xml = """
Store Name
Receipt #12345
123 Main Street, City, State
Product A
$9.99
Product B
$14.50
Product C (x2)
$5.00
TOTAL
$29.49
Thank you for your purchase!
5449000000996
"""
printer.receipt(receipt_xml)
```
--------------------------------
### Connect and Print via Network Printer
Source: https://context7.com/fvdsn/py-xml-escpos/llms.txt
Illustrates connecting to an ESC/POS printer over a network using TCP/IP. The example specifies the printer's host IP address and port, and prints a receipt containing network-specific information.
```python
from xmlescpos.printer import Network
# Connect to network printer (default port 9100)
printer = Network(host="192.168.1.100", port=9100)
# Print receipt
printer.receipt("""
Network Receipt
Printed over TCP/IP
""")
```
--------------------------------
### Send Raw ESC/POS Commands Directly
Source: https://context7.com/fvdsn/py-xml-escpos/llms.txt
Allows sending low-level ESC/POS commands directly to the printer using the `_raw()` method. This is useful for commands not exposed through higher-level XML tags or text methods. It includes examples for printer initialization, alignment, and cutting.
```python
from xmlescpos.printer import Usb
printer = Usb(0x04b8, 0x0e03)
# Send raw ESC/POS commands
printer._raw('\x1b\x40') # Initialize printer
printer._raw('\x1b\x61\x01') # Center alignment
printer.text("Raw Command Text")
printer._raw('\x0a') # Line feed
printer._raw('\x1d\x56\x00') # Full cut
# Use text() method for proper UTF-8 encoding
printer.text("Hello in UTF-8: Héllo, Мир, 日本語")
printer.cut()
```
--------------------------------
### XML Value Tag for Formatted Numerical Output
Source: https://github.com/fvdsn/py-xml-escpos/blob/master/README.md
Demonstrates the `value` tag for formatting numerical data in receipts. This example shows setting a currency symbol and its position using `value-symbol` and `value-symbol-position` attributes.
```xml
3.1415
```
--------------------------------
### Create Lists with Bullets and Numbering
Source: https://context7.com/fvdsn/py-xml-escpos/llms.txt
This example shows how to generate unordered lists with custom bullet characters and ordered lists with automatic numbering using the XML-ESC/POS library. It also demonstrates setting tab widths for better alignment within lists. The code uses a USB printer connection.
```python
from xmlescpos.printer import Usb
printer = Usb(0x04b8, 0x0e03)
list_receipt = """
Shopping List
Instructions
- Connect the printer
- Load the receipt paper
- Send print command
- Tear off the receipt
"""
printer.receipt(list_receipt)
```
--------------------------------
### XML Barcode Tag with EAN13 Encoding
Source: https://github.com/fvdsn/py-xml-escpos/blob/master/README.md
Shows how to include a barcode in the receipt using the `barcode` tag. The `encoding` attribute is mandatory, and this example specifies 'EAN13' for the barcode type.
```xml
5400113509509
```
--------------------------------
### XML Structure for ESC/POS Receipts
Source: https://github.com/fvdsn/py-xml-escpos/blob/master/DESCRIPTION.rst
This example demonstrates the XML format used by the XML-ESC/POS library to construct receipt content. It showcases elements for text formatting, product lines, totals, barcodes, and printer commands like cash drawer and cutting. This XML is parsed and converted into ESC/POS commands by the library.
```xml
Receipt!
div,span,p,ul,ol are also supported
Product
0.15€
TOTAL
0.15€
5449000000996
```
--------------------------------
### Connect and Print via USB Printer
Source: https://context7.com/fvdsn/py-xml-escpos/llms.txt
Demonstrates connecting to an ESC/POS printer over USB using vendor and product IDs and printing a simple 'Hello World' receipt. The connection is explicitly closed after printing.
```python
from xmlescpos.printer import Usb
# Connect to Epson TM-T20 printer (vendor: 0x04b8, product: 0x0e03)
printer = Usb(0x04b8, 0x0e03)
# Print simple text
printer.receipt("
Hello World!
")
# Close connection
printer.close()
```
--------------------------------
### Print a Receipt using XML-ESC/POS in Python
Source: https://github.com/fvdsn/py-xml-escpos/blob/master/DESCRIPTION.rst
This Python code snippet illustrates how to use the XML-ESC/POS library to send a simple receipt to a USB-connected ESC/POS printer. It requires the `xmlescpos` library and specifies the USB vendor and product IDs for the printer. The `receipt` method takes an XML string as input.
```python
from xmlescpos.printer import Usb
printer = Usb(0x04b8,0x0e03)
printer.receipt("Hello World!
")
```
--------------------------------
### List and Connect to Supported ESC/POS Devices
Source: https://context7.com/fvdsn/py-xml-escpos/llms.txt
Provides a method to access a predefined list of common ESC/POS printer vendor and product IDs. This list can be used to dynamically identify and connect to printers by their known identifiers.
```python
from xmlescpos.printer import Usb
from xmlescpos.supported_devices import device_list
# Display supported devices
for device in device_list:
print(f"{device['name']}: Vendor={hex(device['vendor'])}, Product={hex(device['product'])}")
# Output:
# Epson TM-T20: Vendor=0x4b8, Product=0xe03
# Epson TM-T70: Vendor=0x4b8, Product=0x202
# Epson TM-T20II: Vendor=0x4b8, Product=0xe15
# Connect using device from list
epson_tm_t20 = device_list[0]
printer = Usb(epson_tm_t20['vendor'], epson_tm_t20['product'])
```
--------------------------------
### Apply Text Styling and Formatting in Receipts
Source: https://context7.com/fvdsn/py-xml-escpos/llms.txt
This Python code demonstrates various text styling options available in XML-ESC/POS, including alignment (left, center, right), font styles (bold, underline, font B), size variations (double, double-width, double-height), and color. It uses a USB printer connection.
```python
from xmlescpos.printer import Usb
printer = Usb(0x04b8, 0x0e03)
styled_receipt = """
Heading 1 - Bold Double Size
Heading 2 - Double Size
Heading 3 - Bold Double Height
Heading 5 - Bold Normal
Left aligned text
Center aligned text
Right aligned text
Bold text
Underlined text
Double underlined text
Font B (smaller)
Double size
Double width only
Double height only
Red text (if supported)
"""
printer.receipt(styled_receipt)
```
--------------------------------
### Control Cash Drawer Operation (Python)
Source: https://context7.com/fvdsn/py-xml-escpos/llms.txt
Triggers the cash drawer to open after a receipt is printed using either the `` tag within the XML, a direct `printer.cashdraw()` function call with a pin number, or by setting the `open-cashdrawer='true'` attribute on the `` tag.
```python
from xmlescpos.printer import Usb
printer = Usb(0x04b8, 0x0e03)
# Method 1: Using XML tag
receipt_with_drawer = """
Sale Complete
Cash: $20.00
Change: $5.00
"""
printer.receipt(receipt_with_drawer)
# Method 2: Direct function call
printer.cashdraw(2) # Send pulse to pin 2
printer.cashdraw(5) # Send pulse to pin 5
# Method 3: Receipt attribute
auto_drawer_receipt = """
Payment Received
"""
printer.receipt(auto_drawer_receipt)
```
--------------------------------
### XML Line Tag with Left and Right Alignment
Source: https://github.com/fvdsn/py-xml-escpos/blob/master/README.md
Illustrates the `line` tag for creating lines with content aligned to the left and right. The `line-ratio` attribute controls the width distribution between the left and right parts.
```xml
Product Name
$0.15
```
--------------------------------
### Handle Common ESC/POS Printer Errors
Source: https://context7.com/fvdsn/py-xml-escpos/llms.txt
Demonstrates how to catch and handle various exceptions that can occur during ESC/POS printer operations, such as device connection issues, printing failures, and invalid data formats. It provides specific error messages for common problems.
```python
from xmlescpos.printer import Usb
from xmlescpos.exceptions import (
NoDeviceError,
HandleDeviceError,
TicketNotPrinted,
BarcodeTypeError,
ImageSizeError
)
try:
printer = Usb(0x04b8, 0x0e03)
receipt = """
Test Receipt
5449000000996
"""
printer.receipt(receipt)
printer.close()
except NoDeviceError:
print("ERROR: Printer not found. Check USB connection and IDs.")
except HandleDeviceError as e:
print(f"ERROR: Cannot handle device: {e}")
except TicketNotPrinted:
print("ERROR: Receipt was not fully printed")
except BarcodeTypeError:
print("ERROR: Invalid barcode encoding specified")
except ImageSizeError:
print("ERROR: Image dimensions exceed printer limits")
except Exception as e:
print(f"Unexpected error: {e}")
```
--------------------------------
### Connect and Print via Serial Printer
Source: https://context7.com/fvdsn/py-xml-escpos/llms.txt
Shows how to connect to an ESC/POS printer via a serial port (RS-232) with custom baud rate and other serial communication settings. The receipt includes basic XML formatting, and the connection is managed automatically.
```python
from xmlescpos.printer import Serial
# Connect to serial printer
printer = Serial(
devfile="/dev/ttyS0",
baudrate=9600,
bytesize=8,
timeout=1
)
# Print receipt
printer.receipt("Serial Receipt
Printed via RS-232
")
# Connection closes automatically on object deletion
```
--------------------------------
### Format Numerical Values with Decimals and Symbols (Python)
Source: https://context7.com/fvdsn/py-xml-escpos/llms.txt
Formats numerical values within a receipt, allowing customization of decimal places, thousands separators, and currency symbols. The `` tag with attributes like `value-decimals`, `value-symbol`, and `value-thousands-separator` enables flexible financial display.
```python
from xmlescpos.printer import Usb
printer = Usb(0x04b8, 0x0e03)
value_receipt = """
Price List
Item A
1234.56
Item B (Euro)
999.99
Item C (Auto-int)
100.00
Item D (3 decimals)
3.14159
"""
printer.receipt(value_receipt)
```
--------------------------------
### Format Receipt Lines with Left-Right Alignment (Python)
Source: https://context7.com/fvdsn/py-xml-escpos/llms.txt
Formats receipt lines with left-aligned and right-aligned content on a single line using the `` tag with specified ratios. This is useful for aligning item names with their prices or quantities.
```python
from xmlescpos.printer import Usb
printer = Usb(0x04b8, 0x0e03)
line_receipt = """
Invoice
Item Description
Price
Coffee - Large
$3.50
Sandwich
$6.99
Tax (8%)
$0.84
TOTAL
$11.33
"""
printer.receipt(line_receipt)
```
--------------------------------
### Perform Partial Paper Cut on Receipts
Source: https://context7.com/fvdsn/py-xml-escpos/llms.txt
Demonstrates how to execute a partial paper cut, leaving a small perforation for easier manual tearing. This can be achieved using the `` XML tag or the `printer.cut(mode='part')` function call.
```python
from xmlescpos.printer import Usb
printer = Usb(0x04b8, 0x0e03)
# Method 1: XML tag
partial_cut_receipt = """
Receipt with Partial Cut
Easy to tear manually
"""
printer.receipt(partial_cut_receipt)
# Method 2: Direct function call
printer.text("Another receipt\n")
printer.cut(mode='part')
```
--------------------------------
### XML List Tag with Tab Width and Bullet Customization
Source: https://github.com/fvdsn/py-xml-escpos/blob/master/README.md
Illustrates how to use the `ul` tag for creating lists in XML receipts. It shows the customization of `tabwidth` for indentation and `bullet` for the list marker character.
```xml
```
--------------------------------
### Print Images from Base64 Data URLs (Python)
Source: https://context7.com/fvdsn/py-xml-escpos/llms.txt
Prints images embedded as base64-encoded data URLs within receipt XML. Requires the image to be read, encoded, and then embedded using the `
` tag. Supported formats are PNG, JPEG, and GIF, with constraints on image dimensions.
```python
from xmlescpos.printer import Usb
import base64
printer = Usb(0x04b8, 0x0e03)
# Read image and convert to base64
with open('logo.png', 'rb') as img_file:
img_data = base64.b64encode(img_file.read()).decode('utf-8')
image_receipt = f"""
Company Logo:
Store Receipt
Thank you for shopping with us!
"""
printer.receipt(image_receipt)
# Supported formats: PNG, JPEG, GIF
# Image width should be <= 512 pixels
# Image height must be <= 255 pixels
```
--------------------------------
### XML Image Tag with Base64 Encoded Data
Source: https://github.com/fvdsn/py-xml-escpos/blob/master/README.md
Demonstrates the usage of the `img` tag to embed images directly within the XML receipt. The `src` attribute must contain the image data (PNG, GIF, or JPEG) encoded in Base64.
```xml
```
--------------------------------
### Add Horizontal Rules and Line Breaks in Receipts
Source: https://context7.com/fvdsn/py-xml-escpos/llms.txt
Shows how to use XML tags `
` for horizontal separators and `
` for line breaks within receipt templates. This enhances the visual structure and readability of printed receipts.
```python
from xmlescpos.printer import Usb
printer = Usb(0x04b8, 0x0e03)
separator_receipt = """
Invoice
Item 1: $10.00
Item 2: $15.00
Total: $25.00
Thank you!
"""
printer.receipt(separator_receipt)
```
--------------------------------
### Print Barcodes on Receipts (Python)
Source: https://context7.com/fvdsn/py-xml-escpos/llms.txt
Generates and prints various standard barcode formats directly onto receipts using the `` tag with the `encoding` attribute. Supported formats include EAN-13, EAN-8, CODE39, and UPC-A.
```python
from xmlescpos.printer import Usb
printer = Usb(0x04b8, 0x0e03)
barcode_receipt = """
Barcode Examples
EAN-13 Barcode:
5449000000996
EAN-8 Barcode:
12345670
CODE39 Barcode:
ABC123
UPC-A Barcode:
012345678905
"""
printer.receipt(barcode_receipt)
# Supported encodings: UPC-A, UPC-E, EAN13, EAN8, CODE39, ITF, NW7
```
--------------------------------
### Monitor Printer Status (Python)
Source: https://context7.com/fvdsn/py-xml-escpos/llms.txt
Checks the current status of the printer, including paper level, online status, cover state, and errors. The `printer.get_printer_status()` method returns a dictionary with detailed status information, which can be used for error handling and alerts.
```python
from xmlescpos.printer import Usb
from xmlescpos.exceptions import NoStatusError
import pprint
printer = Usb(0x04b8, 0x0e03)
try:
status = printer.get_printer_status()
pprint.pprint(status)
# Check specific conditions
if not status['printer']['online']:
print("ERROR: Printer is offline")
if not status['offline']['paper']:
print("WARNING: Out of paper")
if status['paper']['near_end']:
print("WARNING: Paper near end")
if status['offline']['cover_open']:
print("ERROR: Printer cover is open")
if status['error']['unrecoverable']:
print("ERROR: Unrecoverable printer error")
except NoStatusError as e:
print(f"Cannot retrieve printer status: {e}")
```
--------------------------------
### Disable Auto-Cut Feature for Receipts
Source: https://context7.com/fvdsn/py-xml-escpos/llms.txt
Explains how to prevent the printer from automatically cutting the paper after a receipt is printed using the `cut='false'` attribute in the `` tag. This is useful for scenarios requiring continuous printing or manual cutting.
```python
from xmlescpos.printer import Usb
printer = Usb(0x04b8, 0x0e03)
no_cut_receipt = """
Receipt 1
This receipt won't auto-cut
"""
printer.receipt(no_cut_receipt)
# Print another receipt immediately
another_receipt = """
Receipt 2
This will cut after printing
"""
printer.receipt(another_receipt)
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.