npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

react-native-kozen-printer

v1.1.2

Published

React Native module for Kozen POS printer integration with enhanced features

Downloads

48

Readme

react-native-kozen-printer

React Native module for Kozen POS printer integration.

Installation

npm install react-native-kozen-printer
# or
yarn add react-native-kozen-printer

Requirements

  • Hardware: Kozen POS device with printer service installed
  • Android: Minimum SDK 21 (API level 21)
  • React Native: 0.72+
  • Node.js: 18+

Setup Instructions

Choose the setup instructions based on your project type:

🚫 Expo Go (NOT Supported)

This library requires custom native code and cannot be used with Expo Go. You must use one of the supported workflows below.


✅ Option 1: Bare React Native (Recommended for Native Modules)

If you're using a bare React Native project (created with react-native init or ejected from Expo):

Step 1: Install the Library

npm install react-native-kozen-printer

Step 2: Android Configuration

  1. Add the library to android/settings.gradle:
include ':react-native-kozen-printer'
project(':react-native-kozen-printer').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-kozen-printer/android')
  1. Add the dependency in android/app/build.gradle:
dependencies {
    // ... other dependencies
    implementation project(':react-native-kozen-printer')
}
  1. Register the package in MainApplication.java or MainApplication.kt:

For Java (MainApplication.java):

import com.kozen.printer.KozenPrinterPackage;
import java.util.Arrays;
import java.util.List;

public class MainApplication extends Application implements ReactApplication {
  // ... existing code ...

  @Override
  protected List<ReactPackage> getPackages() {
    return Arrays.<ReactPackage>asList(
        new MainReactPackage(),
        new KozenPrinterPackage() // Add this line
    );
  }
}

For Kotlin (MainApplication.kt):

import com.kozen.printer.KozenPrinterPackage

class MainApplication : Application(), ReactApplication {
  override fun getPackages(): List<ReactPackage> {
    val packages = PackageList(this).packages
    packages.add(KozenPrinterPackage()) // Add this line
    return packages
  }
}
  1. Add BLUETOOTH permission in android/app/src/main/AndroidManifest.xml:
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
    <uses-permission android:name="android.permission.BLUETOOTH" />
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
    <!-- ... rest of manifest ... -->
</manifest>

Step 3: Rebuild the App

cd android
./gradlew clean
cd ..
npm run android

✅ Option 2: Expo Development Build (Managed Workflow with Custom Native Code)

If you're using Expo with the managed workflow but need custom native code:

Step 1: Install Dependencies

# Install expo-dev-client (required for custom native modules)
npx expo install expo-dev-client

# Install the library
npm install react-native-kozen-printer

Step 2: Add Config Plugin

Add the config plugin to your app.json or app.config.js. The plugin automatically handles:

  • Copying AIDL files
  • Including JAR dependency
  • Configuring build.gradle
  • Adding BLUETOOTH permissions

app.json:

{
  "expo": {
    "plugins": [
      "react-native-kozen-printer"
    ],
    "android": {
      "permissions": ["BLUETOOTH", "BLUETOOTH_ADMIN"]
    }
  }
}

app.config.js (if using config file):

export default {
  expo: {
    plugins: [
      'react-native-kozen-printer'
    ],
    android: {
      permissions: ['BLUETOOTH', 'BLUETOOTH_ADMIN'],
    },
  },
};

Step 3: Generate Native Directories

Run expo prebuild to generate the android/ and ios/ directories with native code:

npx expo prebuild --clean

This command will:

  • Generate the android/ directory with native Android project files
  • Automatically copy AIDL files to android/app/src/main/aidl/
  • Automatically include JAR dependency in android/app/libs/
  • Automatically configure build.gradle with sourceSets, repositories, and dependencies
  • Automatically add BLUETOOTH permissions to AndroidManifest.xml
  • Automatically link the native module via React Native autolinking

Note: The config plugin handles all native configuration automatically. No manual steps required!

Step 4: Create Development Build

Option A: Build with EAS (Recommended for production):

# Install EAS CLI if not already installed
npm install -g eas-cli

# Login to Expo
eas login

# Configure EAS
eas build:configure

# Build development client
eas build --profile development --platform android

Option B: Build locally:

npx expo run:android

This will:

  • Build the native Android app with the custom native module
  • Install it on your connected device/emulator
  • Start the Metro bundler

Step 5: Start Development

# Start Expo development server
npx expo start --dev-client

Verification

After expo prebuild, you can verify the automatic configuration:

  1. AIDL files should be in android/app/src/main/aidl/com/xcheng/printerservice/
  2. JAR file should be in android/app/libs/core-3.3.0.jar
  3. build.gradle should include:
    • aidl.srcDirs = ['src/main/aidl'] in sourceSets
    • flatDir { dirs 'libs' } in repositories
    • implementation files('libs/core-3.3.0.jar') in dependencies
  4. AndroidManifest.xml should include BLUETOOTH permissions
  5. Native module should be automatically registered (check MainApplication.kt)

If any of these are missing, run npx expo prebuild --clean again.


✅ Option 3: Expo Bare Workflow

If you're using Expo's bare workflow (project initialized with expo init --template bare-minimum or ejected):

Step 1: Install the Library

npm install react-native-kozen-printer

Step 2: Configure Android

Follow the same steps as Option 1: Bare React Native above, since bare workflow projects have full access to native directories.

Step 3: Add Permissions

Add BLUETOOTH permissions to android/app/src/main/AndroidManifest.xml:

<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />

Step 4: Rebuild

cd android
./gradlew clean
cd ..
npm run android

Workflow Comparison

| Feature | Expo Go | Expo Dev Build | Expo Bare | Bare RN | |---------|---------|----------------|-----------|---------| | Custom Native Code | ❌ No | ✅ Yes | ✅ Yes | ✅ Yes | | Native Directories | ❌ No | ✅ Generated | ✅ Yes | ✅ Yes | | Setup Complexity | ❌ N/A | ✅ Automatic (Config Plugin) | ⚠️ Manual | ⚠️ Manual | | expo prebuild Required | ❌ N/A | ✅ Yes | ❌ No | ❌ No | | EAS Build | ❌ No | ✅ Recommended | ✅ Optional | ❌ No | | AIDL/JAR Auto-Config | ❌ N/A | ✅ Yes (Plugin) | ⚠️ Manual | ⚠️ Manual |

Key Differences:

  • Expo Go: Cannot use this library (no custom native code support)
  • Expo Dev Build: ✅ Easiest setup - Add plugin to app.json, run expo prebuild, everything is automatic!
  • Expo Bare: Has native directories, configure like bare React Native (manual setup)
  • Bare RN: Full native access, manual configuration required

Usage

import KozenPrinterLibrary from 'react-native-kozen-printer';

// Connect and initialize printer
await KozenPrinterLibrary.prepare();

// Print text
await KozenPrinterLibrary.printText('Hello World');

// Print QR code
await KozenPrinterLibrary.printQRCode('https://example.com', 8, 'middle');

// Print barcode
await KozenPrinterLibrary.printBarcode(
  '123456789',
  'CODE128',
  100,
  2,
  'textUnderBarcode'
);

// Print image
await KozenPrinterLibrary.printBitmapBase64(base64Image, 384);

// Set alignment
await KozenPrinterLibrary.setAlignment('center');

// Set font size
await KozenPrinterLibrary.setFontSize(32);

// Line wrap
await KozenPrinterLibrary.lineWrap(3);

// Cut paper
await KozenPrinterLibrary.cutPaper();

// Disconnect
await KozenPrinterLibrary.disconnect();

API Reference

Core Functions

  • prepare() - Connect and initialize printer
  • printerInit() - Initialize printer
  • printerReset() - Reset printer
  • disconnect() - Disconnect from printer
  • updatePrinterState() - Get printer state

Information Functions

  • getPrinterInfo() - Get printer information
  • getPrinterSerialNo() - Get serial number
  • getPrinterVersion() - Get firmware version
  • getServiceVersion() - Get service version
  • getPrinterModal() - Get printer model
  • getPrinterPaper() - Get paper width (58mm or 80mm)
  • getPrintedLength() - Get printed length

Text Printing

  • setAlignment(alignment) - Set text alignment ('left' | 'center' | 'right')
  • setFontSize(fontSize) - Set font size
  • setBold(isBold) - Set bold text
  • setUnderline(isUnderline) - Set underline
  • printText(text) - Print text
  • printTextWithFont(text, fontSize) - Print text with font size
  • printOriginalText(text) - Print original text
  • printColumnsText(texts, widths, alignments) - Print table row
  • printColumnsString(texts, widths, alignments) - Print table row with width/alignment

Barcode/QR Printing

  • printBarcode(text, format, height, width, textPosition) - Print 1D barcode
  • printQRCode(text, moduleSize, errorLevel) - Print QR code

Image Printing

  • printBitmapBase64(base64, pixelWidth) - Print image from base64
  • printBitmapBase64Custom(base64, pixelWidth, type) - Print image with custom type

Paper Control

  • lineWrap(count) - Line wrap
  • cutPaper() - Cut paper

Transaction Printing

  • enterPrinterBuffer(clear) - Enter transaction mode
  • exitPrinterBuffer(commit) - Exit transaction mode
  • commitPrinterBuffer() - Commit transaction

Kozen Enhanced Features

  • cashDrawerOpen() - Open cash drawer
  • lcdSendCommand(command) - Send LCD command
  • blackLabelDetect() - Detect black label
  • labelLocate() - Locate label
  • labelOutput() - Output label

Raw Commands

  • sendRAWData(base64) - Send raw ESC/POS commands

Constants

  • MaxPixelWidth - Maximum pixel width for paper sizes ({ '58mm': 384, '80mm': 576 })
  • defaultFontSize - Default font size (24)
  • EventType - Event type constants for event listeners

Advanced Usage

Error Handling

import KozenPrinterLibrary from 'react-native-kozen-printer';
import { KozenPrinterError } from 'react-native-kozen-printer';

try {
  await KozenPrinterLibrary.prepare();
  await KozenPrinterLibrary.printText('Hello');
} catch (error) {
  if (error instanceof KozenPrinterError) {
    console.error('Printer error:', error.code, error.message);
  } else {
    console.error('Unknown error:', error);
  }
}

Event Listeners

import { onPrinterConnected, onPrinterError, removeAllListeners } from 'react-native-kozen-printer';

// Listen to connection events
const unsubscribeConnected = onPrinterConnected(() => {
  console.log('Printer connected');
});

// Listen to error events
const unsubscribeError = onPrinterError((error) => {
  console.error('Printer error:', error);
});

// Clean up listeners
// unsubscribeConnected();
// unsubscribeError();
// Or remove all:
// removeAllListeners();

Table Printing Example

// Print a receipt table
await KozenPrinterLibrary.setAlignment('center');
await KozenPrinterLibrary.setBold(true);
await KozenPrinterLibrary.printText('RECEIPT');
await KozenPrinterLibrary.setBold(false);
await KozenPrinterLibrary.lineWrap(1);

// Table header
await KozenPrinterLibrary.printColumnsText(
  ['Item', 'Qty', 'Price'],
  [20, 10, 15],
  ['left', 'center', 'right']
);

// Table rows
await KozenPrinterLibrary.printColumnsText(
  ['Product A', '2', '$10.00'],
  [20, 10, 15],
  ['left', 'center', 'right']
);

await KozenPrinterLibrary.printColumnsText(
  ['Product B', '1', '$5.00'],
  [20, 10, 15],
  ['left', 'center', 'right']
);

await KozenPrinterLibrary.lineWrap(2);
await KozenPrinterLibrary.cutPaper();

Complete Receipt Example

async function printReceipt() {
  try {
    // Connect and initialize
    await KozenPrinterLibrary.prepare();

    // Header
    await KozenPrinterLibrary.setAlignment('center');
    await KozenPrinterLibrary.setBold(true);
    await KozenPrinterLibrary.printText('MY STORE');
    await KozenPrinterLibrary.setBold(false);
    await KozenPrinterLibrary.printText('123 Main St');
    await KozenPrinterLibrary.printText('Phone: 555-1234');
    await KozenPrinterLibrary.lineWrap(1);

    // Receipt details
    await KozenPrinterLibrary.setAlignment('left');
    await KozenPrinterLibrary.printText('Date: ' + new Date().toLocaleString());
    await KozenPrinterLibrary.printText('Receipt #: 12345');
    await KozenPrinterLibrary.lineWrap(1);

    // Items
    await KozenPrinterLibrary.printColumnsText(
      ['Item', 'Price'],
      [25, 15],
      ['left', 'right']
    );
    await KozenPrinterLibrary.printText('--------------------------------');
    
    await KozenPrinterLibrary.printColumnsText(
      ['Product 1', '$10.00'],
      [25, 15],
      ['left', 'right']
    );
    await KozenPrinterLibrary.printColumnsText(
      ['Product 2', '$5.00'],
      [25, 15],
      ['left', 'right']
    );

    await KozenPrinterLibrary.printText('--------------------------------');
    await KozenPrinterLibrary.setBold(true);
    await KozenPrinterLibrary.printColumnsText(
      ['Total', '$15.00'],
      [25, 15],
      ['left', 'right']
    );
    await KozenPrinterLibrary.setBold(false);
    await KozenPrinterLibrary.lineWrap(2);

    // QR Code
    await KozenPrinterLibrary.setAlignment('center');
    await KozenPrinterLibrary.printQRCode('https://example.com/receipt/12345', 8, 'middle');
    await KozenPrinterLibrary.lineWrap(2);

    // Footer
    await KozenPrinterLibrary.printText('Thank you for your purchase!');
    await KozenPrinterLibrary.lineWrap(3);
    await KozenPrinterLibrary.cutPaper();

    // Disconnect
    await KozenPrinterLibrary.disconnect();
  } catch (error) {
    console.error('Print error:', error);
  }
}

Testing

Unit Tests

Run unit tests with mocked NativeModules:

npm test

Hardware Tests

For testing with actual hardware, use the hardware test suite:

import { runHardwareTests } from 'react-native-kozen-printer/src/__tests__/hardware/PrinterHardwareTest';

// Run all hardware tests
await runHardwareTests();

Development

Building the Library

# Build TypeScript to JavaScript
npm run build

# Type check without building
npm run typecheck

# Run linter
npm run lint

# Clean build artifacts
npm run clean

Build System

This library uses react-native-builder-bob for building. The build system generates:

  • CommonJS format (lib/commonjs/)
  • ES Modules format (lib/module/)
  • TypeScript definitions (lib/typescript/)

Troubleshooting

Expo-Specific Issues

"Module not found" or "Native module not linked" in Expo Dev Build

Solution:

  1. Ensure the config plugin is added to app.json:

    {
      "expo": {
        "plugins": ["react-native-kozen-printer"]
      }
    }
  2. Run prebuild with clean to regenerate native directories:

    npx expo prebuild --clean
  3. Verify the plugin ran successfully - check that:

    • AIDL files exist in android/app/src/main/aidl/
    • JAR file exists in android/app/libs/core-3.3.0.jar
    • build.gradle includes the AIDL sourceSets and JAR dependency
  4. Rebuild the development client:

    npx expo run:android
    # OR
    eas build --profile development --platform android
  5. If still not working, verify autolinking:

    npx expo-modules-autolinking verify -v

    Look for react-native-kozen-printer in the output.

"expo prebuild" overwrites manual changes

Solution:

  • Use the config plugin - All native configuration is handled automatically
  • Use app.config.js or app.json for configuration instead of manually editing native files
  • The plugin is idempotent - Safe to run expo prebuild multiple times
  • ⚠️ Don't manually edit files that the plugin manages (AIDL, JAR, build.gradle sections)

Development build doesn't include the library

Solution:

  1. Verify config plugin is in app.json:

    {
      "expo": {
        "plugins": ["react-native-kozen-printer"]
      }
    }
  2. Clean and regenerate native directories:

    npx expo prebuild --clean
  3. Verify plugin output - Check prebuild logs for [KozenPrinter] messages

  4. Verify files were copied:

    • android/app/src/main/aidl/com/xcheng/printerservice/ should exist
    • android/app/libs/core-3.3.0.jar should exist
  5. Verify node_modules/react-native-kozen-printer exists

  6. Check that android/settings.gradle includes the module (should be auto-generated by React Native autolinking)

  7. Rebuild the development client

General Issues

Printer service not found

Ensure the Kozen printer service app is installed on the device. The service package is com.xcheng.printerservice.

Check service installation:

adb shell pm list packages | grep xcheng

Connection failed

  1. Check that the printer service is running
  2. Verify BLUETOOTH permission is granted in Android settings
  3. Ensure the device is a Kozen POS device with printer hardware
  4. Check Android logcat for connection errors:
    adb logcat | grep -i printer

Build errors

For Bare React Native / Expo Bare:

  • Ensure android/settings.gradle includes the :react-native-kozen-printer module
  • Verify android/app/build.gradle has the dependency
  • Check that AIDL files are in the correct location
  • Clean build: cd android && ./gradlew clean && cd ..

For Expo Dev Build:

  • Ensure config plugin is in app.json - "plugins": ["react-native-kozen-printer"]
  • Run npx expo prebuild --clean to regenerate native directories with plugin applied
  • Verify plugin copied AIDL files and JAR dependency
  • Ensure you're using a development build, not Expo Go
  • Rebuild the development client after configuration changes

"Package not found" or linking errors

  1. Verify the library is installed:
    npm list react-native-kozen-printer
  2. Clear Metro bundler cache:
    npm start -- --reset-cache
  3. Clean and rebuild:
    # For bare React Native
    cd android && ./gradlew clean && cd ..
       
    # For Expo
    npx expo prebuild --clean

TypeScript errors

If you see TypeScript errors about missing types:

  1. Ensure you're using TypeScript 4.8+
  2. Restart your TypeScript server in your IDE
  3. Run npm run typecheck to verify types

License

MIT