Git Product home page Git Product logo

thermal-printer-cordova-plugin's Introduction

Cordova Plugin for Thermal Printer's

npm version npm downloads


This plugin is a wrapper for the Android library for ESC/POS Thermal Printer.

Install

Cordova

$ cordova plugin add thermal-printer-cordova-plugin

Ionic

$ ionic cordova plugin add thermal-printer-cordova-plugin

Capacitor

$ npm install thermal-printer-cordova-plugin
$ npx cap sync

Don't forget to add BLUETOOTH and INTERNET (for TCP) permissions and for USB printers the android.hardware.usb.host feature to the AndroidManifest.xml.

<uses-feature android:name="android.hardware.usb.host" />
<uses-permission android:maxSdkVersion="30" android:name="android.permission.BLUETOOTH" />
<uses-permission android:maxSdkVersion="30" android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
<uses-permission android:name="android.permission.BLUETOOTH_SCAN" />

Run this for getting Bluetooth access permission if needed

ThermalPrinter.requestBTPermissions({type: 'bluetooth'}, function(result){ console.log(result) }, function(error){ console.log(error) });

Examples

Notice for TypeScript-Developers

You can easily import and use the ThermalPrinter plugin in your TypeScript-Projects.

import { ThermalPrinterPlugin } from 'thermal-printer-cordova-plugin/src';

declare let ThermalPrinter: ThermalPrinterPlugin;

And then use the following examples in your code.

Print via Bluetooth

Printing via Bluetooth is as easy as possible.

ThermalPrinter.printFormattedText({
    type: 'bluetooth',
    id: 'first', // You can also use the identifier directly i. e. 00:11:22:33:44:55 (address) or name
    text: '[C]<u><font size='big'>Hello World</font></u>' // new lines with "\n"
}, function() {
    console.log('Successfully printed!');
}, function(error) {
    console.error('Printing error', error);
});

Notice: If not working please ensure that you have the printer connected. (Settings -> Bluetooth -> Pairing) If you have other issues maybe you have not granted the android.permission.BLUETOOTH permission.

Print via TCP

Printing via TCP is as easy as possible.

ThermalPrinter.printFormattedText({
    type: 'tcp',
    address: '192.168.1.123',
    port: 9100,
    id: 'tcp-printer-001', // Use an unique identifier for each printer i. e. address:port or name
    text: '[C]<u><font size='big'>Hello World</font></u>' // new lines with "\n"
}, function() {
    console.log('Successfully printed!');
}, function(error) {
    console.error('Printing error', error);
});

Notice: If not working please ensure that your device can ping the printer. And the printer must be a POSPrinter! Also ensure that you're using the correct port. 9100 is default for the thermal printers.

Print via USB (incl. listPrinters and requestPermissions)

  1. First we get our printer because we don't know the printer's ID.
  2. Then we request permissions for printing. This is needed because Android will not allow us to access all devices.
  3. And finally we can print with our device.
ThermalPrinter.listPrinters({type: 'usb'}, function(printers) {
    if (printers.length > 0) {
        var printer = printers[0];
        ThermalPrinter.requestPermissions(printer, function() {
            // Permission granted - We can print!
            ThermalPrinter.printFormattedText({
                type: 'usb',
                id: printer.id,
                text: '[C]<u><font size='big'>Hello World</font></u>' // new lines with "\n"
            }, function() {
                console.log('Successfully printed!');
            }, function(error) {
                console.error('Printing error', error);
            });
        }, function(error) {
            console.error('Permission denied - We can\'t print!');
        });
    } else {
        console.error('No printers found!');
    }
}, function(error) {
    console.error('Ups, we cant list the printers!', error);
});

listPrinters(data, successCallback, errorCallback)

List available printers

Param Type Description
data Object Data object
data.type "bluetooth" | "usb" Type of list: bluetooth or usb
successCallback function Result on success
errorCallback function Result on failure

printFormattedText(data, successCallback, errorCallback)

Print a formatted text and feed paper

See: https://github.com/DantSu/ESCPOS-ThermalPrinter-Android#formatted-text--syntax-guide

Param Type Description
data Array.<Object> Data object
data.type "bluetooth" | "tcp" | "usb" List all bluetooth or usb printers
[data.id] string | number ID of printer to find (Bluetooth: address, TCP: Use address + port instead, USB: deviceId)
[data.address] string If type is "tcp" then the IP Address of the printer
[data.port] number If type is "tcp" then the Port of the printer
[data.mmFeedPaper] numberoptional Millimeter distance feed paper at the end
[data.dotsFeedPaper] numberoptional Distance feed paper at the end
[data.printerDpi] numberoptional Printer DPI
[data.printerWidthMM] numberoptional Paper Width in mm
[data.printerNbrCharactersPerLine] numberoptional Number of characters per line
data.text string Formatted text to be printed
successCallback function Result on success
errorCallback function Result on failure

printFormattedTextAndCut(data, successCallback, errorCallback)

Print a formatted text, feed paper and cut the paper

See: https://github.com/DantSu/ESCPOS-ThermalPrinter-Android#formatted-text--syntax-guide

Param Type Description
data Array.<Object> Data object
data.type "bluetooth" | "tcp" | "usb" List all bluetooth or usb printers
[data.id] string | number ID of printer to find (Bluetooth: address, TCP: Use address + port instead, USB: deviceId)
[data.address] string If type is "tcp" then the IP Address of the printer
[data.port] number If type is "tcp" then the Port of the printer
[data.mmFeedPaper] numberoptional Millimeter distance feed paper at the end
[data.dotsFeedPaper] numberoptional Distance feed paper at the end
[data.printerDpi] numberoptional Printer DPI
[data.printerWidthMM] numberoptional Paper Width in mm
[data.printerNbrCharactersPerLine] numberoptional Number of characters per line
data.text string Formatted text to be printed
successCallback function Result on success
errorCallback function Result on failure

getEncoding(data, successCallback, errorCallback)

Get the printer encoding when available

Param Type Description
data Array.<Object> Data object
data.type "bluetooth" | "tcp" | "usb" List all bluetooth or usb printers
[data.id] string | number ID of printer to find (Bluetooth: address, TCP: Use address + port instead, USB: deviceId)
[data.address] string If type is "tcp" then the IP Address of the printer
[data.port] number If type is "tcp" then the Port of the printer
successCallback function Result on success
errorCallback function Result on failure

disconnectPrinter(data, successCallback, errorCallback)

Close the connection with the printer

Param Type Description
data Array.<Object> Data object
data.type "bluetooth" | "tcp" | "usb" List all bluetooth or usb printers
[data.id] string | number ID of printer to find (Bluetooth: address, TCP: Use address + port instead, USB: deviceId)
[data.address] string If type is "tcp" then the IP Address of the printer
[data.port] number If type is "tcp" then the Port of the printer
successCallback function Result on success
errorCallback function Result on failure

requestPermissions(data, successCallback, errorCallback)

Request permissions for USB printers

Param Type Description
data Array.<Object> Data object
data.type "bluetooth" | "tcp" | "usb" List all bluetooth or usb printers
[data.id] string | number ID of printer to find (Bluetooth: address, TCP: Use address + port instead, USB: deviceId)
[data.address] string If type is "tcp" then the IP Address of the printer
[data.port] number If type is "tcp" then the Port of the printer
successCallback function Result on success
errorCallback function Result on failure

requestBTPermissions(data, successCallback, errorCallback)

Request permissions for bluetooth

Param Type Description
data Array.<Object> Data object
data.type "bluetooth" List all bluetooth or usb printers
successCallback function Result on success
errorCallback function Result on failure

bitmapToHexadecimalString(data, successCallback, errorCallback)

Convert Drawable instance to a hexadecimal string of the image data

Param Type Description
data Array.<Object> Data object
data.type "bluetooth" | "tcp" | "usb" List all bluetooth or usb printers
[data.id] string | number ID of printer to find (Bluetooth: address, TCP: Use address + port instead, USB: deviceId)
[data.address] string If type is "tcp" then the IP Address of the printer
[data.port] number If type is "tcp" then the Port of the printer
[data.mmFeedPaper] numberoptional Millimeter distance feed paper at the end
[data.dotsFeedPaper] numberoptional Distance feed paper at the end
[data.printerDpi] numberoptional Printer DPI
[data.printerWidthMM] numberoptional Paper Width in mm
data.base64 string Base64 encoded picture string to convert
successCallback function Result on success
errorCallback function Result on failure

thermal-printer-cordova-plugin's People

Contributors

danielehrhardt avatar dantsu avatar iagorocha3112 avatar lacort avatar patrickbussmann avatar saaiful avatar

Stargazers

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

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

thermal-printer-cordova-plugin's Issues

Change Charset Encoding

Hi,

When I try to change charsetName from windows-1252 in ThermalPrinterCordovvaPlugin.java
charsetEncoding = new EscPosCharsetEncoding( charsetEncodingData.optString("charsetName","CP737"),charsetEncodingData.optInt("charsetId", 16));
(same applies for every other charsetName, always returns windows-1252)
The printer settings are setup to CP737 and are working properly when printing test-page.
Running getEncoding still returns windows-1252

Any ideas whay might causing this?

listPrinters is not defined

Hello, i using this plugin in my project use framework7-vue. Now i have an error= "listPrinters is not defined"
this is test code:
methods: {
login: function () {
listPrinters(
"bluetooth",
function (s) {
console.log("OK",s);
},
function (r) {
console.log("Err" + r);
}
);
},
}

ThermalPrinter.printFormattedText via bluetooth

I use the plugin to my Ionic / Angular App, the plugin seems to work, i can list the available devices.. etc. However, when i use the function ThermalPrinter.printFormattedText it console logs me that the print was successfull but my printer doesnt print. I use the LK-P30II bluetooth thermal printer.
Sample of my code
`print() {
let self = this;
window.ThermalPrinter.printFormattedText({
type: 'bluetooth',
id: 'my name', // You can also use the identifier directly i. e. 00:11:22:33:44:55 (address) or name
text: '[C]Hello World' // new lines with "\n"
}, function() {
console.log('Successfully printed!');
}, function(error: any) {
console.error('Printing error', error);
});

}`

App Crash whenever i call print function

Hello, thanks for the library but i haven't been able to make it work, i am printing with TCP.
I pass all necessary fields, but it keeps crashing but if i take out the ID property from the data object, i doesn't crash but i get an error telling me to pass the ID but when i do the app crashes.

[App crash only happens when i call the function]

function requestPermission() { var IPAddress = "192.168.1.240"; var port = 9100; console.log(IPAddress, port); if (ThermalPrinter.printFormattedText) { ThermalPrinter.printFormattedTextAndCut( { type: "tcp", id: "192.168.1.240:9100", // i have also tried "192.168.1.2409100 address: IPAddress, port: port, }, function (success) { console.log(success, "SUCCESS"); }, function (error) { console.log(error, "ERROR"); } ); } }

Thanks.

Added a logic that support a img size > 256 as well. also added some code to improve image quality

Hi! 👋

Firstly, thanks for your work on this project! 🙂

Today I used patch-package to patch [email protected] for the project I'm working on.

Here is the diff that solved my problem:

diff --git a/node_modules/thermal-printer-cordova-plugin/src/android/ThermalPrinterCordovaPlugin.java b/node_modules/thermal-printer-cordova-plugin/src/android/ThermalPrinterCordovaPlugin.java
index b2aa637..9dd25bb 100644
--- a/node_modules/thermal-printer-cordova-plugin/src/android/ThermalPrinterCordovaPlugin.java
+++ b/node_modules/thermal-printer-cordova-plugin/src/android/ThermalPrinterCordovaPlugin.java
@@ -80,9 +80,26 @@ public class ThermalPrinterCordovaPlugin extends CordovaPlugin {
     private void bytesToHexadecimalString(CallbackContext callbackContext, JSONObject data) throws JSONException {
         EscPosPrinter printer = this.getPrinter(callbackContext, data);
         try {
-            byte[] bytes = (byte[]) data.get("bytes");
+             byte[] bytes = (byte[]) data.get("bytes");
             Bitmap decodedByte = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
-            callbackContext.success(PrinterTextParserImg.bitmapToHexadecimalString(printer, decodedByte));
+            int targetWidth = 383;
+                    //(int) (201 * 5.6 / 2);
+            int targetHeight = (int) ((201 * 5.6 / 2.54) * 2);
+                    //Math.round(decodedByte.getHeight() * targetWidth / decodedByte.getWidth());
+
+            //(int) ((201 * 5.6 / 2.54) * 3)
+            Bitmap resizedBitmap = Bitmap.createScaledBitmap(decodedByte, targetWidth ,targetHeight , true);
+            decodedByte.recycle();
+
+            int width = resizedBitmap.getWidth(), height = resizedBitmap.getHeight();
+            StringBuilder textToPrint = new StringBuilder();
+            for(int y = 0; y < height; y += 256) {
+                Bitmap bitmap = Bitmap.createBitmap(resizedBitmap, 0, y, width, (y + 256 >= height) ? height - y : 256);
+                textToPrint.append("[C]<img>" + PrinterTextParserImg.bitmapToHexadecimalString(printer, bitmap) + "</img>\n");
+            }
+
+            textToPrint.append("[C]Printed!!!\n");
+            callbackContext.success(String.valueOf(textToPrint));
         } catch (Exception e) {
             callbackContext.error(new JSONObject(new HashMap<String, Object>() {{
                 put("error", e.getMessage());

This issue body was partially generated by patch-package.

Unable to Print Image Using bitmapToHexadecimalString()

I am facing an issue with my code where I am attempting to print an image on a thermal printer using the bitmapToHexadecimalString() function. However, the image is not being printed on the paper. I would appreciate any assistance in identifying and resolving the problem.

Here is the code I am using:

    ThermalPrinter.bitmapToHexadecimalString({
         type: 'bluetooth',
         id: '00:11:22:33:44:55',
         base64: base64txt
     }, function() {
         alert('Successfully printed!');
     }, function(error) {
         alert('Printing error: ' + error);
    });

Tried on capacitor 5 but does not work

Just tried on capacitor 5 but it does not work. SDK30&31 both does not work.
The error i see is the following:
image

tPrinter is declared and used as per sample on the main page:


`
import { Printer, ThermalPrinterPlugin } from 'thermal-printer-cordova-plugin/src';

declare let tPrinter: ThermalPrinterPlugin;

tPrinter.listPrinters({type: 'bluetooth'}, function(printers) {
        alert(printers);
        if (printers.length > 0) {
            var pr = printers[0] as Printer;
            tPrinter.requestPermissions({
                type: 'bluetooth',
                id: 'SPP-R400'
            }, function() {
                // Permission granted - We can print!
                tPrinter.printFormattedText({
                    type: 'bluetooth',
                    id: 4,
                    text: '[C]<u> Hello World</u>' // new lines with "\n"
                }, function() {
                    console.log('Successfully printed!');
                }, function(error) {
                    console.error('Printing error', error);
                });
            }, function(error) {
                alert('Permission');
                console.error('Permission denied - We can\'t print!');
            });
        } else {
            console.error('No printers found!');
        }
    }, function(error) {
        console.error('Ups, we cant list the printers!', error);
    });
`

Another problem is that when you install it from npm:
npm install thermal-printer-cordova-plugin it will install a version old 2 years so the package also on npmjs should be updated.

How To Trigger Open Cash Drawer ?

How To Trigger Kick Out Cash Drawer using Thermal printer connect with RJ11 cable to cashdrawer when After Printed??
using Bluetooth Connection..

ThermalPrinter.printFormattedText({
        type: 'bluetooth',
        id: 'first',
        mmFeedPaper:25,
        text: struk
}, function () {
});

i tried method printFormattedTextAndOpenCashBox(String text, float mmFeedPaper) but didnt work...
Thank you, i love this plugin..

ionic project build failure

hi is anyone using this package with ionic?

`
FAILURE: Build failed with an exception.

  • What went wrong:
    Could not determine the dependencies of task ':app:processDebugResources'.

Could not resolve all task dependencies for configuration ':app:debugRuntimeClasspath'.
Could not resolve com.github.DantSu:ESCPOS-ThermalPrinter-Android:2.0.8.
Required by:
project :app
project :app > project :capacitor-cordova-android-plugins
> Could not resolve com.github.DantSu:ESCPOS-ThermalPrinter-Android:2.0.8.
> Could not get resource 'https://dl.bintray.com/ionic-team/capacitor/com/github/DantSu/ESCPOS-ThermalPrinter-Android/2.0.8/ESCPOS-ThermalPrinter-Android-2.0.8.pom'.
> Could not HEAD 'https://dl.bintray.com/ionic-team/capacitor/com/github/DantSu/ESCPOS-ThermalPrinter-Android/2.0.8/ESCPOS-ThermalPrinter-Android-2.0.8.pom'. Received status code 502 from server: Bad Gateway

`

when print bitmap return function of success but nothing printed

i convert image to base64 then use it in bitmap function like :
ThermalPrinter.bitmapToHexadecimalString({
type: 'tcp',
address: '192.168.1.100',
port: 9100,
id: '192.168.1.100:9100', // Use an unique identifier for each printer i. e. address:port or name
base64:imageData
}, function () {
console.log('Successfully printed!');
}, function (error) {
console.error('Printing error', error);
});

TCP whole App Crashes

Thank you for this amazing library. I have decided to use the TCP, as USB was working well. Now the whole App crash and I cannot see what is wrong. I have spent so long time trying to read the logcat logs, but did not manage to find anaything.

I am using ionic framework with this library. Any help would be appreciated!

let port = 68;
let ip = '192.168.0.187';
let deviceId = ${ip}:${port};
await this.thermal.printFormattedTextAndCut({
type: "tcp",
address: ip,
port: port,
id: deviceId,
text: 'testing please',
mmFeedPaper: 20,
printerWidthMM: 80,
}).then(res => {
console.log(res);

}).catch(err => {
console.log(err);
});

( Ionic 6 ) ReferenceError: ThermalPrinter is not defined

Unable to trigger print on Ionic 6.

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { BarcodeScanner } from '@capacitor-community/barcode-scanner';
import { ThermalPrinterPlugin } from 'thermal-printer-cordova-plugin/src';

// eslint-disable-next-line @typescript-eslint/naming-convention, no-var
declare var ThermalPrinter: ThermalPrinterPlugin;

@Component({
  selector: 'app-folder',
  templateUrl: './folder.page.html',
  styleUrls: ['./folder.page.scss'],
})
export class FolderPage implements OnInit {
  public folder: string;
  devices = [];
  constructor(
    private activatedRoute: ActivatedRoute // private bluetoothSerial: BluetoothSerial
  ) {}

  printCatch() {
    try {
      console.log(ThermalPrinter || 'ee');
      this.print();
    } catch (error) {
      alert(error);
    }
  }
  print() {
    const formattedText =
      '[C]<u><font size="big">ORDER N°045</font></u>\n' +
      '[L]\n' +
      '[C]================================\n' +
      '[L]\n' +
      '[L]<b>BEAUTIFUL SHIRT</b>[R]9.99e\n' +
      '[L]  + Size : S\n' +
      '[L]\n' +
      '[L]<b>AWESOME HAT</b>[R]24.99e\n' +
      '[L]  + Size : 57/58\n' +
      '[L]\n' +
      '[C]--------------------------------\n' +
      '[R]TOTAL PRICE :[R]34.98e\n' +
      '[R]TAX :[R]4.23e\n' +
      '[L]\n' +
      '[C]================================\n' +
      '[L]\n' +
      '[L]Raymond DUPONT\n' +
      '[L]5 rue des girafes\n' +
      '[L]31547 PERPETES\n' +
      '[L]Tel : +33801201456\n';

    ThermalPrinter.listPrinters(
      { type: 'bluetooth' },
      (printers) => {
        if (printers.length > 0) {
          alert(printers);
        } else {
          alert('no printers;');
        }
      },
      (e) => alert(e)
    );
    ThermalPrinter.printFormattedText(
      {
        type: 'bluetooth',
        id: 'first', // You can also use the identifier directly i. e. 00:11:22:33:44:55 (address) or name
        text: formattedText,
      },
      () => {
        alert('Successfully printed!');
      },
      (error) => {
        alert(error);
      }
    );
  }
}

mmfeedpage and dotfeedpage not working

hello everyone, I tried to use this plugin but when I enter the mmfeedpage value and print it it doesn't make a difference.
my code

ThermalPrinter.printFormattedTextAndCut(
            {
              type: "bluetooth",
              id: container.activePrinter.address, // You can also use the identifier directly i. e. 00:11:22:33:44:55 (address) or name
              mmFeedPaper: 30,
              dotsFeedPaper: 30,
              // printerWidthMM: container.activeLaundry.printer_width_mm,
              text:
                "[C]<img>" +
                imgHex +
                "</img>\n\n" +
                "[C]<font size='big'>Nama Launndry</font>\n\n" + //nama laundry
                "[C]<font size='normal'>Jl. Dr. Saharjo No.55, RT.6/RW.1, Manggarai Sel., Kec. Tebet, Kota Jakarta Selatan, Daerah Khusus Ibukota Jakarta 12860</font>\n\n" + //alamat laundry
                "[C]<font size='normal'>Selamat Datang</font>\n\n" + //ucapan selamat datang
                "[L]<font size='normal'>Tanggal   : 12-04-2023</font>\n" +
                "[L]<font size='normal'>Order Id  : 1</font>\n" +
                "[L]<font size='normal'>Cashier   : Fabar</font>\n" +
                "[L]<font size='normal'>Cust      : Fabar</font>\n" +
                "[L]<font size='normal'>------------------------------</font>\n" +
                "[L]<font size='normal'>Cuci Karpet Meteran - Rose - 3 Hari x6 @20.000 Catatan : Baju Bagus Sekali dan wangi sekali</font>\n[R]<font size='normal'>120.000</font>\n" +
                "[L]<font size='normal'>------------------------------</font>\n" +
                "[L]<font size='normal'>Estimasi Selesai</font>\n" +
                "[L]<font size='normal'>12-04-2023 17:50</font>\n" +
                "[L]<font size='normal'>------------Delivery----------</font>\n" +
                "[L]<font size='normal'>--------------Lunas-----------</font>\n" +
                "[L]<font size='normal'>Subtotal</font>[R]<font size='normal'>120.000</font>\n" +
                "[L]<font size='normal'>Delivery</font>[R]<font size='normal'>10.000</font>\n" +
                "[L]<font size='normal'>Total</font>[R]<font size='normal'>10.000</font>\n" +
                "[L]<font size='normal'>Bayar</font>[R]<font size='normal'>10.000</font>\n" +
                "[R]<font size='normal'>Cash</font>\n" +
                "[L]<font size='normal'>Total</font>[R]<font size='normal'>10.000</font>\n" +
                "[L]<font size='normal'>Bayar</font>[R]<font size='normal'>10.000</font>\n" +
                "[L]<font size='normal'>------------------------------</font>\n" +
                "[L]<font size='normal'>Terima kasih sudah order</font>\n" +
                "[L]<font size='normal'>------------------------------</font>\n" +
                "[C]<qrcode size='30'>https://youtu.be/9vqrUKSb54c?t=194</qrcode>\n\n\n",
              // new lines with "\n"
            },
            function () {
              ("Successfully printed!");
            },
            function (error) {
              console.error("Printing error", error);
              alert(error);
            }
          );
      

is there any proble in my code ? thank you

how to reconnect printer before print?

how we can connect printer before print for avoiding connection reset and broken pipe issue like if there is any way to calling this private EscPosPrinter getPrinter(CallbackContext callbackContext, JSONObject data) i think problem will be solved

Drawer

Hey

How can i open the Cash-Drawer?

Missing permission for android.permission.DISABLE_KEYGUARD

Hi We have updates the ionic capacitor 4 app to maxSdkVersion 32. Now we are facing this error Missing permission for android.permission.DISABLE_KEYGUARD

As per the official document we need to change to this "If you want your device to be communicable with other devices, you must add BLUETOOTH_CONNECT permission."

So we have made the below changes in AndroidManifest.xml file but no use.

<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
<uses-permission android:maxSdkVersion="30" android:name="android.permission.BLUETOOTH" />

Print line Height

Hi all,

I have two different android devices with two different bluetooth printers.

I have different behaviours related with text text lone height.

See attached image please.

Is there any way to control this?

Thanks a lot.

image

I'll check soon but do you have example code so that I can fix it quicker than without?

I have the same problem, the console says that it is not defined. My example code so you can review. Maybe I'm not doing it right.

declare var ThermalPrinterCordovaPlugin: any;

@component({
selector: 'app-home',
templateUrl: 'home.page.html',
styleUrls: ['home.page.scss'],
})
export class HomePage {

constructor(
) {
const localPrinter = new ThermalPrinterCordovaPlugin();

var text =
"[L]\n" +
                "[C]<u><font size='big'>ORDER N°045</font></u>\n" +
                "[L]\n" +
                "[C]================================\n" +
                "[L]\n" +
                "[L]<b>BEAUTIFUL SHIRT</b>[R]9.99e\n" +
                "[L]  + Size : S\n" +
                "[L]\n" +
                "[L]<b>AWESOME HAT</b>[R]24.99e\n" +
                "[L]  + Size : 57/58\n" +
                "[L]\n" +
                "[C]--------------------------------\n" +
                "[R]TOTAL PRICE :[R]34.98e\n" +
                "[R]TAX :[R]4.23e\n" +
                "[L]\n" +
                "[C]================================\n" +
                "[L]\n" +
                "[L]<font size='tall'>Customer :</font>\n" +
                "[L]Raymond DUPONT\n" +
                "[L]5 rue des girafes\n" +
                "[L]31547 PERPETES\n" +
                "[L]Tel : +33801201456\n" +
                "[L]\n" +
                "[C]<barcode type='ean13' height='10'>831254784551</barcode>\n" +
                "[C]<qrcode size='20'>http://www.developpeur-web.dantsu.com/</qrcode>";

var data = {
  type: "tcp",
  id: '192.168.1.99:9100',
  address: '192.168.1.99',
  port: '9100',
  mmFeedPaper: '200',
  dotsFeedPaper: '20',
  text: text

};
localPrinter.printFormattedTextAndCut(data, function(){
  console.log( "IMPRESO CORRECTAMENTE");
}, function(){
  console.log( "EROORRRR AL IMPRIMIR");
})

}

}

And this is error in console
E/Capacitor/Console: File: http://localhost/vendor.js - Line 60755 - Msg: ERROR Error: Uncaught (in promise): ReferenceError: ThermalPrinterCordovaPlugin is not defined
ReferenceError: ThermalPrinterCordovaPlugin is not defined
at new HomePage (http://localhost/pages-home-home-module.js:128:30)
at NodeInjectorFactory.HomePage_Factory [as factory] (ng:///HomePage/ɵfac.js:4:10)
at getNodeInjectable (http://localhost/vendor.js:58141:44)
at instantiateRootComponent (http://localhost/vendor.js:64681:23)
at createRootComponent (http://localhost/vendor.js:66988:23)
at ComponentFactory$1.create (http://localhost/vendor.js:79631:25)
at ViewContainerRef.createComponent (http://localhost/vendor.js:77671:47)
at IonRouterOutlet.activateWith (http://localhost/vendor.js:49725:53)
at ActivateRoutes.activateRoutes (http://localhost/vendor.js:103923:40)
at http://localhost/vendor.js:103874:18

Update API 33

Please update lib to 3.3.0 and fix "Bluetooth compatibility API 33"
Currently having an error on Android 13

Change Font size

what can i do to change font size, i try with size='big-3' not working, only working if use size='big'. I try to update com.github.DantSu:ESCPOS-ThermalPrinter-Android:2.0.8 to com.github.DantSu:ESCPOS-ThermalPrinter-Android:3.2.1 but error in build gradle...

Cordova build crash on cordova android 10.0.1

Hi, i need some help here, i tried to build the app with the plugin, and the build failed with many lines of error saying there are duplicate classes. I am building this on android 10.0.1 targetSDKversion 30. Would this be anything to do with the androidX update? Because i tried to update the app onto playstore and the min target version is 30, which requires the android 10.0.1

Below is part of the build error.

  • What went wrong:
    Execution failed for task ':app:checkDebugDuplicateClasses'.

A failure occurred while executing com.android.build.gradle.internal.tasks.CheckDuplicatesRunnable
Duplicate class com.google.zxing.BarcodeFormat found in modules jetified-barcodescanner-release-2.1.5-runtime (:barcodescanner-release-2.1.5:) and jetified-core-3.4.0 (com.google.zxing:core:3.4.0)

Thanks!
Clark

How to use ESC/POS commands And getNbrCharactersPerLine() ,getPrinterWidthMM() , getPrinterDpi() and other method

hi patrickbussmann
i am using your paystory-de/thermal-printer-cordova-plugin
URL https://github.com/paystory-de/thermal-printer-cordova-plugin
i use all the function on document and all are work find
can you provide any document or any other link to
get getNbrCharactersPerLine() ,getPrinterWidthMM() , getPrinterDpi() and other method
how i get these thing in my application

and how i use ESC/POS commands (https://www.sparkag.com.br/wp-content/uploads/2016/06/ESC_POS-AK912-English-Command-Specifications-V1.4.pdf)

Image Printing Not Centered Properly

Hello Awesome Community!

I just wanted to know if there were any one else who is experiencing this issue?

When I use "[C]<img>IMAGE DATA</img> the image is printed allright, but is not centered properly.

It looks like the plugin takes the pivot from far left side and centers it instead of taking the pivot from the center of the image.
The image I am using is 350px, Square.

Anyone else experiencing this issue?

unmi V2 pro printing 'r' before actual receipt text

I am using a Sunmi V2 Pro device which has an integrated printer.

I am using your ESC POS library to print receipts and having the following issue.
Only on these sunmi devices, there is a preceding 'r' printed before the 1st character.

'ThermalPrinter' is not defined.

I'm using this plugin with capacitor, vuejs and vuetify and I can't call any method because it keeps saying 'ThermalPrinter' is undefined. Is there another way I could use it?

Printer images Fix width for 100% ?

Hi
Can i fix width 100% of paper,
It looks like with not fix when i try to change height
I try to fix the size of canves, width 1000px
height Auto(by the Image,)
But when print width not full of paper

Error when using with another plugin

Hello, I would like to congratulate you on the development of this excellent plugin. But I had a problem when I used the barcode-scanner plugin.
**Execution failed for task ':app:checkDebugDuplicateClasses'.
Do you suggest any kind of modification I can make?

Duplicate Class com.google.zxing

Duplicate class com.google.zxing.BarcodeFormat found in modules jetified-barcodescanner-release-2.1.5-runtime (:barcodescanner-release-2.1.5:) and jetified-core-3.4.0 (com.google.zxing:core:3.4.0)
     Duplicate class com.google.zxing.Binarizer found in modules jetified-barcodescanner-release-2.1.5-runtime (:barcodescanner-release-2.1.5:) and jetified-core-3.4.0 (com.google.zxing:core:3.4.0)
     Duplicate class com.google.zxing.BinaryBitmap found in modules jetified-barcodescanner-release-2.1.5-runtime (:barcodescanner-release-2.1.5:) and jetified-core-3.4.0 (com.google.zxing:core:3.4.0)
     Duplicate class com.google.zxing.ChecksumException found in modules jetified-barcodescanner-release-2.1.5-runtime (:barcodescanner-release-2.1.5:) and jetified-core-3.4.0 (com.google.zxing:core:3.4.0)
     Duplicate class com.google.zxing.DecodeHintType found in modules jetified-barcodescanner-release-2.1.5-runtime (:barcodescanner-release-2.1.5:) and jetified-core-3.4.0 (com.google.zxing:core:3.4.0)

I have a bunch of duplicate class errors, how do I solve this? I tried a lot of solutions online and I couldn't
like this in my build.gradle:

dependencies {
    configurations.all {
        exclude group: 'com.google.zxing'
    }
}

and I couldn't solve it, how do I fix when two cordova plugins is exporting same class ?

Other Printer by Mumbyn

Hello,

I am using the Mumbin ITPP 047 over TCP it works Fine.

Only the width oft the Paper is not correct! The Print is only about 2/3 of the width of the paper

Can you help me?

image printing issue

hi..
[C]" + PrinterTextParserImg.bitmapToHexadecimalString(printer, this.getApplicationContext().getResources().getDrawableForDensity(R.drawable.logo, DisplayMetrics.DENSITY_MEDIUM))+"\n"
ReferenceError: PrinterTextParserImg is not defined
this above code not working not getting or picking image and print can you please share some example of how to printer read the images

App closes at printer check with Ionic 6 (Android 12 & API 31)

private void requestUSBPermissions(CallbackContext callbackContext, JSONObject data) throws JSONException {

When the function requestUSBPermissions() is called in Android 12 - API 31 the app Crashes and close with the follow log:

E/AndroidRuntime: FATAL EXCEPTION: pool-3-thread-1
    Process: xxxx.xxxxx.xxxx, PID: 3490
    java.lang.IllegalArgumentException: com.nextqs.app: Targeting S+ (version 31 and above) requires that one of FLAG_IMMUTABLE or FLAG_MUTABLE be specified when creating a PendingIntent.
    Strongly consider using FLAG_IMMUTABLE, only use FLAG_MUTABLE if some functionality depends on the PendingIntent being mutable, e.g. if it needs to be used with inline replies or bubbles.
        at android.app.PendingIntent.checkFlags(PendingIntent.java:382)
        at android.app.PendingIntent.getBroadcastAsUser(PendingIntent.java:673)
        at android.app.PendingIntent.getBroadcast(PendingIntent.java:660)
        at de.paystory.thermal_printer.ThermalPrinterCordovaPlugin.requestUSBPermissions(ThermalPrinterCordovaPlugin.java:9😎
        at de.paystory.thermal_printer.ThermalPrinterCordovaPlugin.lambda$execute$0$de-paystory-thermal_printer-ThermalPrinterCordovaPlugin(ThermalPrinterCordovaPlugin.java:60)
        at de.paystory.thermal_printer.ThermalPrinterCordovaPlugin$$ExternalSyntheticLambda0.run(Unknown Source:😎
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
        at java.lang.Thread.run(Thread.java:920)


Application crashes when calling ThermalPrinter.requestPermissions

Here is my current code:

"use client"
import React, { useRef, useState } from "react"
import { Printer, ThermalPrinterPlugin } from "thermal-printer-cordova-plugin/src"
declare let ThermalPrinter: ThermalPrinterPlugin

export const PrintableOrder = ({ order }) => {
	const [usPrinters, setUsPrinters] = useState<Printer[]>([])

	const handlePrint = () => {
		const formattedText =
			'[C]<u><font size="big">ORDER N°045</font></u>\n' +
			"[L]\n" +
			"[C]================================\n" +
			"[L]\n" +
			"[L]<b>BEAUTIFUL SHIRT</b>[R]9.99e\n" +
			"[L]  + Size : S\n" +
			"[L]\n" +
			"[L]<b>AWESOME HAT</b>[R]24.99e\n" +
			"[L]  + Size : 57/58\n" +
			"[L]\n" +
			"[C]--------------------------------\n" +
			"[R]TOTAL PRICE :[R]34.98e\n" +
			"[R]TAX :[R]4.23e\n" +
			"[L]\n" +
			"[C]================================\n" +
			"[L]\n" +
			"[L]Raymond DUPONT\n" +
			"[L]5 rue des girafes\n" +
			"[L]31547 PERPETES\n" +
			"[L]Tel : +33801201456\n"

		ThermalPrinter.listPrinters(
			{ type: "bluetooth" },
			(printers) => {
				if (printers.length > 0) {
					setUsPrinters(printers)
					ThermalPrinter.requestPermissions(
						{ type: "bluetooth", id: printers[0].address ?? "SimulatePrinter" },
						function (result) {
							ThermalPrinter.printFormattedTextAndCut(
								{
									type: "bluetooth",
									id: printers[0].address ?? "SimulatePrinter",
									text: formattedText,
								},
								() => {
									alert("Successfully printed!")
								},
								(error) => {
									alert(error)
								}
							)
						},
						function (error) {
							console.log(error)
						}
					)
				} else {
					alert("no printers;")
				}
			},
			(e) => alert(e)
		)
	}

	return (
		<div>
			this is some kind of a test kekw :/
			<button
				style={{
					margin: "5px",
					border: "black",
					color: "yellow",
				}}
				onClick={handlePrint}
			>
				Print Order 1
			</button>
			<pre>{JSON.stringify(usPrinters, null, 2)}</pre>
		</div>
	)
}

here is error...

FATAL EXCEPTION: pool-7-thread-1
Process: rs.deliverko, PID: 3461
java.lang.ClassCastException: com.dantsu.escposprinter.connection.bluetooth.BluetoothConnection cannot be cast to com.dantsu.escposprinter.connection.usb.UsbConnection
at de.paystory.thermal_printer.ThermalPrinterCordovaPlugin.requestUSBPermissions(ThermalPrinterCordovaPlugin.java:96)
at de.paystory.thermal_printer.ThermalPrinterCordovaPlugin.lambda$execute$0$de-paystory-thermal_printer-ThermalPrinterCordovaPlugin(ThermalPrinterCordovaPlugin.java:60)
at de.paystory.thermal_printer.ThermalPrinterCordovaPlugin$$ExternalSyntheticLambda0.run(Unknown Source:8)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
at java.lang.Thread.run(Thread.java:764)

Any idea why?

I have permissions edited in my AndroidManifest.xml:


    <!-- Permissions -->
    <uses-feature android:name="android.hardware.usb.host" />
    <uses-permission android:maxSdkVersion="30" android:name="android.permission.BLUETOOTH" />
    <uses-permission android:maxSdkVersion="30" android:name="android.permission.BLUETOOTH_ADMIN" />
    <uses-permission android:name="android.permission.BLUETOOTH_PRIVILEGED"/>
    <uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
    <uses-permission android:name="android.permission.BLUETOOTH_SCAN" />
    
    <uses-permission android:name="android.permission.INTERNET" />

when running without requestPermissions I get :
java.io.IOException: Connection refused
2023-08-13 16:36:23.624 1277-1648 System.err rs.deliverko W at android.net.LocalSocketImpl.connectLocal(Native Method)
2023-08-13 16:36:23.624 1277-1648 System.err rs.deliverko W at android.net.LocalSocketImpl.connect(LocalSocketImpl.java:292)
2023-08-13 16:36:23.624 1277-1648 System.err rs.deliverko W at android.net.LocalSocket.connect(LocalSocket.java:145)
2023-08-13 16:36:23.624 1277-1648 System.err rs.deliverko W at android.bluetooth.BluetoothSocket.connect(BluetoothSocket.java:367)
2023-08-13 16:36:23.625 1277-1648 System.err rs.deliverko W at com.dantsu.escposprinter.connection.bluetooth.BluetoothConnection.connect(BluetoothConnection.java:66)
2023-08-13 16:36:23.625 1277-1648 System.err rs.deliverko W at com.dantsu.escposprinter.connection.bluetooth.BluetoothConnection.connect(BluetoothConnection.java:14)
2023-08-13 16:36:23.625 1277-1648 System.err rs.deliverko W at com.dantsu.escposprinter.EscPosPrinterCommands.connect(EscPosPrinterCommands.java:223)
2023-08-13 16:36:23.625 1277-1648 System.err rs.deliverko W at com.dantsu.escposprinter.EscPosPrinter.(EscPosPrinter.java:54)
2023-08-13 16:36:23.626 1277-1648 System.err rs.deliverko W at com.dantsu.escposprinter.EscPosPrinter.(EscPosPrinter.java:40)
2023-08-13 16:36:23.626 1277-1648 System.err rs.deliverko W at de.paystory.thermal_printer.ThermalPrinterCordovaPlugin.getPrinter(ThermalPrinterCordovaPlugin.java:316)
2023-08-13 16:36:23.626 1277-1648 System.err rs.deliverko W at de.paystory.thermal_printer.ThermalPrinterCordovaPlugin.printFormattedText(ThermalPrinterCordovaPlugin.java:197)
2023-08-13 16:36:23.626 1277-1648 System.err rs.deliverko W at de.paystory.thermal_printer.ThermalPrinterCordovaPlugin.lambda$execute$0$de-paystory-thermal_printer-ThermalPrinterCordovaPlugin(ThermalPrinterCordovaPlugin.java:54)
2023-08-13 16:36:23.627 1277-1648 System.err rs.deliverko W at de.paystory.thermal_printer.ThermalPrinterCordovaPlugin$$ExternalSyntheticLambda0.run(Unknown Source:8)
2023-08-13 16:36:23.627 1277-1648 System.err rs.deliverko W at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
2023-08-13 16:36:23.627 1277-1648 System.err rs.deliverko W at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
2023-08-13 16:36:23.628 1277-1648 System.err rs.deliverko W at java.lang.Thread.run(Thread.java:764)
2023-08-13 16:36:24.302 1277-1277 Choreographer rs.deliverko I Skipped 36 frames! The application may be doing too much work on its main thread.
2023-08-13 16:36:24.524 1277-1374 Adreno-EGL rs.deliverko W <qeglDrvAPI_eglGetConfigAttrib:612>: EGL_BAD_ATTRIBUTE
2023-08-13 16:36:26.251 1277-1374 Adreno-ES20 rs.deliverko W <core_glFinish:34>: glFinish skipped: 0
2023-08-13 16:36:26.262 1277-1374 Adreno-ES20 rs.deliverko W <core_glFinish:34>: glFinish skipped: 0
2023

Property 'id' does not exist on type 'Printer'.

printTicket(ticket:string) {
this.thermalPrinter.listPrinters({type: 'usb'}, (printers) => {
if (printers.length > 0) {
var ptr = printers[0];
this.thermalPrinter.printFormattedText({
type: 'usb',
id: ptr.id,
text: ticket // new lines with "\n"
}, function() {
console.log('Successfully printed!');
}, function(error) {
console.error('Printing error', error);
});
} else {
console.error('No printers found!');
}
}, function(error) {
console.error('Ups, we cant list the printers!', error);
});
}

ionic version 7.2.0
capacitor version 5.5.1
angular version 17.3.1

Vue.js + Capacitor project import issue

When I try to import it to my Vue js application I get this error. Is there an extra step that I am missing?

I am importing it like this
import { ThermalPrinterPlugin } from 'thermal-printer-cordova-plugin/src';

The error I get

`This dependency was not found:

  • thermal-printer-cordova-plugin/src in ./node_modules/cache-loader/dist/cjs.js??ref--13-0!./node_modules/babel-loader/lib!./node_modules/cache-loader/dist/cjs.js??ref--1-0!./node_modules/vue-loader-v16/dist??ref--1-1!./src/views/Dashboard.vue?vue&type=script&lang=js

To install it, you can run: npm install --save thermal-printer-cordova-plugin/src`

Printer Devices Suddenly Died

I got my printer device suddenly died after i tried to print over Bluetooth.
It show the message "successfully printed', but the devices is died just after i run the function.
Please help me to fix it

Target SDK 33 app is crashed.

I am using ionic 6
I selected target SDK 33 apps is crash.

pls, update the plugin library.

any other solution please help me.

noting printing in zebra printer

I used this plugin to connect zebra printer through Bluetooth but while clicking on the print it showing printing is successful but nothing is printing in thermal printer.
Can you please guide me what is wrong on the app
used this fuction only
printViaBluetooth(){
console.log('enter into 33 line')
ThermalPrinter.listPrinters({type: 'bluetooth'}, function(printers) {
console.log('enter into 35 line')
console.log('enter into 35 line')

         let printer = printers[0];
         console.log('enter into 39 line' + printer)
         console.log('enter into 40 line' + printer.address)
          // Permission granted - We can print!
          ThermalPrinter.printFormattedText({
              type: 'bluetooth',
              id: printer.address,
              text: '[C]<u><font size="big">Hello World</font></u>' // new lines with "\n"
          }, function() {
              console.log('Successfully printed!');
          }, function(error) {
              console.error('Printing error', error);
          });    
}, function(error) {
    console.error('Ups, we cant list the printers!', error);
});

}

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.