node-printer-native
v1.0.1
Published
Modern cross-platform printer library for Node.js with N-API native bindings. Compatible with latest Node.js versions (16+). Supports Windows (Win32 API) and Unix/macOS (CUPS).
Maintainers
Readme
node-printer-native
A modern, cross-platform printer library for Node.js with native performance using N-API. Compatible with the latest Node.js versions (16+) and provides a stable API across all Node versions.
Features
✨ Modern & Stable: Built with N-API for compatibility across Node.js versions
🌍 Cross-Platform: Works on Windows, macOS, and Linux
⚡ Native Performance: Direct system API integration (Win32 on Windows, CUPS on Unix)
📘 TypeScript Support: Full TypeScript typings included
🎯 API Compatible: Maintains compatibility with the original node-printer API
🔔 Event-Driven: Real-time job status monitoring with events
💪 Production Ready: Comprehensive error handling and robust implementation
Installation
Prerequisites
Windows:
- Visual Studio Build Tools with C++ support
- Node.js 16 or higher
macOS:
- Xcode Command Line Tools
- CUPS (pre-installed on macOS)
- Node.js 16 or higher
Linux:
- GCC compiler
- CUPS development headers:
sudo apt-get install libcups2-dev(Ubuntu/Debian) - Node.js 16 or higher
Install
npm install node-printer-nativeThe native addon will automatically build during installation.
Quick Start
import { Printer } from 'node-printer-native';
// Get list of all available printers
const printers = Printer.list();
console.log('Available printers:', printers);
// Get the default printer
const defaultPrinter = Printer.getDefault();
console.log('Default printer:', defaultPrinter?.name);
// Create a printer instance
const printer = new Printer('Your Printer Name');
// Print a file
const job = await printer.printFile('./document.pdf', {
copies: 2,
media: 'A4',
orientation: 'portrait'
});
// Monitor job status
job.on('sent', () => console.log('Job sent to printer'));
job.on('completed', () => console.log('Print job completed!'));
job.on('failed', () => console.log('Print job failed'));API Reference
Printer Class
Static Methods
Printer.list(): PrinterInfo[]
Get a list of all available printers on the system.
const printers = Printer.list();
printers.forEach(p => {
console.log(`${p.name} - ${p.status}`);
});Printer.getDefault(): Printer | null
Get the default printer.
const printer = Printer.getDefault();
if (printer) {
console.log('Default printer:', printer.name);
}Printer.exists(name: string): boolean
Check if a printer exists.
if (Printer.exists('My Printer')) {
console.log('Printer found!');
}Instance Methods
constructor(name: string)
Create a new Printer instance.
const printer = new Printer('HP LaserJet');async getInfo(): Promise<PrinterInfo>
Get detailed printer information.
const info = await printer.getInfo();
console.log(info.capabilities);async printFile(filePath: string, options?: PrintOptions): Promise<PrintJob>
Print a file.
const job = await printer.printFile('./document.pdf', {
copies: 2,
media: 'A4',
color: true,
duplex: 'long'
});async printBuffer(buffer: Buffer, options?: PrintOptions): Promise<PrintJob>
Print raw data from a buffer.
const buffer = fs.readFileSync('./document.pdf');
const job = await printer.printBuffer(buffer, {
jobName: 'My Print Job'
});async printText(text: string, options?: PrintOptions): Promise<PrintJob>
Print plain text.
const job = await printer.printText('Hello, World!', {
jobName: 'Text Print'
});PrintJob Class
Represents a print job with event emission capabilities.
Properties
id: Job IDname: Job nameprinter: Printer namestatus: Current job statuscreatedAt: Job creation timestamp
Methods
async getInfo(): Promise<JobInfo>
Get detailed job information.
async cancel(): Promise<void>
Cancel the print job.
await job.cancel();async pause(): Promise<void>
Pause the print job.
async resume(): Promise<void>
Resume a paused job.
Events
sent: Job sent to printercompleted: Job completed successfullyfailed: Job failedcancelled: Job was cancelledstatus-changed: Status changed (receives new and old status)
job.on('completed', () => {
console.log('Print completed!');
});
job.on('status-changed', (newStatus, oldStatus) => {
console.log(`Status changed from ${oldStatus} to ${newStatus}`);
});Types
PrintOptions
interface PrintOptions {
copies?: number; // Number of copies (default: 1)
media?: string; // Paper size: 'A4', 'Letter', 'Custom.200x600mm'
orientation?: Orientation; // 'portrait' or 'landscape'
resolution?: number; // DPI
color?: boolean; // Color printing (default: true)
duplex?: DuplexMode; // 'simplex', 'long', 'short'
pageRange?: string; // e.g., '1-5', '1,3,5'
collate?: boolean; // Collate copies
jobName?: string; // Job name/title
}PrinterInfo
interface PrinterInfo {
name: string;
description?: string;
location?: string;
isDefault: boolean;
status: PrinterStatus;
statusMessage?: string;
jobCount: number;
capabilities?: PrinterCapabilities;
}Examples
Print with Options
const printer = new Printer('My Printer');
const job = await printer.printFile('./invoice.pdf', {
copies: 3,
media: 'A4',
orientation: 'portrait',
duplex: 'long',
color: true,
collate: true,
pageRange: '1-10',
jobName: 'Invoice #12345'
});Monitor Job Progress
const job = await printer.printFile('./document.pdf');
job.on('sent', () => {
console.log('Sending to printer...');
});
job.on('completed', async () => {
const info = await job.getInfo();
console.log(`Printed ${info.pages} pages`);
});
job.on('failed', () => {
console.error('Print failed');
});List All Printers with Details
const printers = Printer.list();
for (const p of printers) {
console.log(`
Name: ${p.name}
Status: ${p.status}
Location: ${p.location || 'Unknown'}
Jobs in queue: ${p.jobCount}
Color support: ${p.capabilities?.supportsColor}
Duplex support: ${p.capabilities?.supportsDuplex}
`.trim());
}Print Raw Text to Thermal Printer
const thermalPrinter = new Printer('Thermal Printer');
const receipt = `
================================
STORE RECEIPT
================================
Item 1...................$10.00
Item 2...................$20.00
--------------------------------
Total....................$30.00
================================
`;
await thermalPrinter.printText(receipt, {
jobName: 'Receipt'
});Platform-Specific Notes
Windows
Uses Win32 Print Spooler API directly for best performance and feature support. No additional dependencies required.
macOS
Uses CUPS API. CUPS is pre-installed on macOS. Requires Xcode Command Line Tools for building.
Linux
Uses CUPS API. Install CUPS development headers:
# Ubuntu/Debian
sudo apt-get install libcups2-dev
# Fedora/RHEL
sudo yum install cups-devel
# Arch Linux
sudo pacman -S cupsMigration from old node-printer
The API is largely compatible with the original node-printer:
// Old API
var Printer = require('node-printer');
var printer = new Printer('EPSON_SX510');
var job = printer.printFile('package.json');
// New API (same thing works!)
import { Printer } from 'node-printer-native';
const printer = new Printer('EPSON_SX510');
const job = await printer.printFile('package.json');Main differences:
- All methods are now async/Promise-based
- Full TypeScript support with type safety
- Better error handling with specific error types
- More reliable cross-platform support
Troubleshooting
Build Errors
Windows: Make sure Visual Studio Build Tools are installed with C++ support.
macOS/Linux: Ensure CUPS development headers are installed.
Printer Not Found
Check that the printer name is exact (case-sensitive):
const printers = Printer.list();
console.log(printers.map(p => p.name));Permission Errors
On Linux/macOS, ensure your user has permission to access CUPS:
sudo usermod -a -G lpadmin $USERDevelopment
# Clone the repository
git clone https://github.com/yourusername/node-printer-lib.git
# Install dependencies
npm install
# Build native addon and TypeScript
npm run build
# Run tests
npm test
# Clean and rebuild
npm run rebuildLicense
MIT
Contributing
Contributions are welcome! Please open an issue or submit a pull request.
Credits
Inspired by the original node-printer by alepee.
