cordova-plugin-xprinter
v1.1.32
Published
Cordova Plugin for Printer Library
Downloads
91
Maintainers
Readme
Enhanced POS Printer Plugin
A powerful Cordova plugin for ESC/POS thermal printers with automatic connection management and modern Promise-based API.
🚀 Features
- Auto-Initialization: No manual setup required
- Auto-Connection Management: Handles connections automatically
- Connection Pooling: Maintains and reuses connections efficiently
- Promise-Based API: Modern async/await syntax
- Multi-Printer Support: Connect to multiple printers simultaneously
- Cross-Platform: Android and iOS support
- Rich Printing Options: Text, images, barcodes, QR codes, receipts
- Batch Operations: Print multiple items in sequence
📱 Platform Support
| Platform | USB | Bluetooth | Network/WiFi | Serial | | -------- | --- | --------- | ------------ | ------ | | Android | ✅ | ✅ | ✅ | ✅ | | iOS | 🚧 | 🚧 | ✅ | ❌ |
🚧 = Planned/In Development
📦 Installation
cordova plugin add cordova-plugin-xprinter🎯 Quick Start
// 1. Create printer info
const printer = { type: 'network', id: '192.168.1.100' };
// 2. Print anything instantly (auto-connects)
await cordova.plugins.printer.printText(printer, 'Hello World!\n');
await cordova.plugins.printer.printQRCode(printer, 'https://example.com');
await cordova.plugins.printer.cutPaper(printer);📖 API Reference
Printer Info Objects
Create printer connection info using helper methods:
// Network Printer
const networkPrinter = { type: 'network', id: '192.168.1.100' };
// USB Printer (Android only)
const usbPrinter = { type: 'usb', id: '0416:5011' }; // VID:PID format
// or
const usbPrinter = { type: 'usb', id: '/dev/usb/lp0' }; // Path format
// Bluetooth Printer (Android only)
const btPrinter = { type: 'bluetooth', id: '12:34:56:78:9A:BC' };Core Printing Methods
All methods return Promises and handle connections automatically.
Print Text
await cordova.plugins.printer.printText(printerInfo, 'Hello World!\n');Print Base64 Image
await cordova.plugins.printer.printBase64Image(
printerInfo,
base64ImageString,
1, //center=1, alignment
384 // width in pixels
);Print Barcode
const C = cordova.plugins.printer.Constants;
await cordova.plugins.printer.printBarcode(printerInfo, '1234567890123', C.BCS_EAN13);Print QR Code
await cordova.plugins.printer.printQRCode(printerInfo, 'https://example.com');Paper Control
// Feed paper lines
await cordova.plugins.printer.feedLine(printerInfo, 3);
// Cut paper
await cordova.plugins.printer.cutPaper(printerInfo);
// Open cash drawer
await cordova.plugins.printer.openCashBox(printerInfo);Batch Operations
Print multiple items in sequence:
await cordova.plugins.printer.printBatch(printerInfo, [
{ type: 'text', data: 'Receipt Header\n' },
{ type: 'text', data: '------------------------\n' },
{ type: 'qrcode', data: 'receipt-data-here' },
{ type: 'feed', lines: 3 },
{ type: 'cut' },
]);Device Discovery
// Get USB devices (Android only)
const usbDevices = await cordova.plugins.printer.getUsbDevices();
console.log(usbDevices);
/* Output:
[
{
id: "0416:5011",
devicePath: "/dev/bus/usb/001/002",
vendorId: 1046,
productId: 20497,
name: "Thermal Printer",
manufacturer: "Epson" | undefined | null,
type: "usb"
}
]
*/
// Get Bluetooth devices (Android only)
const btDevices = await cordova.plugins.printer.getBluetoothDevices();
console.log(btDevices);
/* Output:
[
{
id: "12:34:56:78:9A:BC",
name: "Thermal Printer",
address: "12:34:56:78:9A:BC",
deviceType: 2,
type: "bluetooth"
}
]
*/🔧 Error Handling
try {
await cordova.plugins.printer.printText(printerInfo, 'Test');
console.log('Print successful!');
} catch (error) {
console.error('Print failed:', error);
// Common error scenarios:
// - "USB permission denied by user"
// - "Failed to connect to network printer"
// - "Bluetooth connection not implemented"
// - "Unsupported printer type: xyz"
}🔍 Device Discovery Examples
Finding and Connecting to USB Printers
// Get available USB devices
const devices = await cordova.plugins.printer.getUsbDevices();
// Display to user for selection
devices.forEach((device, index) => {
console.log(`${index}: ${device.productName} (${device.id})`);
});
// Connect using device ID (VID:PID format)
const selectedDevice = devices[0];
const printer = cordova.plugins.printer.createUSBPrinterInfo(selecteddevice.id);
// Test connection
await cordova.plugins.printer.printText(printer, 'Connection test\n');Auto-Discovery Network Printers
// Try common printer IP addresses
const commonIPs = ['192.168.1.100', '192.168.1.200', '192.168.0.100'];
for (const ip of commonIPs) {
try {
const printer = cordova.plugins.printer.createNetworkPrinterInfo(ip);
await cordova.plugins.printer.printText(printer, 'Test\n');
console.log(`Found printer at: ${ip}`);
break;
} catch (error) {
console.log(`No printer at: ${ip}`);
}
}🐛 Troubleshooting
Common Issues
USB Permission Denied (Android)
// The plugin automatically requests USB permissions // If denied by user, you'll get this error try { await cordova.plugins.printer.printText(usbPrinter, 'test'); } catch (error) { if (error.includes('permission denied')) { alert('Please grant USB permission and try again'); } }Network Connection Timeout
// Ensure printer IP is correct and printer is on same network const printer = { type: 'network', id: '192.168.1.100' }; // Test with a simple ping first try { await cordova.plugins.printer.printText(printer, 'Network test\n'); } catch (error) { console.log('Check network connection and printer IP'); }iOS USB Not Supported
// USB is not supported on iOS due to platform limitations // Use network printers instead if (cordova.platformId === 'ios') { // Only use network printers on iOS const printer = cordova.plugins.printer.createNetworkPrinterInfo(ipAddress); }
Debug Mode
Enable detailed logging by checking connection status:
// Check what connections are active
const status = await cordova.plugins.printer.getConnectionStatus();
console.log('Active connections:', status);
// Test each connection
for (const connection of status.connections) {
const [type, id] = connection.split(':');
const printer = { type, id };
try {
await cordova.plugins.printer.printText(printer, 'Debug test\n');
console.log(`${connection}: OK`);
} catch (error) {
console.log(`${connection}: Failed - ${error}`);
}
}🏗️ Architecture
The plugin uses a modern architecture with:
- Auto-Initialization: Plugin initializes automatically on load
- Connection Pooling: Maintains active connections in memory
- Promise-Based: All methods return Promises for easy async/await usage
- Error Propagation: Detailed error messages for debugging
- Platform Abstraction: Same API works across Android and iOS
📄 License
MIT License - see LICENSE file for details.
🤝 Contributing
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
📞 Support
For issues and questions:
- Create an issue on GitHub
- Check the troubleshooting section above
- Review the complete examples
🔄 Changelog
v2.0.0
- Complete rewrite with auto-connection management
- Promise-based API
- Connection pooling
- Batch operations
- Enhanced receipt printing
- Removed legacy callback methods
v1.x.x
- Legacy callback-based API (deprecated)
