@georgemichel/react-native-xprinter-manager
v1.0.0
Published
Complete XPrinter thermal printer management library with TCP/IP support, receipt printing, and auto-connect
Maintainers
Readme
React Native XPrinter Manager
A 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.
Features
- 📦 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
Installation
Install from Private NPM
One command - everything included!
npm install @yourcompany/react-native-xprinter-managerThat's it! All dependencies (react-native-tcp-socket, @react-native-async-storage/async-storage) are included automatically.
For Expo Projects
After installing, rebuild your native code:
npx expo prebuild
npm run android # or npm run iosSetup Authentication
Create .npmrc in your project root:
@yourcompany:registry=https://npm.pkg.github.com/
//npm.pkg.github.com/:_authToken=YOUR-GITHUB-TOKENSee SETUP.md for complete publishing and installation instructions.
Quick Start
1. Basic Connection
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 (
<View>
{isConnected ? (
<>
<Text>Connected to: {connectedPrinter.deviceName}</Text>
<Button title="Disconnect" onPress={disconnect} />
</>
) : (
<Button title="Connect" onPress={handleConnect} />
)}
</View>
);
}2. Print a Receipt
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 (
<Button title="Print Receipt" onPress={handlePrint} />
);
}3. Save and Auto-Connect
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 (
<View>
{isAutoConnecting && <Text>Auto-connecting...</Text>}
{savedPrinters.map(printer => (
<Text key={printer.id}>{printer.deviceName}</Text>
))}
<Button title="Add Printer" onPress={handleAddPrinter} />
</View>
);
}API Reference
Hooks
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
Utilities
printReceipt(socket, receiptData)
Prints a formatted receipt.
Parameters:
socket- Active TCP socketreceiptData- Receipt data object (see example above)
Returns: Promise<boolean>
Commands
ESC/POS command constants:
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_PAPERHelper Functions
separator(char, length)- Create separator lineformatLine(left, right, totalWidth)- Format left/right aligned textcenterText(text, width)- Center textformatCurrency(amount, currency)- Format currency
Receipt Template
The library includes a customizable receipt template. Here's how to modify it:
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
};Configuration for Private NPM
To publish as a private npm package:
- Update package.json:
{
"name": "@yourcompany/react-native-xprinter-manager",
"private": false,
"publishConfig": {
"registry": "https://npm.pkg.github.com/"
}
}- Publish:
cd lib
npm publish- Install in projects:
npm install @yourcompany/react-native-xprinter-managerTroubleshooting
Connection Issues
- Check IP and Port: Verify printer IP address and port (usually 9100)
- Network Connection: Ensure device is on same network as printer
- Firewall: Check if firewall is blocking TCP connections
- Printer Status: Ensure printer is powered on and online
Print Issues
- Paper Loaded: Verify paper is loaded correctly
- ESC/POS Support: Ensure printer supports ESC/POS commands
- Encoding: Try different text encodings if characters appear wrong
- Commands: Some printers may not support all ESC/POS commands
License
MIT
Support
For issues and questions, please open an issue on GitHub or contact support.
