Skip to content

Instantly share code, notes, and snippets.

@tresf
Last active June 25, 2024 09:29
Show Gist options
  • Save tresf/f5ffb9445072dcd468209596de933202 to your computer and use it in GitHub Desktop.
Save tresf/f5ffb9445072dcd468209596de933202 to your computer and use it in GitHub Desktop.
// From https://github.com/WebBluetoothCG/demos/blob/gh-pages/bluetooth-printer/index.html
var SERVICE = '000018f0-0000-1000-8000-00805f9b34fb';
var WRITE = '00002af1-0000-1000-8000-00805f9b34fb';
var DATA = ''
+ '\x1B' + '\x61' + '\x31' // center align
+ '\x1D' + '\x21' + '\x11' + 'Hello\nBluetooth!\n\n' // double font size
+ '\x1D' + '\x21' + '\x00' + '... from your friends\nat https://qz.io' // normal font size
+ '\n\n\n\n\n\n\n'; // feed paper
var deviceHandle;
navigator.bluetooth.requestDevice({ filters: [{ services: [SERVICE]}] }).then(device => {
console.log(device);
deviceHandle = device;
return device.gatt.connect()
}).then(server => {
console.log(server);
return server.getPrimaryService(SERVICE);
}).then(service => {
console.log(service);
return service.getCharacteristic(WRITE);
}).then(channel => {
console.log(channel);
return channel.writeValue(new TextEncoder("utf-8").encode(DATA));
}).catch(error => {
console.error(error)
}).finally(() => {
deviceHandle.gatt.disconnect();
});
@elvispdosreis
Copy link

I am having difficulty printing on a thermal printer model HM-A400

SecurityError: Origin is not allowed to access the service. Tip: Add the service UUID to 'optionalServices' in requestDevice() options. https://goo.gl/HxfxSQ

@tresf
Copy link
Author

tresf commented Feb 16, 2024

What is your origin? Is it a private address? Is it an HTTPS address? It's been a while since I've tried this code, but from what I recall Google is pretty picky about this (for example, they block access to their crypto libs when using HTTP).

There's also a good chance that the security model has changed and that the code has become outdated. If so, feel free to fork this example and link the fork in the comments.

@fathulhusnan
Copy link

Hey, is it possible to print an image? Like, i want to print receipt that include company's logo on the top of the receipt

@tresf
Copy link
Author

tresf commented Apr 22, 2024

Hey, is it possible to print an image? Like, i want to print receipt that include company's logo on the top of the receipt

@fathulhusnan Hi! Yes, however this will require converting the image from a raster/pixel format over to valid ESC/POS commands. There are several libraries that claim to support this. Here's one of them: https://github.com/NielsLeenheer/EscPosEncoder?tab=readme-ov-file#image

@fathulhusnan
Copy link

Thank you so much! It's help a lot!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment