### Run Example Script Source: https://github.com/klemen1337/node-thermal-printer/blob/master/README.md Execute example scripts via the command line, specifying the printer connection type. ```bash node examples/example.js tcp://xxx.xxx.xxx.xxx ``` ```bash node examples/example.js 'printer:My Printer' ``` ```bash node examples/example.js '\\.\\COM1' ``` -------------------------------- ### Installation Source: https://context7.com/klemen1337/node-thermal-printer/llms.txt Install the node-thermal-printer package using npm. For Linux systems, ensure build-essentials is installed. ```APIDOC ## Installation Install the package via npm to add thermal printer support to your Node.js application. ```bash npm install node-thermal-printer # Linux requires build-essentials sudo apt-get install build-essential ``` ``` -------------------------------- ### Install Build Essentials on Linux Source: https://github.com/klemen1337/node-thermal-printer/blob/master/README.md On Linux systems, the build-essentials package is required. Install it using apt-get. ```bash sudo apt-get install build-essential ``` -------------------------------- ### Install Node Thermal Printer Source: https://github.com/klemen1337/node-thermal-printer/blob/master/README.md Install the node-thermal-printer package using npm. This is the primary installation command. ```bash npm install node-thermal-printer ``` -------------------------------- ### Network Printing Example Source: https://github.com/klemen1337/node-thermal-printer/blob/master/README.md Demonstrates network printing to a specified TCP address. Includes centering text, printing an image, and cutting the paper. Error handling for execution is included. ```javascript const ThermalPrinter = require("node-thermal-printer").printer; const PrinterTypes = require("node-thermal-printer").types; let printer = new ThermalPrinter({ type: PrinterTypes.EPSON, interface: 'tcp://xxx.xxx.xxx.xxx' }); printer.alignCenter(); printer.println("Hello world"); await printer.printImage('./assets/olaii-logo-black.png') printer.cut(); try { let execute = printer.execute() console.log("Print done!"); } catch (error) { console.error("Print failed:", error); } ``` -------------------------------- ### Install Node Thermal Printer Source: https://context7.com/klemen1337/node-thermal-printer/llms.txt Install the package via npm to add thermal printer support to your Node.js application. Linux users may need to install build-essential. ```bash npm install node-thermal-printer # Linux requires build-essentials sudo apt-get install build-essential ``` -------------------------------- ### 2D Barcode Generation Source: https://github.com/klemen1337/node-thermal-printer/blob/master/README.md Examples for generating various 2D barcodes including Code 128, QR Code, PDF417, and MaxiCode with customizable settings. ```javascript printer.code128("Code128", { width: "LARGE", // "SMALL", "MEDIUM", "LARGE", height: 80, // 50 < x < 80 text: 2 // 1 - No text // 2 - Text on bottom // 3 - No text inline // 4 - Text on bottom inline }); printer.printQR("QR Code", { cellSize: 3, // 1 - 8 correction: 'M', // L(7%), M(15%), Q(25%), H(30%) model: 2 // 1 - Model 1 // 2 - Model 2 (standard) // 3 - Micro QR }); printer.pdf417("PDF417", { rowHeight: 3, // 2 - 8 width: 3, // 2 - 8 correction: 1, // Ratio: 1 - 40 truncated: false, // boolean columns: 0 // 1 - 30, 0 auto }); printer.maxiCode("MaxiCode", { mode: 4, // 2 - Formatted/structured Carrier Message (US) // 3 - Formatted/structured Carrier Message (International) // 4 - Unformatted data with Standard Error Correction. // 5 - Unformatted data with Enhanced Error Correction. // 6 - For programming hardware devices. }); ``` -------------------------------- ### Get Printer Buffer Source: https://github.com/klemen1337/node-thermal-printer/blob/master/README.md Returns the raw printer buffer, which includes all accumulated commands, text, and data ready to be sent to the printer. ```javascript printer.getBuffer(); ``` -------------------------------- ### 1D Barcode Generation Source: https://github.com/klemen1337/node-thermal-printer/blob/master/README.md Generates a 1D barcode (GS1-128 example) with options for human-readable text position, font, width, and height. ```javascript var data = "GS1-128" // Barcode data (string or buffer) var type = 74 // Barcode type (See Reference) var settings = { // Optional Settings hriPos: 0, // Human readable character 0 - 3 (none, top, bottom, both) hriFont: 0, // Human readable character font width: 3, // Barcode width height: 168 // Barcode height } printer.printBarcode(data, type, settings); ``` -------------------------------- ### Get Print Buffer String Source: https://github.com/klemen1337/node-thermal-printer/blob/master/README.md Returns the current content of the printer's text buffer as a string. This does not include raw commands or image data. ```javascript printer.getText(); ``` -------------------------------- ### Printer Initialization and Basic Operations Source: https://github.com/klemen1337/node-thermal-printer/blob/master/README.md Demonstrates how to initialize the ThermalPrinter with different configurations and perform basic operations like checking connection and executing commands. ```APIDOC ## Printer Initialization and Basic Operations ### Description Initialize the ThermalPrinter with specified options and perform fundamental actions. ### Method Constructor ### Endpoint N/A ### Parameters #### Request Body - **type** (PrinterTypes) - Required - The type of the printer ('star' or 'epson'). - **width** (number) - Required - The number of characters per line. - **interface** (string) - Required - The printer interface (e.g., 'tcp://xxx.xxx.xxx.xxx'). - **characterSet** (CharacterSet) - Optional - The character set to use (default: PC852_LATIN2). - **removeSpecialCharacters** (boolean) - Optional - Whether to remove special characters (default: false). - **lineCharacter** (string) - Optional - The character used for drawing lines (default: '-'). - **breakLine** (BreakLine) - Optional - How to break lines ('WORD' or 'CHARACTERS', disabled with 'NONE', default: 'WORD'). - **options** (object) - Optional - Additional printer options. - **timeout** (number) - Optional - Connection timeout in milliseconds (default: 3000). ### Request Example ```javascript const { ThermalPrinter, PrinterTypes, CharacterSet, BreakLine } = require('node-thermal-printer'); const printer = new ThermalPrinter({ type: PrinterTypes.STAR, width: 48, interface: 'tcp://xxx.xxx.xxx.xxx', characterSet: CharacterSet.PC852_LATIN2, removeSpecialCharacters: false, lineCharacter: "=", breakLine: BreakLine.WORD, options:{ timeout: 5000 } }); ``` ### Methods - **isPrinterConnected()**: Checks if the printer is connected. Returns a boolean. - **execute()**: Executes all queued commands. Returns success or throws an error. - **raw(buffer)**: Prints raw buffer data instantly. Returns success or throws an error. ``` -------------------------------- ### Initialize Printer with Custom Driver Source: https://github.com/klemen1337/node-thermal-printer/blob/master/README.md Set up the ThermalPrinter using a custom driver, either during initialization or by calling `setPrinterDriver`. ```javascript const ThermalPrinter = require("node-thermal-printer").printer; const PrinterTypes = require("node-thermal-printer").types; let printer = new ThermalPrinter({ type: PrinterTypes.EPSON, interface: 'printer:My Printer', driver: MyCustomDriver }); // you can also set the driver after init: printer.setPrinterDriver(MyCustomDriver) ``` -------------------------------- ### Initialize Printer with System Driver Source: https://github.com/klemen1337/node-thermal-printer/blob/master/README.md Configure the ThermalPrinter with a system printer driver, automatically selecting or by name. Requires the 'printer' or 'electron-printer' module. ```javascript const ThermalPrinter = require("node-thermal-printer").printer; const PrinterTypes = require("node-thermal-printer").types; const electron = typeof process !== 'undefined' && process.versions && !!process.versions.electron; let printer = new ThermalPrinter({ type: PrinterTypes.EPSON, interface: 'printer:My Printer', driver: require(electron ? 'electron-printer' : 'printer') }); ``` -------------------------------- ### Initialize ThermalPrinter Instance Source: https://context7.com/klemen1337/node-thermal-printer/llms.txt Creates a new printer instance with configuration for printer type, connection interface, paper width, character encoding, and line breaking behavior. Ensure to select the correct PrinterTypes and CharacterSet for your printer. ```javascript const { ThermalPrinter, PrinterTypes, CharacterSet, BreakLine } = require('node-thermal-printer'); const printer = new ThermalPrinter({ type: PrinterTypes.EPSON, // PrinterTypes: EPSON, STAR, TANCA, DARUMA, BROTHER, CUSTOM interface: 'tcp://192.168.1.100:9100', // Network printer width: 48, // Characters per line (default: 48) characterSet: CharacterSet.PC852_LATIN2, // Character encoding removeSpecialCharacters: false, // Strip diacritics (default: false) lineCharacter: '-', // Character for drawLine() (default: '-') breakLine: BreakLine.WORD, // Line break mode: WORD, CHARACTER, NONE options: { timeout: 5000 // Network timeout in ms (default: 3000) } }); ``` -------------------------------- ### Print QR Code Source: https://github.com/klemen1337/node-thermal-printer/blob/master/README.md Prints a QR code from the provided string. ```javascript printer.printQR("QR CODE"); ``` -------------------------------- ### ThermalPrinter Constructor Source: https://context7.com/klemen1337/node-thermal-printer/llms.txt Initialize a new ThermalPrinter instance with configuration options for printer type, connection, paper width, character encoding, and line breaking. ```APIDOC ## ThermalPrinter Constructor Creates a new printer instance with configuration for printer type, connection interface, paper width, character encoding, and line breaking behavior. ```javascript const { ThermalPrinter, PrinterTypes, CharacterSet, BreakLine } = require('node-thermal-printer'); const printer = new ThermalPrinter({ type: PrinterTypes.EPSON, // PrinterTypes: EPSON, STAR, TANCA, DARUMA, BROTHER, CUSTOM interface: 'tcp://192.168.1.100:9100', // Network printer width: 48, // Characters per line (default: 48) characterSet: CharacterSet.PC852_LATIN2, // Character encoding removeSpecialCharacters: false, // Strip diacritics (default: false) lineCharacter: '-', // Character for drawLine() (default: '-') breakLine: BreakLine.WORD, // Line break mode: WORD, CHARACTER, NONE options: { timeout: 5000 // Network timeout in ms (default: 3000) } }); ``` ``` -------------------------------- ### Configure Printer Interface Options Source: https://context7.com/klemen1337/node-thermal-printer/llms.txt Configure the printer connection using network TCP, system printer driver, or direct file/port access. Choose the interface that matches your printer's connection method. ```javascript const { ThermalPrinter, PrinterTypes } = require('node-thermal-printer'); // Network printer (TCP/IP) const networkPrinter = new ThermalPrinter({ type: PrinterTypes.EPSON, interface: 'tcp://192.168.1.100:9100' // IP address with optional port }); // System printer via printer driver const systemPrinter = new ThermalPrinter({ type: PrinterTypes.EPSON, interface: 'printer:My Printer Name', // Specific printer by name driver: require('printer') // or 'electron-printer' for Electron apps }); // Auto-select system printer const autoPrinter = new ThermalPrinter({ type: PrinterTypes.STAR, interface: 'printer:auto', driver: require('printer') }); // Direct file/port (Windows COM port or Unix device) const directPrinter = new ThermalPrinter({ type: PrinterTypes.EPSON, interface: '\\.\\COM1' // Windows: COM1, Linux: /dev/usb/lp0 }); ``` -------------------------------- ### Print Table with Custom Settings Source: https://github.com/klemen1337/node-thermal-printer/blob/master/README.md Prints a table with custom settings for each column, including text, alignment, width ratio, column count, and bold formatting. ```javascript printer.tableCustom([ { text:"Left", align:"LEFT", width:0.5 }, { text:"Center", align:"CENTER", width:0.25, bold:true }, { text:"Right", align:"RIGHT", cols:8 } ]); ``` -------------------------------- ### Initialize Thermal Printer Source: https://github.com/klemen1337/node-thermal-printer/blob/master/README.md Configure and initialize a new ThermalPrinter instance. Specify printer type, dimensions, interface, character set, and other options. Ensure the correct printer type and interface are set for your hardware. ```javascript const { ThermalPrinter, PrinterTypes, CharacterSet, BreakLine } = require('node-thermal-printer'); const printer = new ThermalPrinter({ type: PrinterTypes.STAR, width: 48, interface: 'tcp://xxx.xxx.xxx.xxx', characterSet: CharacterSet.PC852_LATIN2, removeSpecialCharacters: false, lineCharacter: "=", breakLine: BreakLine.WORD, options:{ timeout: 5000 } }); ``` -------------------------------- ### Generate QR Code with printQR() Source: https://context7.com/klemen1337/node-thermal-printer/llms.txt Generate and print QR codes using printQR(). You can configure the size, error correction level, and model type for the QR code. ```javascript const { ThermalPrinter, PrinterTypes } = require('node-thermal-printer'); const printer = new ThermalPrinter({ type: PrinterTypes.EPSON, interface: 'tcp://192.168.1.100:9100' }); // Simple QR code with defaults printer.printQR('https://example.com'); // QR code with custom settings printer.printQR('https://example.com/receipt/12345', { cellSize: 6, // Module size: 1-8 (default: 3) correction: 'H', // Error correction: L(7%), M(15%), Q(25%), H(30%) model: 2 // Model: 1, 2 (standard), 3 (Micro QR) }); printer.newLine(); printer.println('Scan for digital receipt'); printer.cut(); await printer.execute(); ``` -------------------------------- ### Print Table with Equal Columns Source: https://github.com/klemen1337/node-thermal-printer/blob/master/README.md Prints an array of strings as a table, with each column having equal width. ```javascript printer.table(["One", "Two", "Three"]); ``` -------------------------------- ### Print PNG Images from Buffer with node-thermal-printer Source: https://context7.com/klemen1337/node-thermal-printer/llms.txt Demonstrates printing a PNG image directly from a buffer, useful for dynamically generated images like QR codes. Requires an external library (e.g., qr-image) to generate the buffer. ```javascript const { ThermalPrinter, PrinterTypes } = require('node-thermal-printer'); const qr = require('qr-image'); // External QR library async function printDynamicQR() { const printer = new ThermalPrinter({ type: PrinterTypes.EPSON, interface: 'tcp://192.168.1.100:9100' }); // Generate QR code as PNG buffer using external library const qrBuffer = qr.imageSync('https://example.com/order/12345', { type: 'png', margin: 0, size: 10, ec_level: 'M' }); printer.alignCenter(); printer.newLine(); await printer.printImageBuffer(qrBuffer); printer.newLine(); printer.println('Scan for order details'); printer.cut(); await printer.execute(); } ``` -------------------------------- ### Interface Options Source: https://context7.com/klemen1337/node-thermal-printer/llms.txt Configure the printer connection using various interface options including network (TCP/IP), system printer drivers, or direct file/port access. ```APIDOC ## Interface Options Configure the printer connection using network TCP, system printer driver, or direct file/port access. ```javascript const { ThermalPrinter, PrinterTypes } = require('node-thermal-printer'); // Network printer (TCP/IP) const networkPrinter = new ThermalPrinter({ type: PrinterTypes.EPSON, interface: 'tcp://192.168.1.100:9100' // IP address with optional port }); // System printer via printer driver const systemPrinter = new ThermalPrinter({ type: PrinterTypes.EPSON, interface: 'printer:My Printer Name', // Specific printer by name driver: require('printer') // or 'electron-printer' for Electron apps }); // Auto-select system printer const autoPrinter = new ThermalPrinter({ type: PrinterTypes.STAR, interface: 'printer:auto', driver: require('printer') }); // Direct file/port (Windows COM port or Unix device) const directPrinter = new ThermalPrinter({ type: PrinterTypes.EPSON, interface: '\\.\\COM1' // Windows: COM1, Linux: /dev/usb/lp0 }); ``` ``` -------------------------------- ### Print to Multiple Printers Simultaneously Source: https://context7.com/klemen1337/node-thermal-printer/llms.txt Instantiate multiple ThermalPrinter objects for different printers and execute print jobs in parallel using Promise.all. Ensure correct printer types and network interfaces are configured. ```javascript const { ThermalPrinter, PrinterTypes } = require('node-thermal-printer'); async function printToMultiplePrinters() { const kitchenPrinter = new ThermalPrinter({ type: PrinterTypes.EPSON, interface: 'tcp://192.168.1.100:9100' }); const barPrinter = new ThermalPrinter({ type: PrinterTypes.STAR, interface: 'tcp://192.168.1.101:9100' }); // Build order for kitchen kitchenPrinter.bold(true); kitchenPrinter.println('KITCHEN ORDER'); kitchenPrinter.bold(false); kitchenPrinter.println('Table 5 - Order #123'); kitchenPrinter.drawLine(); kitchenPrinter.println('1x Burger'); kitchenPrinter.println('1x Fries'); kitchenPrinter.cut(); // Build order for bar barPrinter.bold(true); barPrinter.println('BAR ORDER'); barPrinter.bold(false); barPrinter.println('Table 5 - Order #123'); barPrinter.drawLine(); barPrinter.println('2x Beer'); barPrinter.println('1x Soda'); barPrinter.cut(); // Print to both simultaneously await Promise.all([ kitchenPrinter.execute(), barPrinter.execute() ]); } ``` -------------------------------- ### Print Image Source: https://github.com/klemen1337/node-thermal-printer/blob/master/README.md Asynchronously prints a PNG image from the specified file path. Ensure the image is in PNG format and accessible. ```javascript await printer.printImage('./assets/olaii-logo-black.png'); ``` -------------------------------- ### Print PNG Images from File with node-thermal-printer Source: https://context7.com/klemen1337/node-thermal-printer/llms.txt Illustrates how to print a PNG image from a local file path using the printImage function. Includes basic error handling and fallback text if image printing fails. ```javascript const { ThermalPrinter, PrinterTypes } = require('node-thermal-printer'); async function printWithImage() { const printer = new ThermalPrinter({ type: PrinterTypes.EPSON, interface: 'tcp://192.168.1.100:9100' }); printer.alignCenter(); try { await printer.printImage('./logo.png'); // Only PNG format supported printer.newLine(); printer.println('Company Name'); printer.println('123 Main Street'); } catch (error) { console.error('Image print failed:', error); printer.println('[Logo]'); // Fallback } printer.drawLine(); printer.println('Thank you for your purchase!'); printer.cut(); await printer.execute(); } ``` -------------------------------- ### Apply Text Formatting (Bold, Underline, Invert) Source: https://context7.com/klemen1337/node-thermal-printer/llms.txt Controls text styling including bold, underline, thick underline, and inverted (white on black) modes. These styles remain active until explicitly disabled. Ensure the printer object is initialized. ```javascript const { ThermalPrinter, PrinterTypes } = require('node-thermal-printer'); const printer = new ThermalPrinter({ type: PrinterTypes.EPSON, interface: 'tcp://192.168.1.100:9100' }); printer.bold(true); printer.println('This text is bold'); printer.bold(false); printer.underline(true); printer.println('This text is underlined'); printer.underline(false); printer.underlineThick(true); printer.println('This text has thick underline'); printer.underlineThick(false); printer.invert(true); printer.println('White text on black background'); printer.invert(false); printer.upsideDown(true); printer.println('Upside down text (180° rotation)'); printer.upsideDown(false); printer.cut(); await printer.execute(); ``` -------------------------------- ### Barcode Settings Reference Source: https://github.com/klemen1337/node-thermal-printer/blob/master/README.md Details on available settings for customizing barcode output. ```APIDOC ## Barcode Settings Reference ### Settings characters | # | Description | |:-:|-------------------------------------------------------------------------------------|--------------------------| | 1 | No added under-bar characters. Executes line feed after printing a bar code | | 2 | Adds under-bar characters. Executes line feed after printing a bar code | | 3 | No added under-bar characters. Does not execute line feed after printing a bar code | | 4 | Adds under-bar characters. Does not execute line feed after printing a bar code | ### Settings mode | # | UPC-E, UPC-A, JAN/EAN8, JAN/EAN13, Code128, Code93 | Code39, NW-7 | ITF | |:-:|-----------------------------------------------------|--------------------------|---------------------------| | 1 | Minimum module 2 dots | Narrow: Wide = 2:6 dots | Narrow: Wide = 2:5 dots | | 2 | Minimum module 3 dots | Narrow: Wide = 3:9 dots | Narrow: Wide = 4:10 dots | | 3 | Minimum module 4 dots | Narrow: Wide = 4:12 dots | Narrow: Wide = 6:15 dots | | 4 | | Narrow: Wide = 2:5 dots | Narrow: Wide = 2:4 dots | | 5 | | Narrow: Wide = 3:8 dots | Narrow: Wide = 4:8 dots | | 6 | | Narrow: Wide = 4:10 dots | Narrow: Wide = 6:12 dots | | 7 | | Narrow: Wide = 2:4 dots | Narrow: Wide = 2:6 dots | | 8 | | Narrow: Wide = 3:6 dots | Narrow: Wide = 3:9 dots | | 9 | | Narrow: Wide = 4:8 dots | Narrow: Wide = 4:12 dots | ``` -------------------------------- ### Execute Print Buffer Source: https://context7.com/klemen1337/node-thermal-printer/llms.txt Sends the accumulated print buffer to the printer and returns a promise that resolves on success or rejects on error. Use options like `docname` for system printers and `waitForResponse` for network printers. ```javascript const { ThermalPrinter, PrinterTypes } = require('node-thermal-printer'); async function printReceipt() { const printer = new ThermalPrinter({ type: PrinterTypes.EPSON, interface: 'tcp://192.168.1.100:9100' }); printer.println('Hello World!'); printer.cut(); try { await printer.execute(); console.log('Print successful'); } catch (error) { console.error('Print failed:', error); } } // Execute with options await printer.execute({ docname: 'Receipt', // Document name for system printers waitForResponse: true // Wait for printer response (network only) }); ``` -------------------------------- ### Print Custom Column Widths with tableCustom() Source: https://context7.com/klemen1337/node-thermal-printer/llms.txt Use tableCustom() to print tables with custom column widths, alignment, and bold styling. It supports both proportional widths (0.0-1.0) and fixed character columns. ```javascript const { ThermalPrinter, PrinterTypes } = require('node-thermal-printer'); const printer = new ThermalPrinter({ type: PrinterTypes.EPSON, interface: 'tcp://192.168.1.100:9100', width: 48 }); // Using proportional widths (0.0 - 1.0) printer.tableCustom([ { text: 'Product', align: 'LEFT', width: 0.5, bold: true }, { text: 'Qty', align: 'CENTER', width: 0.2, bold: true }, { text: 'Price', align: 'RIGHT', width: 0.3, bold: true } ]); printer.drawLine(); printer.tableCustom([ { text: 'Espresso', align: 'LEFT', width: 0.5 }, { text: '2', align: 'CENTER', width: 0.2 }, { text: '$6.00', align: 'RIGHT', width: 0.3 } ]); printer.tableCustom([ { text: 'Cappuccino Grande', align: 'LEFT', width: 0.5 }, // Long text wraps { text: '1', align: 'CENTER', width: 0.2 }, { text: '$5.50', align: 'RIGHT', width: 0.3 } ]); // Using fixed character columns printer.newLine(); printer.tableCustom([ { text: 'Left', align: 'LEFT', cols: 16 }, { text: 'Center', align: 'CENTER', cols: 16, bold: true }, { text: 'Right', align: 'RIGHT', cols: 16 } ]); printer.cut(); await printer.execute(); ``` -------------------------------- ### Print Raw Data Source: https://github.com/klemen1337/node-thermal-printer/blob/master/README.md Prints raw data directly to the printer. Accepts a Buffer object. This method returns a promise that resolves on success or rejects with an error. ```javascript const raw = await printer.raw(Buffer.from("Hello world")); ``` -------------------------------- ### raw() - Send Raw Buffer Source: https://context7.com/klemen1337/node-thermal-printer/llms.txt Sends raw bytes directly to the printer, bypassing the print buffer. Useful for custom commands or pre-formatted data. ```APIDOC ## raw(buffer) ### Description Sends raw bytes directly to the printer, bypassing the print buffer. Useful for custom commands or pre-formatted data. ### Method This is a method of the ThermalPrinter class. ### Endpoint N/A (This is a library function, not a network endpoint). ### Parameters - **buffer** (Buffer) - Required - The buffer containing the raw bytes to send to the printer. ### Request Example ```javascript const { ThermalPrinter, PrinterTypes } = require('node-thermal-printer'); async function sendRawCommand() { const printer = new ThermalPrinter({ type: PrinterTypes.EPSON, interface: 'tcp://192.168.1.100:9100' }); // Send raw ESC/POS commands directly const initCommand = Buffer.from([0x1B, 0x40]); // ESC @ - Initialize printer await printer.raw(initCommand); // Send raw text await printer.raw(Buffer.from('Hello World\n')); // Cut command await printer.raw(Buffer.from([0x1D, 0x56, 0x00])); // GS V 0 - Full cut } ``` ### Response N/A (This function directly controls hardware and does not return a specific response payload). #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### Print 2D Barcodes (PDF417, MaxiCode) with node-thermal-printer Source: https://context7.com/klemen1337/node-thermal-printer/llms.txt Shows how to print PDF417 and MaxiCode 2D barcodes. Options for PDF417 include row height, width, error correction, truncation, and columns. MaxiCode supports different modes. ```javascript const { ThermalPrinter, PrinterTypes } = require('node-thermal-printer'); const printer = new ThermalPrinter({ type: PrinterTypes.EPSON, interface: 'tcp://192.168.1.100:9100' }); // PDF417 barcode printer.println('PDF417:'); printer.pdf417('Shipping label data with tracking info', { rowHeight: 3, // Row height: 2-8 width: 3, // Module width: 2-8 correction: 5, // Error correction ratio: 1-40 truncated: false, // Truncated variant columns: 0 // Columns: 1-30, 0=auto }); printer.newLine(); // MaxiCode (used by UPS) printer.println('MaxiCode:'); printer.maxiCode('96819501234567891', { mode: 4 // Mode: 2=US carrier, 3=Intl carrier, 4=standard, 5=enhanced, 6=programming }); printer.cut(); await printer.execute(); ``` -------------------------------- ### Control Cash Drawer Source: https://github.com/klemen1337/node-thermal-printer/blob/master/README.md Sends a command to open the cash drawer connected to the printer. ```javascript printer.openCashDrawer(); ``` -------------------------------- ### Open Cash Drawer Source: https://context7.com/klemen1337/node-thermal-printer/llms.txt Use this method to send the command to open an attached cash drawer. Ensure the cash drawer is properly connected to the printer. ```javascript const { ThermalPrinter, PrinterTypes } = require('node-thermal-printer'); async function completeSale() { const printer = new ThermalPrinter({ type: PrinterTypes.EPSON, interface: 'tcp://192.168.1.100:9100' }); printer.alignCenter(); printer.println('SALE COMPLETE'); printer.drawLine(); printer.leftRight('Total:', '$25.00'); printer.leftRight('Cash:', '$30.00'); printer.leftRight('Change:', '$5.00'); printer.drawLine(); printer.println('Thank you!'); printer.cut(); printer.openCashDrawer(); // Opens connected cash drawer await printer.execute(); } ``` -------------------------------- ### Execute Printer Commands Source: https://github.com/klemen1337/node-thermal-printer/blob/master/README.md Executes all accumulated print commands. This method returns a promise that resolves on success or rejects with an error if execution fails. ```javascript const execute = await printer.execute(); ``` -------------------------------- ### Buffer Management: getBuffer, setBuffer, clear Source: https://context7.com/klemen1337/node-thermal-printer/llms.txt Manage the internal print buffer. Use `getBuffer` to retrieve the current buffer content, `setBuffer` to load a buffer, and `clear` to empty it. This is useful for cloning print jobs or reusing data across different printers. ```javascript const { ThermalPrinter, PrinterTypes } = require('node-thermal-printer'); const printer1 = new ThermalPrinter({ type: PrinterTypes.EPSON, interface: 'tcp://192.168.1.100:9100' }); const printer2 = new ThermalPrinter({ type: PrinterTypes.EPSON, interface: 'tcp://192.168.1.101:9100' }); // Build print content printer1.println('Order #12345'); printer1.println('Table 5'); printer1.cut(); // Get buffer and print to both printers const buffer = printer1.getBuffer(); await printer1.execute(); // Send same content to second printer await printer2.raw(buffer); // Or use setBuffer for full control printer2.clear(); // Clear existing buffer printer2.setBuffer(buffer); // Set buffer to copy await printer2.execute(); // Get text representation (for debugging) console.log(printer1.getText()); // Get configured paper width console.log(printer1.getWidth()); // Returns: 48 ``` -------------------------------- ### Print Equal Width Columns with table() Source: https://context7.com/klemen1337/node-thermal-printer/llms.txt Use table() to print data in equally-spaced columns across the paper width. This is suitable for simple tabular data where column widths do not need to be customized. ```javascript const { ThermalPrinter, PrinterTypes } = require('node-thermal-printer'); const printer = new ThermalPrinter({ type: PrinterTypes.EPSON, interface: 'tcp://192.168.1.100:9100', width: 48 }); printer.bold(true); printer.table(['Item', 'Qty', 'Price', 'Total']); printer.bold(false); printer.drawLine(); printer.table(['Coffee', '2', '$4.50', '$9.00']); printer.table(['Muffin', '1', '$3.25', '$3.25']); printer.table(['Tea', '3', '$3.00', '$9.00']); printer.drawLine(); printer.table(['', '', 'Total:', '$21.25']); printer.cut(); await printer.execute(); ``` -------------------------------- ### execute() - Send Print Buffer Source: https://context7.com/klemen1337/node-thermal-printer/llms.txt Send the accumulated print buffer to the printer. This method returns a promise that resolves on success or rejects on error. It can also accept options for document naming and waiting for a response. ```APIDOC ## execute() - Send Print Buffer Sends the accumulated print buffer to the printer and returns a promise that resolves on success or rejects on error. ```javascript const { ThermalPrinter, PrinterTypes } = require('node-thermal-printer'); async function printReceipt() { const printer = new ThermalPrinter({ type: PrinterTypes.EPSON, interface: 'tcp://192.168.1.100:9100' }); printer.println('Hello World!'); printer.cut(); try { await printer.execute(); console.log('Print successful'); } catch (error) { console.error('Print failed:', error); } } // Execute with options await printer.execute({ docname: 'Receipt', // Document name for system printers waitForResponse: true // Wait for printer response (network only) }); ``` ``` -------------------------------- ### openCashDrawer() - Cash Drawer Control Source: https://context7.com/klemen1337/node-thermal-printer/llms.txt Sends a command to open an attached cash drawer by triggering a kick pulse. ```APIDOC ## openCashDrawer() ### Description Sends the command to open an attached cash drawer (kick pulse). ### Method This is a method of the ThermalPrinter class. ### Endpoint N/A (This is a library function, not a network endpoint). ### Parameters None ### Request Example ```javascript const { ThermalPrinter, PrinterTypes } = require('node-thermal-printer'); async function completeSale() { const printer = new ThermalPrinter({ type: PrinterTypes.EPSON, interface: 'tcp://192.168.1.100:9100' }); // ... other print commands ... printer.cut(); printer.openCashDrawer(); // Opens connected cash drawer await printer.execute(); } ``` ### Response N/A (This function directly controls hardware and does not return a specific response payload). #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### Set Character Set Source: https://github.com/klemen1337/node-thermal-printer/blob/master/README.md Sets the character set for the printer. This should match the `characterSet` option used during initialization or the printer's capabilities. ```javascript printer.setCharacterSet(CharacterSet.PC852_LATIN2); ``` -------------------------------- ### Text Formatting: Bold Source: https://github.com/klemen1337/node-thermal-printer/blob/master/README.md Enables or disables bold text formatting for subsequent prints. ```javascript printer.bold(true); ``` -------------------------------- ### Align Text (Left, Center, Right) Source: https://context7.com/klemen1337/node-thermal-printer/llms.txt Sets text alignment to left, center, or right. The chosen alignment affects all subsequent text until it is changed. Ensure the printer is initialized. ```javascript const { ThermalPrinter, PrinterTypes } = require('node-thermal-printer'); const printer = new ThermalPrinter({ type: PrinterTypes.EPSON, interface: 'tcp://192.168.1.100:9100' }); printer.alignLeft(); printer.println('Left aligned text'); printer.alignCenter(); printer.println('Center aligned text'); printer.alignRight(); printer.println('Right aligned text'); printer.alignLeft(); // Reset to left printer.cut(); await printer.execute(); ``` -------------------------------- ### Draw Lines and New Lines for Separators Source: https://context7.com/klemen1337/node-thermal-printer/llms.txt Creates visual separators using `drawLine()` with a specified character or the default line character, and inserts blank lines with `newLine()`. Configurable line character and width are set during initialization. ```javascript const { ThermalPrinter, PrinterTypes, BreakLine } = require('node-thermal-printer'); const printer = new ThermalPrinter({ type: PrinterTypes.EPSON, interface: 'tcp://192.168.1.100:9100', width: 48, lineCharacter: '-' // Default line character }); printer.println('Section 1'); printer.drawLine(); // Uses default '-' character printer.println('Section 2'); printer.drawLine('='); // Custom character printer.println('Section 3'); printer.drawLine('*'); printer.newLine(); // Empty line printer.newLine(); printer.println('After two blank lines'); printer.cut(); await printer.execute(); ``` -------------------------------- ### Text Formatting: Underline Source: https://github.com/klemen1337/node-thermal-printer/blob/master/README.md Enables or disables underline formatting for text. Use `underlineThick` for a thicker underline. ```javascript printer.underline(true); ``` -------------------------------- ### Print Barcode with Custom Settings Source: https://github.com/klemen1337/node-thermal-printer/blob/master/README.md Use this function to print barcodes with specified data, type, and optional settings like characters and mode. Ensure the barcode type and settings values are within the valid ranges specified in the documentation. ```javascript var data = "TEST" // Barcode data (string or buffer) var type = 7 // Barcode type (See Reference) var settings = { // Optional Settings characters: 1, // Add characters (See Reference) mode: 3, // Barcode mode (See Reference) height: 150, // Barcode height (0≤ height ≤255) } printer.printBarcode(data, type, settings); ``` -------------------------------- ### Text Alignment: Center Source: https://github.com/klemen1337/node-thermal-printer/blob/master/README.md Sets the text alignment to center for subsequent prints. ```javascript printer.alignCenter(); ``` -------------------------------- ### Configure Webpack for Browser Usage Source: https://github.com/klemen1337/node-thermal-printer/blob/master/README.md When using the module in a browser, network interfaces will not work. Configure webpack to ignore 'fs' and 'net' node dependencies. ```javascript new webpack.IgnorePlugin({ resourceRegExp: /^fs$|^net$/, }), ``` -------------------------------- ### Control Paper Cutting with node-thermal-printer Source: https://context7.com/klemen1337/node-thermal-printer/llms.txt Shows how to perform full cuts (cut()) and partial cuts (partialCut()) to separate printed receipts. The cut function can also accept an option for vertical tab amount. ```javascript const { ThermalPrinter, PrinterTypes } = require('node-thermal-printer'); const printer = new ThermalPrinter({ type: PrinterTypes.EPSON, interface: 'tcp://192.168.1.100:9100' }); printer.println('First receipt'); printer.partialCut(); // Partial cut - leaves small bridge printer.println('Second receipt'); printer.cut(); // Full cut // Custom vertical tab amount before cut printer.println('Third receipt'); printer.cut({ verticalTabAmount: 4 }); // More space before cut (default: 2) await printer.execute(); ``` -------------------------------- ### Advanced Printer Features Source: https://github.com/klemen1337/node-thermal-printer/blob/master/README.md Details on using advanced features like cash drawer, cutting, beeping, and printing barcodes/QR codes. ```APIDOC ## Advanced Printer Features ### Description Utilize advanced functionalities such as cash drawer operation, paper cutting, audible beeps, and printing machine-readable codes. ### Methods - **openCashDrawer()**: Kicks the cash drawer. - **cut()**: Performs a full paper cut. - **partialCut()**: Performs a partial paper cut (leaves a bridge). - **beep()**: Sounds the printer's internal beeper. - **upsideDown(enable)**: Toggles upside-down printing. `enable` (boolean). - **setCharacterSet(characterSet)**: Sets the printer's character set. `characterSet` (CharacterSet). - **setPrinterDriver(driver)**: Sets a custom printer driver. `driver` (Object). - **code128(data)**: Prints a Code128 barcode. `data` (string). - **printQR(data)**: Prints a QR code. `data` (string). - **printImage(filePath)**: Prints a PNG image from the specified file path. `filePath` (string). ### Request Example ```javascript printer.openCashDrawer(); printer.cut(); printer.beep(); printer.code128("1234567890"); printer.printQR("https://example.com"); await printer.printImage('./path/to/your/image.png'); ``` ``` -------------------------------- ### Buffer Management - getBuffer, setBuffer, clear Source: https://context7.com/klemen1337/node-thermal-printer/llms.txt Provides methods to access, manipulate, and clear the internal print buffer for advanced operations. ```APIDOC ## Buffer Management Methods ### Description These methods allow for advanced management of the internal print buffer, including retrieving its contents, setting it with external data, and clearing it. ### Methods - **getBuffer()**: Returns the current print buffer as a Buffer object. - **setBuffer(buffer)**: Sets the printer's internal buffer to the provided Buffer object. This can be used to clone print jobs or send pre-formatted data. - **clear()**: Clears the printer's internal buffer. ### Endpoint N/A (These are library functions, not network endpoints). ### Parameters - **getBuffer()**: None - **setBuffer(buffer)**: - **buffer** (Buffer) - Required - The buffer to set as the printer's internal buffer. - **clear()**: None ### Request Example ```javascript const { ThermalPrinter, PrinterTypes } = require('node-thermal-printer'); const printer1 = new ThermalPrinter({ type: PrinterTypes.EPSON, interface: 'tcp://192.168.1.100:9100' }); const printer2 = new ThermalPrinter({ type: PrinterTypes.EPSON, interface: 'tcp://192.168.1.101:9100' }); // Build print content on printer1 printer1.println('Order #12345'); printer1.println('Table 5'); printer1.cut(); // Get buffer from printer1 const buffer = printer1.getBuffer(); await printer1.execute(); // Send same content to printer2 using raw() with the buffer await printer2.raw(buffer); // Alternatively, use setBuffer for full control on printer2 printer2.clear(); // Clear existing buffer on printer2 printer2.setBuffer(buffer); // Set buffer to the content from printer1 await printer2.execute(); // Get text representation of the buffer (for debugging) console.log(printer1.getText()); // Get configured paper width console.log(printer1.getWidth()); // Returns: 48 ``` ### Response N/A (These functions manage internal state or return buffer data, not typical API responses). #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### Set Custom Text Size Source: https://github.com/klemen1337/node-thermal-printer/blob/master/README.md Sets the text height and width to specific values, ranging from 0 to 7. Values outside this range may not be supported or may default. ```javascript printer.setTextSize(7,7); ``` -------------------------------- ### Send Raw Buffer/Bytes Source: https://context7.com/klemen1337/node-thermal-printer/llms.txt Send raw bytes directly to the printer. This is useful for sending custom commands or pre-formatted data that bypasses the library's print buffer. Ensure the buffer contains valid ESC/POS commands or data. ```javascript const { ThermalPrinter, PrinterTypes } = require('node-thermal-printer'); async function sendRawCommand() { const printer = new ThermalPrinter({ type: PrinterTypes.EPSON, interface: 'tcp://192.168.1.100:9100' }); // Send raw ESC/POS commands directly const initCommand = Buffer.from([0x1B, 0x40]); // ESC @ - Initialize printer await printer.raw(initCommand); // Send raw text await printer.raw(Buffer.from('Hello World\n')); // Cut command await printer.raw(Buffer.from([0x1D, 0x56, 0x00])); // GS V 0 - Full cut } ``` -------------------------------- ### Text Formatting and Printing Source: https://github.com/klemen1337/node-thermal-printer/blob/master/README.md Covers various methods for appending text, controlling text styles, alignment, and line spacing. ```APIDOC ## Text Formatting and Printing ### Description Methods for appending text, applying styles like bold, underline, and controlling text size and alignment. ### Methods - **print(text)**: Appends text to the buffer. - **println(text)**: Appends text with a new line to the buffer. - **bold(enable)**: Sets text to bold. `enable` (boolean). - **invert(enable)**: Inverts background/text color. `enable` (boolean). - **underline(enable)**: Underlines text. `enable` (boolean). - **underlineThick(enable)**: Underlines text with a thick line. `enable` (boolean). - **drawLine()**: Draws a horizontal line. - **newLine()**: Inserts a new line. - **alignCenter()**: Aligns text to the center. - **alignLeft()**: Aligns text to the left. - **alignRight()**: Aligns text to the right. - **setTypeFontA()**: Sets font type to A (default). - **setTypeFontB()**: Sets font type to B. - **setTextNormal()**: Sets text to normal size. - **setTextDoubleHeight()**: Sets text to double height. - **setTextDoubleWidth()**: Sets text to double width. - **setTextQuadArea()**: Sets text to quad area (double height and width). - **setTextSize(height, width)**: Sets text height (0-7) and width (0-7). - **setLineSpacing(spacing)**: Sets the line spacing. `spacing` (number). - **resetLineSpacing()**: Resets line spacing to default. - **leftRight(leftText, rightText)**: Prints text aligned to the left and right edges of the line. - **table(columns)**: Prints text in a table format, equally distributing columns. `columns` (array of strings). - **tableCustom(customColumns)**: Prints text in a table with custom settings. `customColumns` (array of objects with `text`, `align`, `width`, `cols`, `bold` properties). ### Request Example ```javascript printer.bold(true); printer.println("Bold Text"); printer.alignCenter(); printer.println("Centered Text"); printer.leftRight("Left Aligned", "Right Aligned"); printer.table(["Item 1", "Item 2", "Item 3"]); ``` ``` -------------------------------- ### Text Formatting: Invert Colors Source: https://github.com/klemen1337/node-thermal-printer/blob/master/README.md Enables or disables background/text color inversion. This can be used for highlighting specific text. ```javascript printer.invert(true); ``` -------------------------------- ### Print Text with Automatic Line Wrapping Source: https://context7.com/klemen1337/node-thermal-printer/llms.txt Appends text to the print buffer. Line wrapping is automatic based on configured width and break mode. Ensure necessary imports are included. ```javascript const { ThermalPrinter, PrinterTypes, BreakLine } = require('node-thermal-printer'); const printer = new ThermalPrinter({ type: PrinterTypes.EPSON, interface: 'tcp://192.168.1.100:9100', width: 48, breakLine: BreakLine.WORD // Break at word boundaries }); printer.print('No newline after this'); printer.println('This line ends with newline'); printer.println('This is a very long line that will automatically wrap to multiple lines based on the printer width setting'); printer.println('Special characters: ČčŠšŽžÄäÖöÜü'); printer.cut(); await printer.execute(); ``` -------------------------------- ### Set Printer Driver Source: https://github.com/klemen1337/node-thermal-printer/blob/master/README.md Allows setting a custom printer driver object. This is typically used for advanced customization or unsupported printer models. ```javascript printer.setPrinterDriver(Object); ```