You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
write() function not working with thermal printer #461
I am using the plugin to connect and print using a thermal printer. but the write() function is not working giving error: Device connection was lost.
my code:
`
import { BluetoothSerial } from '@awesome-cordova-plugins/bluetooth-serial/ngx';
....
async printStuff() {
// this.alertMessage2(this.selectedPrinter);
this.bluetooth.connect(this.selectedPrinter)
.subscribe(async() => {
//2. Connected successfully
// this.alertMessage2('392: ' + success)
await this.bluetooth.write(this.espEncode())
.then(success => {
//3. Print successful
//If you want to tell user print is successful,
//handle it here
//4. IMPORTANT! Disconnect bluetooth after printing
// console.log('sucess')
this.alertMessage2('401: ' + success)
this.bluetooth.disconnect()
}, err => {
//If there is an error printing to bluetooth printer
//handle it here
console.error('43:' + err)
this.alertMessage2('error 43: ' + err)
})
}, err => {
//If there is an error connecting to bluetooth printer
//handle it here
this.alertMessage('error 416: ' + err, '')
this.bluetooth.disconnect();
console.error(err)
})
// await this.print.sendToBluetoothPrinter(this.selectedPrinter, this.espEncode());
}`
Hey, first of all using both await and .then() is incorrect since await "waits" for the return of the .then() value but you still need a catch function if an error occurs.
You should use either
try {
await function()
} catch (err) {
// error handling
} finally {
// optional function that happens in both cases
}
or
.then(
// function
)
.catch(
// error handling
)
Secondly, and hopefully to answer your question, it might be an issue with your encoding, most thermal printers use ESC/POS command sequence - they require certain commands to print. Bellow you will find a snippet* of how I print via an embedded thermal printer with this plugin:
async printImage(base64Representation: string, widthRatio: number): Promise {
// Convert the base64 image to a Uint8Array containing bitmap data
const qrBitmap = await this.convertBase64ToBitmap(base64Representation, widthRatio);
// Set up the ESC/POS command sequence for raster graphics
const command = [
0x1D, 0x76, 0x30, 0x00, // GS v 0 command for raster graphics
(qrBitmap.width / 8) & 0xFF, // Width in bytes (low byte)
(qrBitmap.width / 8) >> 8, // Width in bytes (high byte)
qrBitmap.height & 0xFF, // Height (low byte)
qrBitmap.height >> 8, // Height (high byte)
...qrBitmap.pixels, // Pixel data from QR code
0x0A, 0x0A, 0x0A, // Newline/linefeeds to flush the buffer
0x0C // Form feed (flushes and prints the data)
];
// Send the command sequence to the printer
await bluetoothSerial.write(Uint8Array.from(command));
}
// Helper function to convert base64 image to grayscale bitmap
private async convertBase64ToBitmap(base64: string, widthRatio: number): Promise<{ width: number, height: number, pixels: Uint8Array }> {
// Load the image from base64 using image-js
const image = await Image.load(base64);
const grayscale = image.grey(); // Convert to grayscale for easier printing
// Resize to fit printer width (usually 400px)
const resized = grayscale.resize({width: ROLL_SIZE, height: widthRatio * ROLL_SIZE});
// Initialize a Uint8Array to store pixel data
const width = resized.width;
const height = resized.height;
const pixels = new Uint8Array((width * height) / 8);
``
// Apply manual threshold and pack bits into the `pixels` array
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
const pixelValue = resized.getPixelXY(x, y)[0]; // Get the intensity (0-255)
const isBlack = pixelValue < 128 ? 0 : 1; // Apply threshold: 0 for black, 1 for white
const byteIndex = (y * width + x) >> 3; // Index in `pixels` array
const bitIndex = x % 8; // Position within the byte
pixels[byteIndex] |= isBlack << (7 - bitIndex); // Set bit in byte for black pixel
}
}
return {width, height, pixels};
}
*I use base64 representation of an image for my usecase and I adjust the width based on the paper size, but I`m sure you can adapt it to your needs and of course you have to use try catch in the upper level function that invokes this one in order to capture any eventual errors.
Hey, first of all using both await and .then() is incorrect since await "waits" for the return of the .then() value but you still need a catch function if an error occurs. You should use either
try { await function() } catch (err) { // error handling } finally { // optional function that happens in both cases }
or
.then( // function ) .catch( // error handling )
Secondly, and hopefully to answer your question, it might be an issue with your encoding, most thermal printers use ESC/POS command sequence - they require certain commands to print. Bellow you will find a snippet* of how I print via an embedded thermal printer with this plugin:
async printImage(base64Representation: string, widthRatio: number): Promise { // Convert the base64 image to a Uint8Array containing bitmap data const qrBitmap = await this.convertBase64ToBitmap(base64Representation, widthRatio);
// Set up the ESC/POS command sequence for raster graphics
const command = [
0x1D, 0x76, 0x30, 0x00, // GS v 0 command for raster graphics
(qrBitmap.width / 8) & 0xFF, // Width in bytes (low byte)
(qrBitmap.width / 8) >> 8, // Width in bytes (high byte)
qrBitmap.height & 0xFF, // Height (low byte)
qrBitmap.height >> 8, // Height (high byte)
...qrBitmap.pixels, // Pixel data from QR code
0x0A, 0x0A, 0x0A, // Newline/linefeeds to flush the buffer
0x0C // Form feed (flushes and prints the data)
];
// Send the command sequence to the printer
await bluetoothSerial.write(Uint8Array.from(command));
}
// Helper function to convert base64 image to grayscale bitmap private async convertBase64ToBitmap(base64: string, widthRatio: number): Promise<{ width: number, height: number, pixels: Uint8Array }> { // Load the image from base64 using image-js const image = await Image.load(base64); const grayscale = image.grey(); // Convert to grayscale for easier printing
// Resize to fit printer width (usually 400px)
const resized = grayscale.resize({width: ROLL_SIZE, height: widthRatio * ROLL_SIZE});
// Initialize a Uint8Array to store pixel data const width = resized.width; const height = resized.height; const pixels = new Uint8Array((width * height) / 8); ``
// Apply manual threshold and pack bits into the `pixels` array
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
const pixelValue = resized.getPixelXY(x, y)[0]; // Get the intensity (0-255)
const isBlack = pixelValue < 128 ? 0 : 1; // Apply threshold: 0 for black, 1 for white
const byteIndex = (y * width + x) >> 3; // Index in `pixels` array
const bitIndex = x % 8; // Position within the byte
pixels[byteIndex] |= isBlack << (7 - bitIndex); // Set bit in byte for black pixel
}
}
return {width, height, pixels};
}
*I use base64 representation of an image for my usecase and I adjust the width based on the paper size, but I`m sure you can adapt it to your needs and of course you have to use try catch in the upper level function that invokes this one in order to capture any eventual errors.
| Hi @alexandrucozmanca I'm able to print but first write command prints OK, second write command do not print, third write command prints OK, and so on, one success, one fails. When it fails, console logs says all is ok, but printer just make a sound like it tried to print and paper advance like one line. I have tried clear() and disconnect() after print finish, but same behavior. Please, What do you think I'm missing? Thanks!! It is an Ionic 8 App, I use https://github.com/NielsLeenheer/ReceiptPrinterEncoder to encode ESC/POS data. This is the code I'm trying:
async printDemoReceiptPrinterEncoder() {
let encoder = new ReceiptPrinterEncoder();
let result = encoder
.initialize()
.text('The quick brown fox jumps over the lazy dog')
.bold(true)
.line('This text is bold and large')
.bold(false)
.size(2)
.line('This text is twice as large as normal text')
.size(1)
.newline()
.table(
[
{ width: 36, marginRight: 2, align: 'left' },
{ width: 10, align: 'right' }
],
[
[ 'Item 1', '$ 10,00' ],
[ 'Item 2', '$ 15,00' ],
[ 'Item 3', '$ 9,95' ],
[ 'Item 4', '$ 4,75' ],
[ 'Item 5', '$ 211,05' ],
[ '', '='.repeat(10) ],
[ 'Total', (encoder: ReceiptPrinterEncoder) => encoder.bold().text('$ 250,75').bold() ],
]
)
.qrcode('https://nielsleenheer.com')
.newline()
.newline()
.encode();
await this.sentToPrinter(result);
}
async sentToPrinter(data: any) {
console.log('CORDOBA Sending data to printer');
const isConnected = await this.isConnected();
if (isConnected) {
await this.printDataCordova(data);
} else {
console.log('CORDOBA Not connected to printer');
await this.connect(data);
}
}
async printDataCordova(data: any) {
try {
await BluetoothSerial.write(data);
console.log('CORDOVA Data written to device');
await this.disconnect();
} catch (error) {
console.log('CORDOVA Error writing data to device');
console.log(error);
}
}
async connect(data: any) {
BluetoothSerial.connect('66:32:CF:00:F1:D0').subscribe(() => {
console.log('CORDOBA Successfully connected SECURE');
this.printDataCordova(data);
}, (error: any) => {
console.log('CORDOBA Error connecting SECURE...');
console.log(error);
});
}
async disconnect() {
try {
const result = await BluetoothSerial.disconnect();
console.log('CORDOBA disconnect result: ', result);
return result;
} catch (error) {
console.log('CORDOBA Error disconnecting...');
console.log(error);
return false;
}
}
async isConnected(): Promise<boolean> {
try {
const isConnected = await BluetoothSerial.isConnected();
console.log('CORDOBA isConnected: ', isConnected);
return isConnected.toLowerCase() === 'ok';
} catch (error) {
console.log('CORDOBA Error checking if connected...');
console.log(error);
return false;
}
}
async clear(){
try {
const result = await BluetoothSerial.clear();
console.log('CORDOBA clear result: ', result);
return result;
} catch (error) {
console.log('CORDOBA Error clearing...');
console.log(error);
}
}
Activity
sadalsuud commentedon May 19, 2023
In my case no it does not shows any message, supposedly print, but It does not print
bobolat commentedon Jan 19, 2024
i have the same problem..got Write successfully OK but printer no action
alexandrucozmanca commentedon Jun 10, 2025
Hey, first of all using both await and .then() is incorrect since await "waits" for the return of the .then() value but you still need a catch function if an error occurs.
You should use either
try {
await function()
} catch (err) {
// error handling
} finally {
// optional function that happens in both cases
}
or
.then(
// function
)
.catch(
// error handling
)
Secondly, and hopefully to answer your question, it might be an issue with your encoding, most thermal printers use ESC/POS command sequence - they require certain commands to print. Bellow you will find a snippet* of how I print via an embedded thermal printer with this plugin:
async printImage(base64Representation: string, widthRatio: number): Promise {
// Convert the base64 image to a Uint8Array containing bitmap data
const qrBitmap = await this.convertBase64ToBitmap(base64Representation, widthRatio);
}
// Helper function to convert base64 image to grayscale bitmap
private async convertBase64ToBitmap(base64: string, widthRatio: number): Promise<{ width: number, height: number, pixels: Uint8Array }> {
// Load the image from base64 using
image-jsconst image = await Image.load(base64);
const grayscale = image.grey(); // Convert to grayscale for easier printing
// Initialize a Uint8Array to store pixel data
const width = resized.width;
const height = resized.height;
const pixels = new Uint8Array((width * height) / 8);
``
}
*I use base64 representation of an image for my usecase and I adjust the width based on the paper size, but I`m sure you can adapt it to your needs and of course you have to use try catch in the upper level function that invokes this one in order to capture any eventual errors.
numobizdev commentedon Nov 7, 2025
| Hi @alexandrucozmanca I'm able to print but first write command prints OK, second write command do not print, third write command prints OK, and so on, one success, one fails. When it fails, console logs says all is ok, but printer just make a sound like it tried to print and paper advance like one line. I have tried clear() and disconnect() after print finish, but same behavior. Please, What do you think I'm missing? Thanks!! It is an Ionic 8 App, I use https://github.com/NielsLeenheer/ReceiptPrinterEncoder to encode ESC/POS data. This is the code I'm trying: