### Install brother_ql from GitHub Source: https://github.com/pklaus/brother_ql/blob/master/README.md Install the latest version of the brother_ql package directly from its GitHub repository. ```bash pip install --upgrade https://github.com/pklaus/brother_ql/archive/master.zip ``` -------------------------------- ### Complete Brother QL Print Workflow Example Source: https://github.com/pklaus/brother_ql/blob/master/_autodocs/11-utilities.md This example demonstrates a full workflow: discovering USB printers, listing compatible labels for a specific model, converting an image to label data, and sending the data to the printer. Ensure you have a compatible printer connected via USB and an image file named 'label.png' in the same directory. ```python from brother_ql.raster import BrotherQLRaster from brother_ql.conversion import convert from brother_ql.backends.helpers import discover, send from brother_ql.output_helpers import textual_description_discovered_devices from brother_ql.labels import LabelsManager, FormFactor # 1. Discover printers devices = discover('pyusb') if not devices: print("No USB printers found") exit(1) print("Available printers:") print(textual_description_discovered_devices(devices)) device_id = devices[0]['identifier'] # 2. List compatible labels lm = LabelsManager() model = 'QL-710W' print(f"\nLabels compatible with {model}:") for label in lm.iter_elements(): if label.works_with_model(model): print(f" {label.identifier:10s} - {label.name}") # 3. Create and send label qlr = BrotherQLRaster(model) convert( qlr=qlr, images=['label.png'], label='62', compress=True, cut=True ) status = send( instructions=qlr.data, printer_identifier=device_id, blocking=True ) print(f"\nPrint result: {status['outcome']}") ``` -------------------------------- ### Complete Printer Interaction Example Source: https://github.com/pklaus/brother_ql/blob/master/_autodocs/05-backends.md A comprehensive example showing printer discovery, label conversion, and sending the generated instructions to the printer. ```python from brother_ql.raster import BrotherQLRaster from brother_ql.conversion import convert from brother_ql.backends.helpers import send, discover from brother_ql.backends import guess_backend # Discover printers devices = discover('pyusb') if not devices: print("No printers found") exit(1) device_identifier = devices[0]['identifier'] print(f"Using printer: {device_identifier}") # Create raster instructions qlr = BrotherQLRaster('QL-710W') convert( qlr=qlr, images=['label.png'], label='62', cut=True, compress=True ) # Send to printer backend = guess_backend(device_identifier) status = send( instructions=qlr.data, printer_identifier=device_identifier, backend_identifier=backend, blocking=True ) print(f"Print status: {status['outcome']}") ``` -------------------------------- ### Print Label Example Source: https://github.com/pklaus/brother_ql/blob/master/README.md Demonstrates how to print an image file onto a 62mm endless tape using environment variables for printer and model configuration. This is a practical example for everyday use. ```bash export BROTHER_QL_PRINTER=tcp://192.168.1.21 export BROTHER_QL_MODEL=QL-710W brother_ql print -l 62 my_image.png ``` -------------------------------- ### Install brother_ql using pip Source: https://github.com/pklaus/brother_ql/blob/master/README.md Install the latest version of the brother_ql package and its dependencies from the Python Package Index. ```bash pip install --upgrade brother_ql ``` -------------------------------- ### Basic Send Example Source: https://github.com/pklaus/brother_ql/blob/master/_autodocs/05-backends.md Demonstrates how to send raster instructions to a printer using its network identifier and check the print status. ```python from brother_ql.backends.helpers import send status = send( instructions=qlr.data, printer_identifier='tcp://192.168.1.21:9100', blocking=True ) if status['did_print']: print("Print successful!") else: print(f"Print outcome: {status['outcome']}") ``` -------------------------------- ### Setting Global Options via Command Line Source: https://github.com/pklaus/brother_ql/blob/master/_autodocs/07-cli-reference.md Example of setting backend, model, and printer directly on the command line for a print job. ```bash # Via command line brother_ql --backend pyusb --model QL-710W --printer "usb://0x04f9:0x2015/C5Z315686" print -l 62 label.png ``` -------------------------------- ### Setting Global Options via Environment Variables Source: https://github.com/pklaus/brother_ql/blob/master/_autodocs/07-cli-reference.md Example of configuring backend, model, and printer using environment variables before running the command. ```bash # Via environment variables export BROTHER_QL_BACKEND=pyusb export BROTHER_QL_MODEL=QL-710W export BROTHER_QL_PRINTER="tcp://192.168.1.21:9100" brother_ql print -l 62 label.png ``` -------------------------------- ### List Supported Label Sizes Source: https://github.com/pklaus/brother_ql/blob/master/_autodocs/07-cli-reference.md Command to list all supported label sizes, including their dimensions in pixels and descriptions. Shows example output. ```bash brother_ql info labels # Output: # Name Printable px Description # 12 106 12mm endless # 29 306 29mm endless # 62 696 62mm endless # 17x54 165 x 566 17mm x 54mm die-cut # ... (full list) ``` -------------------------------- ### Check Environment Information Source: https://github.com/pklaus/brother_ql/blob/master/_autodocs/07-cli-reference.md Displays information about the current environment, including installed packages and configuration details. ```bash # Check environment brother_ql info env ``` -------------------------------- ### List Supported Printer Models Source: https://github.com/pklaus/brother_ql/blob/master/_autodocs/07-cli-reference.md Command to list all printer models supported by the brother_ql utility. Shows example output. ```bash brother_ql info models # Output: # Supported models: # QL-500 # QL-550 # QL-560 # ... (full list) ``` -------------------------------- ### Connect to Printer via Different Backends Source: https://github.com/pklaus/brother_ql/blob/master/_autodocs/00-index.md Examples of device identifiers and backend selections for connecting to Brother QL printers over USB, WiFi/Network, or Linux device files. ```python # USB (PyUSB backend) device_id = 'usb://0x04f9:0x2015/C5Z315686' backend = 'pyusb' ``` ```python # WiFi/Network (Network backend) device_id = 'tcp://192.168.1.21:9100' backend = 'network' ``` ```python # Linux USB device file (Linux kernel backend) device_id = 'file:///dev/usb/lp0' backend = 'linux_kernel' ``` -------------------------------- ### Get Label by Identifier Example Source: https://github.com/pklaus/brother_ql/blob/master/_autodocs/03-labels.md Retrieves a Label object using its unique identifier string. This example shows how to instantiate LabelsManager and fetch a label's printable dots. ```python lm = LabelsManager() label = lm.get_label_by_identifier('62') print(label.dots_printable) # (696, 0) for 62mm endless ``` -------------------------------- ### BrotherQLReader filename_fmt Property Setter Example Source: https://github.com/pklaus/brother_ql/blob/master/_autodocs/10-reader.md Demonstrates how to set a custom filename format for output images. The default format is 'label{counter:04d}.png'. ```python reader = BrotherQLReader(open('instructions.bin', 'rb')) reader.filename_fmt = 'page_{counter:02d}.png' reader.analyse() # Output: page_00.png, page_01.png, etc. ``` -------------------------------- ### Print Environment Debug Information Source: https://github.com/pklaus/brother_ql/blob/master/_autodocs/07-cli-reference.md Command to display detailed information about the running environment, useful for troubleshooting. Shows example output. ```bash brother_ql info env # Output (excerpt): # About the computer: # * Platform: Linux # * Processor: x86_64 # * System: Linux # About the installed Python version: # * 3.9.2 (default, Feb 28 2021, 17:03:48) # About the brother_ql package: # * package location: /usr/local/lib/python3.9/site-packages # * package version: 0.9.dev0 # ... (full details) ``` -------------------------------- ### Print Label Instruction File using brother_ql_print (USB) Source: https://github.com/pklaus/brother_ql/blob/master/LEGACY.md Send label instructions to a Brother QL printer connected via USB using the `brother_ql_print` tool. Requires PyUSB to be installed. ```bash brother_ql_print 720x151_monochrome.bin usb://0x04f9:0x2015 ``` -------------------------------- ### Basic Label Printing Source: https://github.com/pklaus/brother_ql/blob/master/_autodocs/07-cli-reference.md Example of printing a label using a specified size and image file, with printer details set via environment variables. ```bash export BROTHER_QL_PRINTER=tcp://192.168.1.21:9100 export BROTHER_QL_MODEL=QL-710W brother_ql print -l 62 my_label.png ``` -------------------------------- ### Discover USB Printers Source: https://github.com/pklaus/brother_ql/blob/master/_autodocs/07-cli-reference.md Command to discover USB printers using the pyusb backend. Shows example output. ```bash # Discover USB printers brother_ql --backend pyusb discover # Output: # Found a label printer: usb://0x04f9:0x2015/C5Z315686 (model: unknown) ``` -------------------------------- ### USB Printer Discovery and Setup Source: https://github.com/pklaus/brother_ql/blob/master/_autodocs/07-cli-reference.md Discovers USB-connected printers and provides an identifier for use in subsequent commands. The output identifier should be exported to an environment variable. ```bash # Discover USB-connected printers brother_ql -b pyusb discover # Use discovered identifier # Output: Found a label printer: usb://0x04f9:0x2015/C5Z315686 # Store and use export BROTHER_QL_PRINTER=usb://0x04f9:0x2015/C5Z315686 brother_ql -m QL-710W print -l 62 label.png ``` -------------------------------- ### Catch Base Brother QL Exception Source: https://github.com/pklaus/brother_ql/blob/master/_autodocs/06-exceptions.md Example demonstrating how to catch the base BrotherQLError. This is useful for handling any exception originating from the brother_ql library. ```python from brother_ql import BrotherQLError try: qlr = BrotherQLRaster('QL-INVALID') except BrotherQLError as e: print(f"Brother QL error: {e}") ``` -------------------------------- ### Check Label Model Compatibility Example Source: https://github.com/pklaus/brother_ql/blob/master/_autodocs/03-labels.md Checks if a specific label is compatible with a given printer model. This is useful for ensuring that a label can be used with the intended printer. ```python label_102 = LabelsManager().get_label_by_identifier('102') label_102.works_with_model('QL-1050') # True label_102.works_with_model('QL-710W') # False (restricted to large models) ``` -------------------------------- ### Handle Unsupported Command Exception Source: https://github.com/pklaus/brother_ql/blob/master/_autodocs/06-exceptions.md Example of catching BrotherQLUnsupportedCmd when trying to use a feature like compression on a model that does not support it. This snippet also shows how to enable strict mode for warnings. ```python from brother_ql import BrotherQLRaster, BrotherQLUnsupportedCmd from brother_ql.conversion import convert qlr = BrotherQLRaster('QL-500') # Doesn't support compression qlr.exception_on_warning = True try: convert( qlr=qlr, images=['label.png'], label='62', compress=True # Not supported on QL-500 ) except BrotherQLUnsupportedCmd as e: print(f"Feature not supported: {e}") ``` -------------------------------- ### Iterate Over Label Identifiers Example Source: https://github.com/pklaus/brother_ql/blob/master/_autodocs/03-labels.md Iterates through all available label identifiers and prints each one. This is useful for discovering all supported label types. ```python lm = LabelsManager() for label_id in lm.iter_identifiers(): print(label_id) ``` -------------------------------- ### Iterate Over Label Objects Example Source: https://github.com/pklaus/brother_ql/blob/master/_autodocs/03-labels.md Iterates through all available Label objects. This method yields each Label object, allowing access to all its properties and methods. ```python def iter_elements(self): """Iterate over all Label objects""" # Yields Label - Label objects ``` -------------------------------- ### Backend Factory Function Source: https://github.com/pklaus/brother_ql/blob/master/_autodocs/05-backends.md Retrieves the backend class and a device discovery function for a given backend name. Use this to dynamically get backend components for connecting to printers. ```python from brother_ql.backends import backend_factory be = backend_factory('pyusb') available_devices = be['list_available_devices']() BackendClass = be['backend_class'] for device in available_devices: printer = BackendClass(device['identifier']) ``` -------------------------------- ### Configure Linux udev Rule Source: https://github.com/pklaus/brother_ql/blob/master/_autodocs/05-backends.md Example of a udev rule to set permissions for Brother QL printers, allowing regular users to print without root privileges. This rule targets specific vendor and product IDs and sets the mode to 0666. ```bash # /etc/udev/rules.d/60-brother-ql.rules SUBSYSTEM=="usb", ATTRS{idVendor}=="04f9", ATTRS{idProduct}=="2015", MODE="0666" ``` -------------------------------- ### Get Label Name Example Source: https://github.com/pklaus/brother_ql/blob/master/_autodocs/03-labels.md Retrieves and prints the human-readable name of a label. This demonstrates how to access the 'name' property after getting a label by its identifier. ```python label = LabelsManager().get_label_by_identifier('62') print(label.name) # Output: "62mm endless" label = LabelsManager().get_label_by_identifier('23x23') print(label.name) # Output: "23mm x 23mm die-cut" ``` -------------------------------- ### Display brother_ql_create Help Source: https://github.com/pklaus/brother_ql/blob/master/LEGACY.md View available options and usage for the `brother_ql_create` command-line tool by running it with the --help flag. ```bash brother_ql_create --help ``` -------------------------------- ### Configure Network Backend Source: https://github.com/pklaus/brother_ql/blob/master/_autodocs/09-configuration.md Set up the network backend for communication with the printer over TCP/IP. Timeout and read strategy can be configured. ```python from brother_ql.backends.network import BrotherQLBackendNetwork backend = BrotherQLBackendNetwork('tcp://192.168.1.21:9100') # Configuration attributes backend.read_timeout = 0.01 # seconds (default) backend.strategy = 'socket_timeout' # Read strategy ``` -------------------------------- ### brother_ql_create Help Output Source: https://github.com/pklaus/brother_ql/blob/master/LEGACY.md The help output for `brother_ql_create` details positional arguments like image and outfile, and optional arguments for printer model, label size, rotation, dithering, compression, and more. ```bash usage: brother_ql_create [-h] [--model MODEL] [--label-size LABEL_SIZE] [--rotate {0,90,180,270}] [--threshold THRESHOLD] [--dither] [--compress] [--red] [--600dpi] [--no-cut] [--loglevel LOGLEVEL] image [outfile] positional arguments: image The image file to create a label from. outfile The file to write the instructions to. Defaults to stdout. optional arguments: -h, --help show this help message and exit --model MODEL, -m MODEL The printer model to use. Check available ones with `brother_ql_info list-models`. --label-size LABEL_SIZE, -s LABEL_SIZE The label size (and kind) to use. Check available ones with `brother_ql_info list-label-sizes`. --rotate {0,90,180,270}, -r {0,90,180,270} Rotate the image (counterclock-wise) by this amount of degrees. --threshold THRESHOLD, -t THRESHOLD The threshold value (in percent) to discriminate between black and white pixels. --dither, -d Enable dithering when converting the image to b/w. If set, --threshold is meaningless. --compress, -c Enable compression (if available with the model). Takes more time but results in smaller file size. --red Create a label to be printed on black/red/white tape (only with QL-8xx series on DK-22251 labels). You must use this option when printing on black/red tape, even when not printing red. --600dpi Print with 600x300 dpi available on some models. Provide your image as 600x600 dpi; perpendicular to the feeding the image will be resized to 300dpi. --no-cut Don't cut the tape after printing the label. --loglevel LOGLEVEL Set to DEBUG for verbose debugging output to stderr. ``` -------------------------------- ### Get Element by Identifier Source: https://github.com/pklaus/brother_ql/blob/master/_autodocs/11-utilities.md Retrieves a specific element using its unique identifier. Raises a ValueError if the identifier is not found. ```python def get_element_by_identifier(self, identifier: str): ``` -------------------------------- ### BrotherQLRaster Instance Configuration Source: https://github.com/pklaus/brother_ql/blob/master/_autodocs/09-configuration.md Configure instance attributes like exception handling, automatic cutting, and color printing before conversion. Ensure two_color_printing is set before calling add_media_and_quality(). ```python from brother_ql.raster import BrotherQLRaster from brother_ql.conversion import convert # Configure raster object qlr = BrotherQLRaster('QL-810W') qlr.exception_on_warning = True # Fail on unsupported features qlr.cut_at_end = True # Cut tape after label qlr.two_color_printing = False # Set before conversion # Configure conversion convert( qlr=qlr, images=['label.png'], label='62red', # Cutting options cut=True, # Image processing dither=False, # Disable dithering compress=True, # Enable compression threshold=70, # B/W threshold rotate='auto', # Auto-rotate if needed # Advanced options dpi_600=False, # Standard 300 DPI hq=True, # High quality red=True, # Two-color mode ) ``` -------------------------------- ### Type Hints for Label Initialization Source: https://github.com/pklaus/brother_ql/blob/master/_autodocs/08-types.md Illustrates the type hints for the `__init__` method of a Label class, detailing parameters for tape size, form factor, and printer dimensions. ```python # Label initialization def __init__( identifier: str, tape_size: Tuple[int, int], form_factor: FormFactor, dots_total: Tuple[int, int], dots_printable: Tuple[int, int], offset_r: int, feed_margin: int = 0, restricted_to_models: List[str] = [], color: Color = Color.BLACK_WHITE ) ``` -------------------------------- ### Initialize BrotherQLRaster Source: https://github.com/pklaus/brother_ql/blob/master/_autodocs/01-brotherqlraster.md Initializes the printer to its default state. This method resets the printer and sets the page number to 0. It's typically the first command sent. ```python qlr = BrotherQLRaster('QL-710W') qlr.add_initialize() ``` -------------------------------- ### mtype, mwidth, mlength Properties Source: https://github.com/pklaus/brother_ql/blob/master/_autodocs/01-brotherqlraster.md Properties to get or set media type, width, and length for print media information. ```APIDOC ## Properties ### mtype Media type for print media information. ```python @property def mtype(self): """Media type (byte value)""" @mtype.setter def mtype(self, value): """Set media type""" ``` ### mwidth Media width for print media information. ```python @property def mwidth(self): """Media width (byte value)""" @mwidth.setter def mwidth(self, value): """Set media width""" ``` ### mlength Media length for print media information. ```python @property def mlength(self): """Media length (byte value)""" @mlength.setter def mlength(self, value): """Set media length""" ``` ### Usage ```python qlr.mtype = 0x0A # Continuous tape qlr.mwidth = 62 # 62mm tape qlr.mlength = 0 # Endless (no fixed length) ``` ``` -------------------------------- ### Get Printer Pixel Width Source: https://github.com/pklaus/brother_ql/blob/master/_autodocs/01-brotherqlraster.md Retrieves the pixel width in dots for the printer model. Returns 720 for standard models. ```python def get_pixel_width(self): """ Returns: int Pixel width in dots (8 bits per byte × bytes_per_row) """ pass ``` ```python qlr = BrotherQLRaster('QL-710W') width = qlr.get_pixel_width() # Returns 720 for standard models ``` -------------------------------- ### Create Label Instruction File Source: https://github.com/pklaus/brother_ql/blob/master/LEGACY.md Use `brother_ql_create` to generate a binary instruction file for Brother QL printers from a PNG, GIF, or JPEG image. Specify the printer model and optionally output file. ```bash brother_ql_create --model QL-500 ./720x300_monochrome.png > 720x300_monochrome.bin ``` -------------------------------- ### Configure PyUSB Backend Source: https://github.com/pklaus/brother_ql/blob/master/_autodocs/09-configuration.md Set up the PyUSB backend for communication with the printer. Timeout and read strategy can be configured. ```python from brother_ql.backends.pyusb import BrotherQLBackendPyUSB backend = BrotherQLBackendPyUSB('usb://0x04f9:0x2015/C5Z315686') # Configuration attributes backend.read_timeout = 10.0 # ms (default) backend.write_timeout = 15000.0 # ms (default) backend.strategy = 'try_twice' # Read strategy ``` -------------------------------- ### Configure Linux Kernel Backend Source: https://github.com/pklaus/brother_ql/blob/master/_autodocs/09-configuration.md Set up the Linux kernel backend for communication with the printer via the /dev/usb/lp0 device. Timeout and read strategy can be configured. ```python from brother_ql.backends.linux_kernel import BrotherQLBackendLinuxKernel backend = BrotherQLBackendLinuxKernel('/dev/usb/lp0') # Configuration attributes backend.read_timeout = 0.01 # seconds (default) backend.strategy = 'select' # Read strategy ``` -------------------------------- ### Default Printer Configuration and Conversion Source: https://github.com/pklaus/brother_ql/blob/master/_autodocs/09-configuration.md Initializes the `BrotherQLRaster` with default settings and demonstrates standard conversion options for printing labels. This includes setting up cutting, compression, and color modes before sending the data to the printer. ```python from brother_ql.raster import BrotherQLRaster from brother_ql.conversion import convert from brother_ql.backends.helpers import send # Initialize with defaults qlr = BrotherQLRaster('QL-710W') # Standard configuration qlr.exception_on_warning = False # Log warnings, don't crash qlr.cut_at_end = True # Cut automatically qlr.two_color_printing = False # No two-color # Convert with standard options convert( qlr=qlr, images=['label.png'], label='62', cut=True, compress=True, dither=False, threshold=70, red=False, rotate='auto', dpi_600=False, hq=True ) # Send to printer send( instructions=qlr.data, printer_identifier='tcp://192.168.1.21:9100', blocking=True ) ``` -------------------------------- ### PyUSB Backend Constructor Source: https://github.com/pklaus/brother_ql/blob/master/_autodocs/05-backends.md Initializes the PyUSB backend, accepting a device specifier which can be a string or a PyUSB Device object. String formats include 'usb://...' with vendor/product IDs and optional serial number, or just vendor/product IDs. ```python class BrotherQLBackendPyUSB(BrotherQLBackendGeneric): def __init__(self, device_specifier): pass ``` -------------------------------- ### Get Model by Identifier Source: https://github.com/pklaus/brother_ql/blob/master/_autodocs/04-models.md Retrieves a specific printer model object using its unique identifier string. Raises ValueError if the identifier is not found. ```python from brother_ql.models import ModelsManager mm = ModelsManager() model = mm.get_model_by_identifier('QL-710W') print(model.two_color) # False print(model.compression) # True ``` -------------------------------- ### CLI: List Supported Models and Labels Source: https://github.com/pklaus/brother_ql/blob/master/_autodocs/00-index.md Command-line interface commands to list all supported printer models and label types available in the library. ```bash # List supported models brother_ql info models # List supported labels brother_ql info labels ``` -------------------------------- ### BrotherQLRaster Initialization Source: https://github.com/pklaus/brother_ql/blob/master/_autodocs/01-brotherqlraster.md Initializes the BrotherQLRaster class with a specified printer model. The model identifier determines the printer's capabilities and command set. ```APIDOC ## BrotherQLRaster Constructor ### Description Initializes the BrotherQLRaster class with a specified printer model. The model identifier determines the printer's capabilities and command set. ### Parameters #### Path Parameters - **model** (str) - Required - Printer model identifier (e.g., 'QL-500', 'QL-710W') ### Raises - BrotherQLUnknownModel: If the provided model is not supported. ``` -------------------------------- ### Initialize Linux Kernel Backend Source: https://github.com/pklaus/brother_ql/blob/master/_autodocs/05-backends.md Initializes the Linux kernel backend for connecting to USB printers using device files. The device specifier can be a file path or an integer file descriptor obtained from os.open(). ```python from brother_ql.backends.linux_kernel import BrotherQLBackendLinuxKernel # Example: Connect using a file path # backend = BrotherQLBackendLinuxKernel('/dev/usb/lp0') # Example: Connect using a full URI format # backend = BrotherQLBackendLinuxKernel('file:///dev/usb/lp0') # Example: Connect using an integer file descriptor # import os # fd = os.open('/dev/usb/lp0', os.O_RDWR) # backend = BrotherQLBackendLinuxKernel(fd) ``` -------------------------------- ### Global Options Syntax Source: https://github.com/pklaus/brother_ql/blob/master/_autodocs/07-cli-reference.md The general syntax for using the brother_ql command with global options and a command. ```bash brother_ql [GLOBAL_OPTIONS] COMMAND [ARGS] ``` -------------------------------- ### List Available Label Sizes Source: https://github.com/pklaus/brother_ql/blob/master/_autodocs/07-cli-reference.md Lists all supported label sizes that can be used with the brother_ql tool. ```bash # Check available labels brother_ql info labels ``` -------------------------------- ### Check if Label Supports Two-Color Printing Source: https://github.com/pklaus/brother_ql/blob/master/_autodocs/08-types.md Example showing how to check if a label supports two-color printing using the Color enumeration. Requires initializing LabelsManager. ```python from brother_ql.labels import LabelsManager, Color lm = LabelsManager() label = lm.get_label_by_identifier('62red') if label.color == Color.BLACK_RED_WHITE: print("This label supports two-color printing") ``` -------------------------------- ### CLI Global Options Source: https://github.com/pklaus/brother_ql/blob/master/_autodocs/00-index.md Global command-line interface options for the brother_ql package. Specify backend, printer model, identifier, and debug logging. ```bash -b, --backend pyusb, network, linux_kernel -m, --model Printer model (e.g., QL-710W) -p, --printer Printer identifier --debug Enable debug logging ``` -------------------------------- ### BrotherQLReader Constructor Source: https://github.com/pklaus/brother_ql/blob/master/_autodocs/10-reader.md Initializes the BrotherQLReader with a file object or bytes. This sets up the reader for analyzing the instruction file. ```python def __init__(self, f): ``` -------------------------------- ### Check if Label is Endless Form Factor Source: https://github.com/pklaus/brother_ql/blob/master/_autodocs/08-types.md Example demonstrating how to check if a label's form factor is endless using the FormFactor enumeration. Requires initializing LabelsManager. ```python from brother_ql.labels import LabelsManager, FormFactor lm = LabelsManager() label = lm.get_label_by_identifier('62') if label.form_factor == FormFactor.ENDLESS: print("This is an endless label") ``` -------------------------------- ### List Available Labels Source: https://github.com/pklaus/brother_ql/blob/master/README.md Shows how to list all available label types and their corresponding printable pixel dimensions using the `brother_ql info labels` command. This is useful for determining the correct label size for printing. ```bash brother_ql info labels ``` -------------------------------- ### BrotherQLBackendPyUSB.__init__(device_specifier) Source: https://github.com/pklaus/brother_ql/blob/master/_autodocs/05-backends.md Initializes the PyUSB backend for connecting to USB printers. It accepts a device specifier which can be a string or a PyUSB Device object. ```APIDOC ## BrotherQLBackendPyUSB.__init__(device_specifier) ### Description Constructor for the PyUSB backend. ### Method `__init__(self, device_specifier)` ### Parameters #### Path Parameters - **device_specifier** (str or usb.core.Device) - Required - USB device identifier or PyUSB Device object ### String Format: `usb://0x{vendor_id}:0x{product_id}[/{serial_number}]` ### Examples: - `'usb://0x04f9:0x2015/C5Z315686'` - Full identifier with serial - `'0x04f9:0x2015'` - Vendor and product IDs only - PyUSB Device object directly ### Raises: ValueError if device not found ``` -------------------------------- ### Get Pixel Width for Image Preparation Source: https://github.com/pklaus/brother_ql/blob/master/_autodocs/04-models.md Calculates the pixel width required for image preparation based on the printer model's raster format. This is crucial for ensuring images are correctly sized before printing. ```python from brother_ql.models import ModelsManager mm = ModelsManager() model = mm.get_model_by_identifier('QL-710W') pixel_width = model.number_bytes_per_row * 8 print(f"Image pixel width: {pixel_width}") # 720 dots for standard models ``` -------------------------------- ### Typical Brother QL Raster Usage Pattern Source: https://github.com/pklaus/brother_ql/blob/master/_autodocs/01-brotherqlraster.md Demonstrates a common workflow for creating and sending print jobs using BrotherQLRaster, conversion utilities, and backend helpers. Requires printer connection details. ```python from brother_ql.raster import BrotherQLRaster from brother_ql.conversion import convert from PIL import Image # Create raster object for specific printer model qlr = BrotherQLRaster('QL-710W') qlr.exception_on_warning = True # Convert image(s) to raster instructions images = ['label1.png'] label_size = '62' # 62mm endless tape instructions = convert( qlr=qlr, images=images, label=label_size, cut=True, compress=True ) # Send to printer from brother_ql.backends.helpers import send send( instructions=qlr.data, printer_identifier='tcp://192.168.1.21:9100', backend_identifier='network' ) ``` -------------------------------- ### Get Printable Area for Image Preparation (Endless Tape) Source: https://github.com/pklaus/brother_ql/blob/master/_autodocs/03-labels.md Retrieves the printable dimensions in dots for a given label identifier, specifically for endless tape. Use this to determine the required image width for continuous feed labels. ```python from brother_ql.labels import LabelsManager lm = LabelsManager() label = lm.get_label_by_identifier('62') # For 62mm endless tape at 300 DPI width_dots, height_dots = label.dots_printable print(f"Image should be {width_dots} pixels wide") # Output: Image should be 696 pixels wide # Height can be any value ``` -------------------------------- ### Print Label Instruction File using brother_ql_print (Network) Source: https://github.com/pklaus/brother_ql/blob/master/LEGACY.md Utilize the `brother_ql_print` Python tool to send label instructions to a printer over the network. Specify the backend as 'network' and provide the TCP connection string. ```bash brother_ql_print --backend network 720x151_monochrome.bin tcp://192.168.0.23:9100 ``` -------------------------------- ### Initialize Network Backend Source: https://github.com/pklaus/brother_ql/blob/master/_autodocs/05-backends.md Initializes the network backend for connecting to WiFi/Ethernet-enabled printers via TCP socket. The device specifier can be a hostname or IP address, optionally with a port number. ```python from brother_ql.backends.network import BrotherQLBackendNetwork # Example: Connect to a printer at IP 192.168.1.21 with default port 9100 backend = BrotherQLBackendNetwork('tcp://192.168.1.21') # Example: Connect to a printer using hostname and explicit port # backend = BrotherQLBackendNetwork('tcp://printer.local:9100') # Example: Connect using IP and port without 'tcp://' prefix # backend = BrotherQLBackendNetwork('192.168.1.21:9100') ``` -------------------------------- ### Print a Label from Image File Source: https://github.com/pklaus/brother_ql/blob/master/_autodocs/00-index.md This snippet demonstrates the basic workflow for printing a label from an image file using the brother_ql package. It initializes the rasterizer, converts an image to printer instructions, and sends the data to a network-connected printer. ```python from brother_ql.raster import BrotherQLRaster from brother_ql.conversion import convert from brother_ql.backends.helpers import send qlr = BrotherQLRaster('QL-710W') convert(qlr=qlr, images=['label.png'], label='62', cut=True) send(instructions=qlr.data, printer_identifier='tcp://192.168.1.21:9100') ``` -------------------------------- ### Analyze Instruction File with BrotherQLReader Source: https://github.com/pklaus/brother_ql/blob/master/_autodocs/10-reader.md Opens and analyzes a binary instruction file using BrotherQLReader. Sets a filename format for extracted files and performs the analysis. Useful for extracting instructions from a .bin file. ```python from brother_ql.reader import BrotherQLReader # Open and analyze instruction file with open('my_instructions.bin', 'rb') as f: reader = BrotherQLReader(f) reader.filename_fmt = 'extracted_{counter:03d}.png' reader.analyse() # Output: extracted_000.png, extracted_001.png, etc. ``` -------------------------------- ### add_initialize() Source: https://github.com/pklaus/brother_ql/blob/master/_autodocs/01-brotherqlraster.md Initializes the printer by sending the ESC @ command. This resets the printer to its initial state and resets the page number to 0. ```APIDOC ## add_initialize() ### Description Initializes the printer by sending the ESC @ command. This resets the printer to its initial state and resets the page number to 0. ### Method POST ### Endpoint /initialize ### Effect Adds ESC @ command to instruction data. Increments page_number to 0. ### Example ```python qlr = BrotherQLRaster('QL-710W') qlr.add_initialize() ``` ``` -------------------------------- ### BrotherQLReader analyse Method Source: https://github.com/pklaus/brother_ql/blob/master/_autodocs/10-reader.md Parses and decodes the instruction file, extracts embedded image data, saves images as PNG, and prints analysis output to the console. ```python def analyse(self) -> None: ``` -------------------------------- ### Send Pre-generated Instruction File Source: https://github.com/pklaus/brother_ql/blob/master/_autodocs/07-cli-reference.md Sends a pre-created binary instruction file directly to the printer. This is useful for using instruction files generated by legacy tools. ```bash # Send pre-created instruction file brother_ql -m QL-710W -p "tcp://192.168.1.21" send instructions.bin ``` -------------------------------- ### List Available Backends Source: https://github.com/pklaus/brother_ql/blob/master/_autodocs/05-backends.md This constant provides a list of all backend names that are supported by the library. ```python available_backends = ['pyusb', 'network', 'linux_kernel'] ``` -------------------------------- ### Brother QL CLI Usage Source: https://github.com/pklaus/brother_ql/blob/master/README.md Displays the general usage and available options for the `brother_ql` command-line tool. This includes backend selection, model specification, and printer identification. ```bash Usage: brother_ql [OPTIONS] COMMAND [ARGS]... Command line interface for the brother_ql Python package. Options: -b, --backend [pyusb|network|linux_kernel] -m, --model [QL-500|QL-550|QL-560|QL-570|QL-580N|QL-650TD|QL-700|QL-710W|QL-720NW|QL-800|QL-810W|QL-820NWB|QL-1050|QL-1060N|QL-1100|QL-1110NWB|QL-1115NWB] -p, --printer PRINTER_IDENTIFIER The identifier for the printer. This could be a string like tcp://192.168.1.21:9100 for a networked printer or usb://0x04f9:0x2015/000M6Z401370 for a printer connected via USB. --debug --version Show the version and exit. --help Show this message and exit. Commands: analyze interpret a binary file containing raster... discover find connected label printers info list available labels, models etc. print Print a label send send an instruction file to the printer ``` -------------------------------- ### Print Label Instruction File via USB Source: https://github.com/pklaus/brother_ql/blob/master/LEGACY.md Send a binary label instruction file directly to a Brother QL printer connected via USB by redirecting its content to the device file. ```bash cat my_label.bin > /dev/usb/lp1 ``` -------------------------------- ### Print Label Instruction File using brother_ql_print (USB with Serial) Source: https://github.com/pklaus/brother_ql/blob/master/LEGACY.md Send label instructions to a specific Brother QL printer via USB using `brother_ql_print`, identifying the printer by its unique serial number. This is useful when multiple printers are connected. ```bash brother_ql_print 720x151_monochrome.bin usb://0x04f9:0x2015/000M6Z401370 ``` -------------------------------- ### Analyze Binary Instruction File (Custom Filename Format) Source: https://github.com/pklaus/brother_ql/blob/master/_autodocs/07-cli-reference.md Analyzes a binary instruction file and saves the extracted raster data as PNG images using a custom filename format. ```bash # Custom filename format brother_ql analyze -f "page_{counter:02d}.png" instructions.bin ``` -------------------------------- ### Enable Compression for Labels Source: https://github.com/pklaus/brother_ql/blob/master/_autodocs/09-configuration.md Enable PackBits compression for reducing instruction file size. This is supported by most newer models. Note that compression may slightly increase processing time. ```python convert(qlr=qlr, images=['label.png'], label='62', compress=True) ``` ```python qlr.add_compression(True) ``` -------------------------------- ### Lenient Mode: Log and Continue Source: https://github.com/pklaus/brother_ql/blob/master/_autodocs/06-exceptions.md Configure the library to log warnings for unsupported features but continue execution without raising exceptions. This is the default behavior for warnings. ```python from brother_ql import BrotherQLRaster import logging logging.basicConfig(level=logging.WARNING) qlr = BrotherQLRaster('QL-710W') qlr.exception_on_warning = False # Default behavior # Unsupported features are logged but don't raise exceptions # Continue execution with warnings ``` -------------------------------- ### Enable Debug Logging for Troubleshooting Source: https://github.com/pklaus/brother_ql/blob/master/_autodocs/07-cli-reference.md Enables debug logging for the brother_ql command, which can help diagnose issues by providing detailed output during execution. ```bash # Enable debug logging brother_ql --debug -m QL-710W -p "tcp://192.168.1.21:9100" print -l 62 label.png ``` -------------------------------- ### CLI: Discover and Print Labels Source: https://github.com/pklaus/brother_ql/blob/master/_autodocs/00-index.md Command-line interface commands for discovering USB printers and printing a label from a file to a specified printer. ```bash # Discover USB printers brother_ql --backend pyusb discover # Print label brother_ql -m QL-710W -p "tcp://192.168.1.21:9100" print -l 62 label.png ``` -------------------------------- ### Analyze Binary Instruction File (Default Output) Source: https://github.com/pklaus/brother_ql/blob/master/_autodocs/07-cli-reference.md Analyzes a binary instruction file and extracts raster data, saving it as PNG images with default filenames (label0000.png, etc.). ```bash # Analyze instruction file brother_ql analyze my_instructions.bin ``` -------------------------------- ### Label Constructor Source: https://github.com/pklaus/brother_ql/blob/master/_autodocs/03-labels.md Initializes a Label object with detailed specifications. All parameters except feed_margin and restricted_to_models are required. ```python def __init__(self, identifier: str, tape_size: Tuple[int, int], form_factor: FormFactor, dots_total: Tuple[int, int], dots_printable: Tuple[int, int], offset_r: int, feed_margin: int = 0, restricted_to_models: List[str] = None, color: Color = Color.BLACK_WHITE ): ``` -------------------------------- ### log_discovered_devices(available_devices, level=logging.INFO) Source: https://github.com/pklaus/brother_ql/blob/master/_autodocs/11-utilities.md Logs information about discovered printer devices to the console at a specified logging level. Includes device identifier and model if available. ```APIDOC ## log_discovered_devices(available_devices, level=logging.INFO) ### Description Log discovered printer devices. ### Method `log_discovered_devices(available_devices: list, level=logging.INFO) -> None` ### Parameters #### Path Parameters - **available_devices** (list[dict]) - Required - Devices from backend discovery - **level** (int) - Optional - Logging level (default: INFO) ### Effect Logs each device with identifier and model (if known) ### Example ```python from brother_ql.backends.helpers import discover from brother_ql.output_helpers import log_discovered_devices devices = discover('pyusb') log_discovered_devices(devices) ``` ``` -------------------------------- ### Type Hints for convert Function Source: https://github.com/pklaus/brother_ql/blob/master/_autodocs/08-types.md Details the type hints for the `convert` function, specifying expected inputs like raster objects and images, and the byte output. ```python # Convert function def convert( qlr: BrotherQLRaster, images: Union[List[str], List[Image.Image]], label: str, **kwargs: Dict[str, Union[bool, int, float, str]] ) -> bytes ``` -------------------------------- ### Mixed Global Options (CLI Precedence) Source: https://github.com/pklaus/brother_ql/blob/master/_autodocs/07-cli-reference.md Demonstrates how command-line options override environment variables when both are set. ```bash # Mixed (CLI takes precedence) export BROTHER_QL_MODEL=QL-710W brother_ql --backend network print -l 62 label.png ``` -------------------------------- ### Setting Print Quality Directly Source: https://github.com/pklaus/brother_ql/blob/master/_autodocs/09-configuration.md Set the pquality attribute directly on the BrotherQLRaster object to control print quality. True for high quality, False for low quality. ```python qlr.pquality = True # High quality qlr.pquality = False # Low quality ``` -------------------------------- ### Brother QL Print Command Usage Source: https://github.com/pklaus/brother_ql/blob/master/README.md Details the usage and options for the `print` command, which is used to print labels from image files. Options include label size, rotation, thresholding, dithering, and compression. ```bash Usage: brother_ql print [OPTIONS] IMAGE [IMAGE] ... Print a label of the provided IMAGE. Options: -l, --label [12|29|38|50|54|62|102|103|17x54|17x87|23x23|29x42|29x90|39x90|39x48|52x29|62x29|62x100|102x51|102x152|103x164|d12|d24|d58] The label (size, type - die-cut or endless). Run `brother_ql info labels` for a full list including ideal pixel dimensions. -r, --rotate [auto|0|90|180|270] Rotate the image (counterclock-wise) by this amount of degrees. -t, --threshold FLOAT The threshold value (in percent) to discriminate between black and white pixels. -d, --dither Enable dithering when converting the image to b/w. If set, --threshold is meaningless. -c, --compress Enable compression (if available with the model). Label creation can take slightly longer but the resulting instruction size is normally considerably smaller. --red Create a label to be printed on black/red/white tape (only with QL-8xx series on DK-22251 labels). You must use this option when printing on black/red tape, even when not printing red. --600dpi Print with 600x300 dpi available on some models. Provide your image as 600x600 dpi; perpendicular to the feeding the image will be resized to 300dpi. --lq Print with low quality (faster). Default is high quality. --no-cut Don't cut the tape after printing the label. --help Show this message and exit. ``` -------------------------------- ### File Organization of brother_ql Package Source: https://github.com/pklaus/brother_ql/blob/master/_autodocs/00-index.md The directory structure of the brother_ql Python package. Shows the location of core modules, backends, and legacy tools. ```tree brother_ql/ ├── __init__.py # Package exports (BrotherQLRaster, create_label, exceptions) ├── raster.py # BrotherQLRaster class ├── conversion.py # convert() function ├── labels.py # Label and LabelsManager classes ├── models.py # Model and ModelsManager classes ├── helpers.py # ElementsManager base class ├── exceptions.py # Exception classes ├── reader.py # BrotherQLReader class, response parsing ├── image_trafos.py # Image processing utilities ├── output_helpers.py # Output formatting ├── cli.py # Command line interface ├── backends/ │ ├── __init__.py # Backend factory and utilities │ ├── generic.py # BrotherQLBackendGeneric base class │ ├── pyusb.py # PyUSB backend │ ├── network.py # Network (TCP) backend │ ├── linux_kernel.py # Linux kernel backend │ └── helpers.py # discover() and send() functions └── legacy/ ├── brother_ql_create.py # Legacy CLI tool ├── brother_ql_print.py # Legacy CLI tool └── ... ``` -------------------------------- ### Strict Error Handling (Fail Fast) Source: https://github.com/pklaus/brother_ql/blob/master/_autodocs/06-exceptions.md This pattern shows how to configure the BrotherQLRaster object to raise exceptions for warnings by setting `exception_on_warning = True`. It then uses a try-except block to catch any BrotherQLError, ensuring immediate failure on errors. ```python from brother_ql import BrotherQLRaster, BrotherQLError try: qlr = BrotherQLRaster('QL-710W') qlr.exception_on_warning = True # ... conversion and printing code ... except BrotherQLError as e: print(f"Fatal error: {e}") exit(1) ``` -------------------------------- ### discover Source: https://github.com/pklaus/brother_ql/blob/master/_autodocs/11-utilities.md Discovers printers available via a specific backend. It returns a list of devices, each with an 'identifier' and 'instance' key. ```APIDOC ## discover(backend_identifier='linux_kernel') ### Description Discover printers available via a specific backend. ### Method None (Function Call) ### Endpoint None (Function Call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **backend_identifier** (str) - Backend name: 'pyusb', 'network', or 'linux_kernel' (default: linux_kernel) ### Returns list[dict] - List of devices with 'identifier' and 'instance' keys ### Raises NotImplementedError if backend discovery not implemented (e.g., network backend) ``` -------------------------------- ### Discover USB Devices (Linux Kernel) Source: https://github.com/pklaus/brother_ql/blob/master/_autodocs/05-backends.md Discovers USB printers available via /dev/usb/lp* device files on Linux systems. It returns a list of dictionaries, each containing a 'identifier' in URI format and 'instance' as None. ```python from brother_ql.backends.linux_kernel import list_available_devices devices = list_available_devices() for device in devices: print(f"Found: {device['identifier']}") # Output: Found: file:///dev/usb/lp0 ```