react-native-rongta-wifi-printer-ios
v1.1.0
Published
Reset printer buffer (error when printing image) before printing
Maintainers
Readme
react-native-rongta-wifi-printer-ios
React Native bridge for Rongta Thermal Printer SDK (iOS)
Features
- ✅ WiFi connection (192.168.x.x:9100)
- ✅ Bluetooth connection
- ✅ Print text with formatting (bold, underline, align, font size)
- ✅ Print images (base64)
- ✅ Print QR codes
- ✅ Print barcodes
- ✅ Auto-reconnect when connection lost
- ✅ Network printer discovery
- ✅ Paper feed & cut
- ✅ TypeScript support
- 🍎 iOS support (WiFi/Bluetooth)
- 🤖 Android support (coming soon)
Installation
npm install react-native-rongta-wifi-printer-ios
# or
yarn add react-native-rongta-wifi-printer-iosiOS
cd ios && pod installAdd Bluetooth permissions to your Info.plist:
<key>NSBluetoothAlwaysUsageDescription</key>
<string>This app needs Bluetooth access to connect to thermal printers</string>
<key>NSBluetoothPeripheralUsageDescription</key>
<string>This app needs Bluetooth access to connect to thermal printers</string>Usage
Setup (Important!)
Configure storage for auto-reconnect functionality. Call this once at app startup:
// App.tsx or index.js
import { RTPrinterSDK } from 'react-native-rongta-wifi-printer-ios';
import AsyncStorage from '@react-native-async-storage/async-storage';
// Configure storage on app startup
RTPrinterSDK.configureStorage(
{
getItem: (key: string) => AsyncStorage.getItem(key),
setItem: (key: string, value: string) => AsyncStorage.setItem(key, value),
removeItem: (key: string) => AsyncStorage.removeItem(key),
},
'@printer_ip_address', // Storage key (optional, default: '@printer_ip_address')
9100 // Default port (optional, default: 9100)
);Why? This enables automatic reconnection when the printer disconnects (e.g., idle timeout). The library will save the printer IP and auto-reconnect before each print operation.
Note: Install @react-native-async-storage/async-storage as a peer dependency:
npm install @react-native-async-storage/async-storage
# or
yarn add @react-native-async-storage/async-storageQuick Start
import RTPrinter, { PrinterType, TextAlign } from 'react-native-rongta-wifi-printer-ios';
// Set printer type
await RTPrinter.setPrinterType(PrinterType.ESC);
// Connect to WiFi printer
await RTPrinter.connectWifi('192.168.1.100', 9100);
// Print text
await RTPrinter.printText('Hello World!', {
align: TextAlign.CENTER,
fontSize: 24,
bold: true,
lineFeed: 2
});
// Feed paper and cut
await RTPrinter.feedPaper(3);
await RTPrinter.cutPaper();Connection
WiFi Connection
import RTPrinter, { PrinterType } from 'react-native-rongta-wifi-printer-ios';
// Set printer type (ESC/POS for thermal printers)
await RTPrinter.setPrinterType(PrinterType.ESC);
// Connect to printer
const result = await RTPrinter.connectWifi('192.168.1.100', 9100);
if (result.success) {
console.log('Connected!');
}
// Check connection status
const { connected } = await RTPrinter.isConnected();Bluetooth Connection
await RTPrinter.connectBluetooth('BLUETOOTH_ADDRESS');Discover Printers
const result = await RTPrinter.discoverPrinters();
console.log('Found printers:', result.printers);
if (result.printers.length > 0) {
const printer = result.printers[0];
await RTPrinter.connectWifi(printer.ip, printer.port);
}Printing
Print Text
import { TextAlign } from 'react-native-rongta-wifi-printer-ios';
await RTPrinter.printText('FOZITO PLUS', {
align: TextAlign.CENTER,
fontSize: 32,
bold: true,
lineFeed: 2
});
await RTPrinter.printText('Item 1 $10.00', {
align: TextAlign.LEFT,
lineFeed: 1
});Print Image
// From base64 string
const base64Image = '...'; // Your base64 image
await RTPrinter.printImage(base64Image, 550, 0);
// Feed paper after printing
await RTPrinter.feedPaper(10);Print QR Code
await RTPrinter.printQRCode('https://example.com', 200);Print Barcode
import { BarcodeType } from 'react-native-rongta-wifi-printer-ios';
await RTPrinter.printBarcode('12345678', BarcodeType.CODE128, 2, 50);Print Receipt Example
// Header
await RTPrinter.printText('FOZITO PLUS', {
align: TextAlign.CENTER,
fontSize: 32,
bold: true,
lineFeed: 1
});
await RTPrinter.printText('123 Main St, City', {
align: TextAlign.CENTER,
fontSize: 18,
lineFeed: 2
});
// Items
await RTPrinter.printText('Haircut $25.00', {
align: TextAlign.LEFT,
lineFeed: 1
});
await RTPrinter.printText('Hair Coloring $15.00', {
align: TextAlign.LEFT,
lineFeed: 2
});
// Total
await RTPrinter.printText('TOTAL: $40.00', {
align: TextAlign.RIGHT,
fontSize: 24,
bold: true,
lineFeed: 3
});
// QR Code
await RTPrinter.printQRCode('ticket-12345', 200);
// Feed and cut
await RTPrinter.feedPaper(10);
await RTPrinter.cutPaper();API Reference
Connection Methods
RTPrinter.setPrinterType(type: PrinterType): Promise<{success: boolean}>
RTPrinter.connectWifi(ip: string, port: number): Promise<{success: boolean}>
RTPrinter.connectBluetooth(address: string): Promise<{success: boolean}>
RTPrinter.disconnect(): Promise<{success: boolean}>
RTPrinter.isConnected(): Promise<{connected: boolean}>
RTPrinter.discoverPrinters(): Promise<{printers: PrinterInfo[]}>Printing Methods
RTPrinter.printText(text: string, options?: PrintTextOptions): Promise<{success: boolean}>
RTPrinter.printImage(base64: string, width: number, height: number): Promise<{success: boolean}>
RTPrinter.printQRCode(content: string, size?: number): Promise<{success: boolean}>
RTPrinter.printBarcode(content: string, type: BarcodeType, width: number, height: number): Promise<{success: boolean}>
RTPrinter.feedPaper(lines?: number): Promise<{success: boolean}>
RTPrinter.cutPaper(): Promise<{success: boolean}>Types
enum PrinterType {
ESC = 'ESC', // Thermal printers (recommended)
TSC = 'TSC', // Label printers
CPCL = 'CPCL', // Label printers
ZPL = 'ZPL' // Label printers
}
enum TextAlign {
LEFT = 'left',
CENTER = 'center',
RIGHT = 'right'
}
enum BarcodeType {
UPC_A = 'UPC_A',
UPC_E = 'UPC_E',
EAN13 = 'EAN13',
EAN8 = 'EAN8',
CODE39 = 'CODE39',
CODE128 = 'CODE128',
ITF = 'ITF',
CODABAR = 'CODABAR'
}
interface PrintTextOptions {
align?: TextAlign;
fontSize?: number;
bold?: boolean;
underline?: boolean;
lineFeed?: number;
}
interface PrinterInfo {
ip: string;
port: number;
name: string;
}Auto-Reconnect Feature
The SDK includes automatic reconnection when the printer disconnects (e.g., after idle timeout).
How It Works
Configure storage (once at app startup):
import { RTPrinterSDK } from 'react-native-rongta-wifi-printer-ios'; import AsyncStorage from '@react-native-async-storage/async-storage'; RTPrinterSDK.configureStorage( AsyncStorage, '@printer_ip_address', 9100 );Connect to printer (IP is automatically saved):
await RTPrinter.connectWifi('192.168.1.100', 9100); // IP saved to AsyncStorage automaticallyPrint after disconnect (auto-reconnects silently):
// Even if printer disconnected, this will work: await RTPrinter.printText('Hello!'); // SDK checks connection → finds saved IP → reconnects → prints ✓
Storage Interface
You can use any storage implementation:
interface StorageInterface {
getItem: (key: string) => Promise<string | null>;
setItem: (key: string, value: string) => Promise<void>;
removeItem: (key: string) => Promise<void>;
}
// Example with custom storage:
RTPrinterSDK.configureStorage(
{
getItem: async (key) => myStorage.get(key),
setItem: async (key, value) => myStorage.set(key, value),
removeItem: async (key) => myStorage.delete(key),
},
'@custom_printer_key',
9100
);Constants
import {
PRINTER_IP_KEY, // '@printer_ip_address'
DEFAULT_PRINTER_PORT, // 9100
DEFAULT_PRINTER_IP // '192.168.1.100'
} from 'react-native-rongta-wifi-printer-ios';Troubleshooting
"Printer not connecting"
- Ensure printer and device are on same WiFi network
- Check printer IP address (usually printed on test page)
- Verify port 9100 is accessible
- Try pinging the printer:
ping 192.168.1.100 - Test port:
nc -zv 192.168.1.100 9100
"Connection lost after idle"
The SDK includes auto-reconnect. If issues persist:
- Increase printer timeout settings
- Check WiFi router settings
- Ensure printer power saving is disabled
"Discovery not finding printers"
- Manual IP connection is more reliable
- Some networks block broadcast/UDP
- Try manual connection instead
Complete Example
Here's a full example showing setup, connection, and printing:
// App.tsx - Configure storage on startup
import React, { useEffect } from 'react';
import { RTPrinterSDK } from 'react-native-rongta-wifi-printer-ios';
import AsyncStorage from '@react-native-async-storage/async-storage';
export default function App() {
useEffect(() => {
// Configure storage for auto-reconnect
RTPrinterSDK.configureStorage(
{
getItem: (key: string) => AsyncStorage.getItem(key),
setItem: (key: string, value: string) => AsyncStorage.setItem(key, value),
removeItem: (key: string) => AsyncStorage.removeItem(key),
},
'@printer_ip_address',
9100
);
}, []);
return <YourApp />;
}// PrinterService.ts - Printer connection & printing
import RTPrinter, {
PrinterType,
TextAlign,
PRINTER_IP_KEY,
} from 'react-native-rongta-wifi-printer-ios';
import AsyncStorage from '@react-native-async-storage/async-storage';
export class PrinterService {
// Connect to printer
static async connect(ip: string = '192.168.1.100') {
try {
// Set printer type
await RTPrinter.setPrinterType(PrinterType.ESC);
// Connect
const result = await RTPrinter.connectWifi(ip, 9100);
if (result.success) {
// IP automatically saved for auto-reconnect
console.log('Connected to printer!');
return true;
}
return false;
} catch (error) {
console.error('Connection failed:', error);
return false;
}
}
// Auto-discover and connect
static async discoverAndConnect() {
try {
const { printers } = await RTPrinter.discoverPrinters();
if (printers.length > 0) {
const printer = printers[0];
await RTPrinter.setPrinterType(PrinterType.ESC);
await RTPrinter.connectWifi(printer.ip, printer.port);
console.log(`Connected to ${printer.name}`);
return true;
}
return false;
} catch (error) {
console.error('Discovery failed:', error);
return false;
}
}
// Print receipt
static async printReceipt(orderData: any) {
try {
// Auto-reconnects if needed (thanks to configureStorage)
await RTPrinter.printText('FOZITO PLUS', {
align: TextAlign.CENTER,
fontSize: 32,
bold: true,
lineFeed: 2,
});
await RTPrinter.printText('Receipt #12345', {
align: TextAlign.CENTER,
fontSize: 24,
lineFeed: 2,
});
// Items
for (const item of orderData.items) {
await RTPrinter.printText(
`${item.name.padEnd(20)} $${item.price.toFixed(2)}`,
{ align: TextAlign.LEFT, lineFeed: 1 }
);
}
await RTPrinter.printText('----------------------------', {
align: TextAlign.LEFT,
lineFeed: 1,
});
// Total
await RTPrinter.printText(
`TOTAL: $${orderData.total.toFixed(2)}`,
{
align: TextAlign.RIGHT,
fontSize: 24,
bold: true,
lineFeed: 2,
}
);
// QR Code
await RTPrinter.printQRCode(orderData.qrData, 200);
// Feed and cut
await RTPrinter.feedPaper(10);
await RTPrinter.cutPaper();
console.log('Print successful!');
return true;
} catch (error) {
console.error('Print failed:', error);
return false;
}
}
// Check connection status
static async isConnected() {
const { connected } = await RTPrinter.isConnected();
return connected;
}
// Disconnect
static async disconnect() {
await RTPrinter.disconnect();
// Note: IP is kept for auto-reconnect
// To remove IP: await AsyncStorage.removeItem(PRINTER_IP_KEY);
}
}// Usage in component
import { PrinterService } from './PrinterService';
// Connect on app start
useEffect(() => {
PrinterService.discoverAndConnect();
}, []);
// Print receipt
const handlePrint = async () => {
const orderData = {
items: [
{ name: 'Haircut', price: 25.00 },
{ name: 'Shampoo', price: 15.00 },
],
total: 40.00,
qrData: 'order-12345',
};
const success = await PrinterService.printReceipt(orderData);
if (success) {
Alert.alert('Success', 'Receipt printed!');
} else {
Alert.alert('Error', 'Print failed');
}
};Platform Support
- ✅ iOS: WiFi ✅, Bluetooth ✅
- 🤖 Android: Coming soon
Requirements
- React Native >= 0.60
- iOS >= 11.0
- Android >= 5.0 (coming soon)
Contributing
Pull requests are welcome! For major changes, please open an issue first.
License
MIT © Vinh Nguyen
Support
- 📧 Email: [email protected]
- 🐛 Issues: GitHub Issues
- 📖 Documentation: Full Guide
Credits
Built with ❤️ using Rongta Thermal Printer SDK
