Complete XPrinter thermal printer management library with TCP/IP support, receipt printing, and auto-connect
npm install @georgemichel/react-native-xprinter-managerA complete, standalone React Native library for managing XPrinter thermal printers over TCP/IP connection. Provides React hooks for connection management, printer storage, auto-connect functionality, and receipt printing.
- ๐ฆ All Dependencies Included - No manual linking required
- ๐ Easy Connection Management - Connect/disconnect with simple hooks
- ๐พ Persistent Storage - Save printer configurations locally
- ๐ Auto-Connect - Automatically connect to saved printers on app start
- ๐งพ Receipt Printing - Pre-built receipt template with customization
- ๐ ESC/POS Commands - Full suite of thermal printer commands
- โก React Hooks - Modern React hooks API
- ๐ฏ TypeScript Ready - (Types can be added)
- ๐ Production Ready - Battle-tested and documented
One command - everything included!
``bash`
npm install @yourcompany/react-native-xprinter-manager
That's it! All dependencies (react-native-tcp-socket, @react-native-async-storage/async-storage) are included automatically.
After installing, rebuild your native code:
`bash`
npx expo prebuild
npm run android # or npm run ios
Create .npmrc in your project root:
``
@yourcompany:registry=https://npm.pkg.github.com/
//npm.pkg.github.com/:_authToken=YOUR-GITHUB-TOKEN
See SETUP.md for complete publishing and installation instructions.
`javascript
import React from 'react';
import { View, Button, Text } from 'react-native';
import { usePrinterConnection } from '@yourcompany/react-native-xprinter-manager';
function App() {
const {
isConnected,
connectedPrinter,
connect,
disconnect,
sendData
} = usePrinterConnection();
const handleConnect = async () => {
try {
await connect('192.168.100.99', 9100, 'Main Printer');
alert('Connected!');
} catch (error) {
alert('Connection failed: ' + error.message);
}
};
return (
{isConnected ? (
<>
>
) : (
)}
);
}
`
`javascript
import { usePrinterConnection, printReceipt } from '@yourcompany/react-native-xprinter-manager';
function ReceiptScreen() {
const { socket, isConnected } = usePrinterConnection();
const handlePrint = async () => {
if (!isConnected) {
alert('Not connected to printer');
return;
}
const receiptData = {
storeName: "My Store",
storeAddress: "123 Main St, City, State",
storePhone: "(555) 123-4567",
receiptNumber: "INV-001",
items: [
{ name: "Coffee", qty: 2, price: 3.50 },
{ name: "Sandwich", qty: 1, price: 7.99 },
],
subtotal: 14.99,
tax: 1.20,
total: 16.19,
paymentMethod: "Cash",
footerText: "Thank you!"
};
try {
await printReceipt(socket, receiptData);
alert('Receipt printed!');
} catch (error) {
alert('Print failed: ' + error.message);
}
};
return (
);
}
`
`javascript
import {
usePrinterConnection,
usePrinterStorage,
useAutoConnect
} from '@yourcompany/react-native-xprinter-manager';
function PrinterManager() {
const { connect, isConnected } = usePrinterConnection();
const { addPrinter, savedPrinters } = usePrinterStorage();
const { isAutoConnecting } = useAutoConnect({ enabled: true });
const handleAddPrinter = async () => {
const printer = await addPrinter({
ip: '192.168.100.99',
port: 9100,
deviceName: 'Main Counter Printer',
autoConnect: true // Will auto-connect on app start
});
// Manually connect now
await connect(printer.ip, printer.port, printer.deviceName);
};
return (
{isAutoConnecting &&
{savedPrinters.map(printer => (
))}
);
}
`
#### usePrinterConnection()
Manages TCP socket connection to printer.
Returns:
- socket - Active socket objectisConnected
- - Connection statusisConnecting
- - Connecting in progressconnectedPrinter
- - Current printer infoerror
- - Last error messagereceivedData
- - Data received from printerconnect(ip, port, deviceName, options)
- - Connect to printerdisconnect()
- - Disconnect from printersendData(data, encoding)
- - Send data to printercheckPrinterAvailable(ip, port, timeout)
- - Check if printer is onlineclearReceivedData()
- - Clear received data buffer
#### usePrinterStorage()
Manages saved printer configurations.
Returns:
- savedPrinters - Array of saved printersisLoading
- - Loading statusaddPrinter(printer)
- - Add new printerremovePrinter(printerId)
- - Remove printerupdatePrinter(printerId, updates)
- - Update printergetPrinter(printerId)
- - Get printer by IDgetPrinterByAddress(ip, port)
- - Get printer by addresssetAutoConnect(printerId, enabled)
- - Set auto-connectgetAutoConnectPrinters()
- - Get printers with auto-connectupdateLastConnected(printerId)
- - Update last connected timeclearAllPrinters()
- - Remove all printersreload()
- - Reload from storage
#### useAutoConnect(options)
Automatically connects to saved printers on app start.
Options:
- enabled - Enable auto-connect (default: true)retryDelay
- - Delay between retries in ms (default: 3000)maxRetries
- - Max retry attempts (default: 3)
Returns:
- isAutoConnecting - Auto-connect in progressautoConnectStatus
- - Array of connection attemptstriggerAutoConnect()
- - Manually trigger auto-connectresetAutoConnect()
- - Reset auto-connect state
#### printReceipt(socket, receiptData)
Prints a formatted receipt.
Parameters:
- socket - Active TCP socketreceiptData
- - Receipt data object (see example above)
Returns: Promise
#### Commands
ESC/POS command constants:
`javascript
import { Commands } from '@yourcompany/react-native-xprinter-manager';
// Initialization
Commands.INIT
// Alignment
Commands.ALIGN_LEFT
Commands.ALIGN_CENTER
Commands.ALIGN_RIGHT
// Text Size
Commands.TEXT_SIZE_NORMAL
Commands.TEXT_SIZE_DOUBLE
Commands.TEXT_SIZE_LARGE
// Text Style
Commands.TEXT_BOLD_ON
Commands.TEXT_BOLD_OFF
// Paper Control
Commands.LINE_FEED
Commands.CUT_PAPER
`
#### Helper Functions
- separator(char, length) - Create separator lineformatLine(left, right, totalWidth)
- - Format left/right aligned textcenterText(text, width)
- - Center textformatCurrency(amount, currency)
- - Format currency
The library includes a customizable receipt template. Here's how to modify it:
`javascript
const receiptData = {
// === HEADER ===
storeName: "Your Store Name", // Store name (centered, large)
storeAddress: "123 Main St", // Store address
storePhone: "(555) 123-4567", // Store phone
// === RECEIPT INFO ===
receiptNumber: "INV-001234", // Invoice/order number
// === ITEMS ===
items: [
{
name: "Product Name", // Item name
qty: 2, // Quantity
price: 10.00 // Price per unit
},
// ... more items
],
// === TOTALS ===
subtotal: 45.00, // Subtotal
tax: 3.60, // Tax amount
total: 48.60, // Total amount
// === PAYMENT ===
paymentMethod: "Cash", // Payment method
// === FOOTER ===
footerText: "Thank you!\nVisit again!" // Footer message
};
`
To publish as a private npm package:
1. Update package.json:
`json`
{
"name": "@yourcompany/react-native-xprinter-manager",
"private": false,
"publishConfig": {
"registry": "https://npm.pkg.github.com/"
}
}
2. Publish:
`bash`
cd lib
npm publish
3. Install in projects:
`bash``
npm install @yourcompany/react-native-xprinter-manager
1. Check IP and Port: Verify printer IP address and port (usually 9100)
2. Network Connection: Ensure device is on same network as printer
3. Firewall: Check if firewall is blocking TCP connections
4. Printer Status: Ensure printer is powered on and online
1. Paper Loaded: Verify paper is loaded correctly
2. ESC/POS Support: Ensure printer supports ESC/POS commands
3. Encoding: Try different text encodings if characters appear wrong
4. Commands: Some printers may not support all ESC/POS commands
MIT
For issues and questions, please open an issue on GitHub or contact support.