krushkamx / nativescript-hprt

Print to thermal printers from HPRT in your Nativescript application https://www.hprt.com/
MIT License
29 stars 16 forks source link

2023-10-12 Update: Unfortunately as you could notice, I don't have enought time to mantain this library anymore, I also switched to Flutter in aspect of mobile development so if you want and know, fork this plugin and adopt it to your use.


Nativescript HPRT Thermal Bluetooth Printer

This plugin uses HPRT SDK for Android and iOS (coming soon) from HPRT. At this moment it is tested on mobile bluetooth thermal printers that use 57mm (2.24") rolls. The SDK supports also wifi and other printer features that are not included (yet), we are open for PRs and contributions.

Installation

tns plugin add nativescript-hprt

Demo

You can find demo app here https://github.com/krushkamx/nativescript-hprt-demo

API

Importing the plugin

import { Component, OnInit } from "@angular/core";
import { Hprt, HPRTPrinter } from "nativescript-hprt";

export class YourClass implements OnInit {
    private hprt: Hprt;

    constructor() {
        this.hprt = new Hprt();
    }

    ngOnInit(): void {

        // Optional, you can enable bluetooth at init (Android only)
        this.enableBluetooth();

    }
}

enableBluetooth

Enables bluetooth if it's turned off, it receives timout value, at this moment it is timeout after which this promise resolves, will try to make automatic. You can call this from ngOnInit() or have a button.

this.hprt.enableBluetooth().then((res) => {
    console.log("BT Enabled", res);
}, (err) => {
    console.log("Error", err);
})
Property Default Description
timeout 6000 Optional. Not used at this moment, will be used in next update to define timeout if bluetooth is not enabled

isBluetoothEnabled

Returns true or false depending on bluetooth state

let isBluetoothEnabled = this.hprt.isBluetoothEnabled();

searchPrinters

It returns array of printers discovered.

printers: Array<HPRTPrinter>;

ngOnInit() {    
    this.printers = [];
}

this.hprt.searchPrinters().then(printers => {
    this.printers = printers;
});

connect

You should call this after bluetooth is turned on.

this.hprt.connect(printer).then((res) => {
    console.log("Printer connected");
}, (err) => {
    console.log("Connect error", err)
})
Property Default Description
printer Required Printer object you get from printer search

disconnect

Disconnect connected printer, no parameter needed.

this.hprt.disconnect().then((res) => {
    console.log("Disconnected");
}, (err) => {
    console.log("error", err)
})

isConnected

Returns true or false if printer is connected. Useful to call before you perform some print action, so you can connect to printer automatically or manually.

let isConnected = this.hprt.isConnected();

Printing API

You should call this after you've connected to printer

printTextSimple

Prints simple text, default styles.

this.hprt.printTextSimple("Hello world");
Property Type Default Description
text string Required Prints simple text, default styles.

printText

Advanced text printing

this.hprt.printText("Hello world", 1, 48, 0);
Property Type Default Description
alignment number 0 Left: 0, Center: 1, Right: 2
attribute number 0 Sets style attributes. Double height: 16, Double Width: 32, Underline: 4, Bold: 2, Mini: 1, White text: 8. You can combine styles by setting sum of styles. Example: Mini + Bold = 3, Double height + width = 48
textSize number 0 Still trying to figure out how this value is used

printTextDouble

Prints double size text

this.hprt.printTextDouble("Hello world");
Property Type Default Description
text string Required Double text

printTextDoubleHeight

Prints double height text

this.hprt.printTextDoubleHeight("Hello world");
Property Type Default Description
text string Required Double height text

printTextDoubleWidth

Prints double width text

this.hprt.printTextDoubleWidth("Hello world");
Property Type Default Description
text string Required Double width text

printTextUnderline

Prints underline text

this.hprt.printTextUnderline("Hello world");
Property Type Default Description
text string Required

printTextBold

Prints text in bold

this.hprt.printTextBold("Hello world");
Property Type Default Description
text string Required

printTextMini

Prints mini text

this.hprt.printTextMini("Hello world");
Property Type Default Description
text string Required

printTextWhite

Prints text in white

this.hprt.printTextWhite("Hello world");
Property Type Default Description
text string Required

printTextLeft

Prints left text

this.hprt.printTextLeft("Hello world");
Property Type Default Description
text string Required

printTextCenter

Prints center text

this.hprt.printTextCenter("Hello world");
Property Type Default Description
text string Required

printTextRight

Prints right text

this.hprt.printTextRight("Hello world");
Property Type Default Description
text string Required

Helpers API

newLine

Adds lines (breaks), useful at the end of receipt when you want to leave space to cut it.

this.hprt.newLine(3);
Property Type Default Description
lines number 1 Optional

horizontalLine

Adds horizontal line (-------) in 32 characters.

this.hprt.horizontalLine();

Working with workers

Add enable-bluetooth.js to app/workers with this code:

global.onmessage = function(msg) {

    var result = enableBluetooth();

    global.postMessage(result);
}

function enableBluetooth() {
    let mBluetoothAdapter = android.bluetooth.BluetoothAdapter.getDefaultAdapter();

    if (mBluetoothAdapter == null) {
        return { success: false, message: "Bluetooth NOT support", enabled: false}
    }
    else {
        if (mBluetoothAdapter.isEnabled()) {
            if (mBluetoothAdapter.isDiscovering()) {
                return { success: true, message: "Bluetooth is currently in device discovery process.", enabled: false};
            } else {
                return { success: true, message: "Bluetooth is enabled", enabled: true}
            }
        }
        else {
            mBluetoothAdapter.enable();
            return { success: true, message: "", enabled: false};
        }
    }

}

Add connect-printer.js to app/workers with this code:

global.onmessage = function(msg) {
    var request = msg.data;
    var port = request.port;

    var result = connectPrinter(port);

    global.postMessage(result);
}

function connectPrinter(port) {
    let isPortOpen = HPRTAndroidSDK.HPRTPrinterHelper.PortOpen("Bluetooth,"+port.portName);

    return isPortOpen;
}

Include workers in your webpack build

Add copying workers in your webpack build

new CopyWebpackPlugin([
    { from: { glob: "*.css" } },
    { from: { glob: "assets/*.css" } },
    { from: { glob: "workers/**" } }, // <-- Add this line to your CopyWebpackPlugin config in webpack.config.js
    { from: { glob: "fonts/**" } },
    { from: { glob: "**/*.jpg" } },
    { from: { glob: "**/*.png" } },
], { ignore: [`${relative(appPath, appResourcesFullPath)}/**`] }),

Tested with printers

Tested with Android phones