Coder Social home page Coder Social logo

webbluetoothreceiptprinter's Introduction

WebBluetoothReceiptPrinter

This is an library that allows you to print to a Bluetooth connected receipt printer using WebBluetooth.

What does this library do?

In order to print a receipt on a receipt printer you need to build the receipt and encode it as in the ESC/POS or StarPRNT language. You can use the ThermalPrinterEncoder library for this. You end up with an array of raw bytes that needs to be send to the printer. One way to do that is using this library and WebBluetooth.

How to use it?

Load the webbluetooth-receipt-printer.umd.js file from the dist directory in the browser and instantiate a WebBluetoothReceiptPrinter object.

<script src='webbluetooth-receipt-printer.umd.js'></script>

<script>

    const receiptPrinter = new WebBluetoothReceiptPrinter();

</script>

Or import the webbluetooth-receipt-printer.esm.js module:

import WebHIDBarcodeScanner from 'webbluetooth-receipt-printer.esm.js';

const receiptPrinter = new WebBluetoothReceiptPrinter();

Connect to a receipt printer

The first time you have to manually connect to the receipt printer by calling the connect() function. This function must be called as the result of an user action, for example clicking a button. You cannot call this function on page load.

function handleConnectButtonClick() {
    receiptPrinter.connect();
}

In the future, there is a way to reconnect to already connected printers. This functionality is still behind a flag in currently shipping browsers. To do it you can simply call the reconnect() function. You have to provide an object with the id of the previously connected receipt printer in order to find the correct printer and connect to it again. You can get this data by listening to the connected event and store it for later use. It is recommended to call this button on page load to prevent having to manually connect to a previously connected device.

receiptPrinter.reconnect(lastUsedDevice);

If there are no receipt printers connected that have been previously connected, or the id does not match up, this function will do nothing.

To find out when a receipt printer is connected you can listen for the connected event using the addEventListener() function.

receiptPrinter.addEventListener('connected', device => {
    console.log(`Connected to ${device.name} (#${device.id})`);

    printerLanguage = device.language;
    printerCodepageMapping = device.codepageMapping;

    /* Store device for reconnecting */
    lastUsedDevice = device;
});

The callback of the connected event is passed an object with the following properties:

  • type
    Type of the connection that is used, in this case it is always bluetooth.
  • name
    The name of the receipt printer.
  • id
    A unique id for the receipt printer. To be used to reconnect to the printer at a later time.
  • language
    Language of the printer, which can be either esc-pos or star-prnt. This can be used as an option for ThermalPrinterEncoder to encode in the correct language for the printer.
  • codepageMapping
    Code page mapping of the printer, which can be used as an option for ThermalPrinterEncoder to map non-ascii characters to the correct codepage supported by the printer.

Commands

Once connected you can use the following command to print receipts.

Printing receipts

When you want to print a receipt, you can call the print() function with an array, or a typed array with bytes. The data must be properly encoded for the printer.

For example:

/* Encode the receipt */

let encoder = new ThermalPrinterEncoder({
    language:  printerLanguage,
    codepageMapping: printerCodepageMapping
});

let data = encoder
    .initialize()
    .text('The quick brown fox jumps over the lazy dog')
    .newline()
    .qrcode('https://nielsleenheer.com')
    .encode();

/* Print the receipt */

receiptPrinter.print(data);

License

MIT

webbluetoothreceiptprinter's People

Contributors

nielsleenheer avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

webbluetoothreceiptprinter's Issues

Image Print issue

Hi,

I have a chinese Epson ESC/POS compatible printer [(https://www.amazon.it/Excelvan-Bluetooth-Automatico-Stampante-Stampanti/dp/B01HO7P8QM?th=1)](this one) and I'm having issues printing an image.

I'm trying to print this sample logo:
logo-black-squared

what I get is something like this:
WhatsApp Image 2023-09-21 at 21 10 10

or this:
WhatsApp Image 2023-09-21 at 21 13 50

if I switch to raster mode, I get variable results, but at least there're no white lines:
WhatsApp Image 2023-09-21 at 21 11 00

Here's the code I'm using:

        const receiptPrinter = new WebBluetoothReceiptPrinter();
        receiptPrinter.connect().then((c) => {
            console.log('CONNECTED!');
            const encoder = new ThermalPrinterEncoder({
                language: 'esc-pos',
                width: 48               
            });
            const img = new Image();
            img.src = 'assets/logo-black-squared.png';

            img.onload = () => {
                const result2 = encoder
                    .initialize()
                    .align('center')
                    .image(img, 192, 192)
                    .encode();
                receiptPrinter.print(result2);
            };

        });

Any suggestion?

Thanks,
Matteo

Clarification on lastUsedDevice

Hi, first of all thank you for this project. It's really easy to use and helped me out a lot till now.
In the README you mentioned the reconnect() method. What would be the best way to store the device? I tried it using the localstorage (of course saved only the id of the device). I also enabled all necessary flags in chrome. But every time i use the reconnect() method after a reload of the page it does not select the printer i already selected before. Is there a work around or am i missing something?
Thanks for the help in advance.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.