B4A Library SD EscPos Printer (Lan,USB, Bluetooth SPP, BLE)

This library allows you to print with thermal printers compatible with the ESC POS language in 4 different communication channels (USB, Bluetooth SPP, BLE, LAN)
you can download the ble3 library from here

The DEMO version prints one minute every 2. The full version of the library will be issued to those making a donation (Contact me in private before making a donation)

WARNING: Make sure the library meets all your needs, is compatible with the printer you need to use.

For ESC/POS B4J version see Here
For ESC/POS B4i version see Here
For ZEBRA printer see Here


Those who want a different version, such as LAN, USB, NFC please contact me privately.
OSBluetooth SPPBLE (Beacon)USB LAN / WIFI RS 232 NFC
Androidxxxx
iOsxx (on request)
Windowxx (on request)x (on request)

To print a PDF with ESC/POS see



SD_EscPosPrinter

Author:
Star-Dust
Version: 1.08
  • BLE_Printer
    • Events:
      • BLEoff
      • Connected (services As List)
      • Disconnected
      • ImageWriteComplete
      • PrinterFound (Name As String, ID As String)
      • StateChanged (msg As String)
      • WriteComplete (Characteristic As String, Success As Boolean)
    • Fields:
      • CharatteristicName As String
      • Charset As String
      • currentState As Int
      • ServiceName As String
    • Functions:
      • AddTab (ArrayTab As Int()) As String
        Add Tab
        eg. PrinterBLE.AddTab(Array As Byte(100,150,121))
      • Beep (Times As Byte, SecondsDurate As Byte) As String
        .Printer.Beep(1..9,1..9)
      • CenterJustify As String
        after this command calls SendBufferToPrinter
      • Class_Globals As String
      • Connect (ID As String) As String
      • Disconnect As String
      • Initialize (CallBack As Object, EventName As String) As String
        Initializes the object. You can add parameters to this method if needed.
      • InitializePrinter As String
      • IsInitialized As Boolean
        Verifica se l'oggetto sia stato inizializzato.
      • LeftJustify As String
        after this command calls SendBufferToPrinter
      • PrintBitmap (bmp As Bitmap)
      • RightJustify As String
        after this command calls SendBufferToPrinter
      • ScanPrinter As String
      • SetCodePage (Code As Byte) As String
        es. Printer.SetCodePage(06) for umlauts char
      • Write (Text As String) As String
        Write (Print) a Text
      • Write_ArrayByte (B As Byte()) As String
        Write (Send to Printer) a Array of Byte
        eg. PrinterBLE.Write_ArrayByte(Array As Byte(0x1D,150,23))
        eg. PrinterBLE.Write_ArrayByte("Text".GetBytes("UTF8"))
      • WriteBarCode (Code As String) As String
      • WriteBarCode2D (Code As String) As String
      • WriteLine (Text As String) As String
        Write (Print) a Text + CHLF
      • WriteList (list As List) As String
        Write (Print) a List
    • Properties:
      • CodeTable
        es. printer.setCodeTable(Encoding.Code_WPC1252)
        aftet this command calls SendBufferToPrinter
      • isConnect As Boolean [read only]
      • isScanning As Boolean [read only]
      • Spacing
        after setSpacing command calls SendBufferToPrinter
  • BT_Printer
    Note: AddPermission(android.permission.ACCESS_COARSE_LOCATION)
    • Events:
      • BluetoothIsDisabled
      • ConnectedToPrint (Success As Boolean)
      • DataReceived (Buffer() As Byte)
      • DisconnectToPrint (Mac As String)
      • DiscoveryComplete (Printers As Map)
      • DiscoveryFinished
      • DiscoveryNewPrinter (PrintedFound As Map, DeviceClass As Int)
      • DiscoveryNoDeviceFound
      • ErrorDiscovery
      • ListPrinterAssociated (ListNameAndMac As Map)
      • SendingError (Mac As String)
      • SendTerminated
    • Fields:
      • Charset As String
      • Const_AUDIO_VIDEO As Int
      • Const_COMPUTER As Int
      • Const_HEALTH As Int
      • Const_IMAGING As Int
      • Const_MISC As Int
      • Const_NETWORKING As Int
      • Const_PERIPHERAL As Int
      • Const_PHONE As Int
      • Const_TOY As Int
      • Const_UNCATEGORIZED As Int
      • Const_WEARABLE As Int
    • Functions:
      • AddBuffer_ArrayByte (B As Byte()) As String
      • AddBuffer_BarCode (Code As String) As String
      • AddBuffer_BarCode2D (Code As String) As String
      • AddBuffer_Bitmap (Bmp As Bitmap, ShiftLeft As Int) As String
      • AddBuffer_BitmapAlternativeCoding (Bmp As Bitmap) As String
      • AddBuffer_List_Write (list As List) As String
      • AddBuffer_List_WriteLine (list As List) As String
      • AddBuffer_Tab (ArrayTab As Int()) As String
      • AddBuffer_Write (Text As String) As String
      • AddBuffer_WriteLine (Text As String) As String
      • AddPrintDefineImage As String
      • Beep (Times As Byte, SecondsDurate As Byte) As String
        .Printer.Beep(1..9,1..9)
      • CenterJustify As String
        after this command calls SendBufferToPrinter
      • Class_Globals As String
      • ClearBuffer As String
      • Connected As Boolean
      • ConnectFromMac (Mac As String) As String
      • DefineImage (Image As Bitmap)
      • Disconnect As String
      • flushAllAndClose
      • Initialize (CallBack As Object, EventName As String) As String
        Initializes the object. You can add parameters to this method if needed.
      • InitializePrinter As String
      • IsInitialized As Boolean
        Verifica se l'oggetto sia stato inizializzato.
      • LeftJustify As String
        after this command calls SendBufferToPrinter
      • Preview As Bitmap
      • ResetPreViewWidth (NewWidth As Int) As String
      • RightJustify As String
        after this command calls SendBufferToPrinter
      • SearchFromAssociatedPrinter As String
      • SearchNewPrinter As String
        select --------------------------------------------
      • SendBufferToPrinter
      • SetCodePage (Code As Byte) As String
        es. Printer.SetCodePage(06) for umlauts char
      • WriteBarCode (Code As String) As String
        send to print immediately, do not preview - Not available in the demo version
      • WriteBarCode2D (Code As String) As String
        send to print immediately, do not preview - Not available in the demo version
      • WriteBitmap (Bmp As Bitmap) As String
        send to print immediately, do not preview - Not available in the demo version
      • WriteByte (Data As Byte()) As String
        send to print immediately, do not preview - Not available in the demo version
      • WriteText (Text As String) As String
        send to print immediately, do not preview - Not available in the demo version
    • Properties:
      • CodeTable
        es. printer.setCodeTable(Encoding.Code_WPC1252)
        aftet this command calls SendBufferToPrinter
      • Spacing
        after setSpacing command calls SendBufferToPrinter
  • ESC_POS
    Code module
    Subs in this code module will be accessible from all modules.
    • Fields:
      • BoldOff As String
      • BoldOn As String
      • cn_PDF417 As String
      • cn_QRcode As String
      • CutPaper As String
      • CutPartialPaper As String
      • CutTotalPaper As String
      • Demo As Boolean
      • DoubleOff As String
      • DoubleOn As String
      • FontA_Bold As String
      • FontA_DoubleHight As String
      • FontA_DoubleWide As String
      • FontA_DoubleWideHeight As String
      • FontA_Normal As String
      • FontB_Bold As String
      • FontB_DoubleHeight As String
      • FontB_DoubleWide As String
      • FontB_DoubleWideHeight As String
      • FontB_Normal As String
      • Horizzontal As String
      • InitializePrinter As String
      • ItalicFontOff As String
      • ItalicFontOn As String
      • NoUnderline As String
      • QueryErrorCauses As String
      • QueryOfflineCauses As String
      • QueryPaperStatus As String
      • QueryPrinterStatus As String
      • Underline1 As String
      • Underline2 As String
      • Vertical As String
    • Functions:
      • feed (lines As Int) As String
      • Process_Globals As String
  • Encoding
    Code module
    Subs in this code module will be accessible from all modules.
    • Fields:
      • CharSet_Chinese As String
      • CharSet_ChineseS As String
      • CharSet_DOS_Latin_1 As String
      • CharSet_IBM_PC As String
      • CharSet_ISO8859 As String
      • CharSet_UTF8 As String
      • CharSet_Windows1252 As String
      • Code_PC437 As Int
      • Code_PC850 As Int
      • Code_PC857 As Int
      • Code_PC858 As Int
      • Code_PC860 As Int
      • Code_PC863 As Int
      • Code_PC865 As Int
      • Code_PC866 As Int
      • Code_WPC1252 As Int
    • Functions:
      • Process_Globals As String
  • LAN_Printer
    • Events:
      • Connected (Success As Boolean)
      • DataReceived (Data() As Byte)
      • Diconnected
      • ErrorTrasmission
    • Fields:
      • Charset As String
    • Functions:
      • AddTab (ArrayTab As Int()) As String
        Add Tab
        eg. PrinterBLE.AddTab(Array As Byte(100,150,121))
      • Beep (Times As Byte, SecondsDurate As Byte) As String
        .Printer.Beep(1..9,1..9)
      • CenterJustify As String
        after this command calls SendBufferToPrinter
      • Class_Globals As String
      • Connect (Host As String, Port As Int) As String
      • Disconnect As String
      • Initialize (CallBack As Object, EventName As String) As String
        Initializes the object. You can add parameters to this method if needed.
      • InitializePrinter As String
      • IsInitialized As Boolean
        Verifica se l'oggetto sia stato inizializzato.
      • LanConnection_Connected (Successful As Boolean) As String
      • LeftJustify As String
        after this command calls SendBufferToPrinter
      • PrintBitmap (bmp As Bitmap) As String
      • RightJustify As String
        after this command calls SendBufferToPrinter
      • SetCodePage (Code As Byte) As String
        es. Printer.SetCodePage(06) for umlauts char
      • Write (Text As String) As String
        Write (Print) a Text
      • Write_ArrayByte (B As Byte()) As String
        Write (Send to Printer) a Array of Byte
        eg. PrinterBLE.Write_ArrayByte(Array As Byte(0x1D,150,23))
        eg. PrinterBLE.Write_ArrayByte("Text".GetBytes("UTF8"))
      • WriteBarCode (Code As String) As String
      • WriteBarCode2D (Code As String) As String
      • WriteLine (Text As String) As String
        Write (Print) a Text + CHLF
      • WriteList (list As List) As String
        Write (Print) a List
    • Properties:
      • CodeTable
        es. printer.setCodeTable(Encoding.Code_WPC1252)
        aftet this command calls SendBufferToPrinter
      • Spacing
        after setSpacing command calls SendBufferToPrinter
  • RS_Printer
    • Fields:
      • Charset As String
    • Functions:
      • AddTab (ArrayTab As Int()) As String
        Add Tab
        eg. PrinterBLE.AddTab(Array As Byte(100,150,121))
      • Beep (Times As Byte, SecondsDurate As Byte) As String
        .Printer.Beep(1..9,1..9)
      • CenterJustify As String
        after this command calls SendBufferToPrinter
      • Class_Globals As String
      • Connect (SerialDevOutput As String) As String
        es. Connect("/dev/ttyAMA1")
        es. Connect("/dev/ttyS0")
      • Disconnect As String
      • Initialize (CallBack As Object, EventName As String) As String
        Initializes the object. You can add parameters to this method if needed.
      • InitializePrinter As String
      • IsInitialized As Boolean
        Verifica se l'oggetto sia stato inizializzato.
      • LeftJustify As String
        after this command calls SendBufferToPrinter
      • PrintBitmap (bmp As Bitmap) As String
      • RightJustify As String
        after this command calls SendBufferToPrinter
      • SetCodePage (Code As Byte) As String
        es. Printer.SetCodePage(06) for umlauts char
      • Write (Text As String) As String
        Write (Print) a Text
      • Write_ArrayByte (B As Byte()) As String
        Write (Send to Printer) a Array of Byte
        eg. PrinterBLE.Write_ArrayByte(Array As Byte(0x1D,150,23))
        eg. PrinterBLE.Write_ArrayByte("Text".GetBytes("UTF8"))
      • WriteBarCode (Code As String) As String
      • WriteBarCode2D (Code As String) As String
      • WriteLine (Text As String) As String
        Write (Print) a Text + CHLF
      • WriteList (list As List) As String
        Write (Print) a List
    • Properties:
      • CodeTable
        es. printer.setCodeTable(Encoding.Code_WPC1252)
        aftet this command calls SendBufferToPrinter
      • Spacing
        after setSpacing command calls SendBufferToPrinter
  • USB_Printer
    • Events:
      • WriteComplete
    • Fields:
      • Charset As String
    • Functions:
      • AddTab (ArrayTab As Int()) As String
        Add Tab
        eg. PrinterBLE.AddTab(Array As Byte(100,150,121))
      • Beep (Times As Byte, SecondsDurate As Byte) As String
        .Printer.Beep(1..9,1..9)
      • CenterJustify As String
        after this command calls SendBufferToPrinter
      • Class_Globals As String
      • CloseConnection As String
      • FindAdbDevice As Boolean
      • HasPermission As Boolean
      • Initialize (CallBack As Object, EventName As String) As String
        Initializes the object. You can add parameters to this method if needed.
      • InitializePrinter As String
      • IsInitialized As Boolean
        Verifica se l'oggetto sia stato inizializzato.
      • LeftJustify As String
        after this command calls SendBufferToPrinter
      • OpenConnection As String
      • PrintBitmap (bmp As Bitmap) As String
      • RequestPermission As String
      • RightJustify As String
        after this command calls SendBufferToPrinter
      • SetCodePage (Code As Byte) As String
        es. Printer.SetCodePage(06) for umlauts char
      • Write (Text As String) As String
        Write (Print) a Text
      • Write_ArrayByte (D As Byte()) As String
        Write (Send to Printer) a Array of Byte
        eg. PrinterBLE.Write_ArrayByte(Array As Byte(0x1D,150,23))
        eg. PrinterBLE.Write_ArrayByte("Text".GetBytes("UTF8"))
      • WriteBarCode (Code As String) As String
      • WriteBarCode2D (Code As String) As String
      • WriteLine (Text As String) As String
        Write (Print) a Text + CHLF
      • WriteList (list As List) As String
        Write (Print) a List
    • Properties:
      • CodeTable
        es. printer.setCodeTable(Enoding.Code_WPC1252)
        aftet this command calls SendBufferToPrinter
      • Spacing
        after setSpacing command calls SendBufferToPrinter


log release
  • 1.04
    • Added CutPartialPaper, CutTotalPaper and feed(lines As Int) in esc_pos.
    • Added WriteBitmap WriteByte WriteText - send to print immediately
  • 1.05
    • Added conversions of color images to black and white for printing
  • 1.06
    • fixed LAN classbug
  • 1.07
    • Added Beep method
  • 1.08
    • Added WriteBarCode, WriteBarCode2D and for Printer_BT also added AddBarCode2d. Other commands to print 2D barcodes compatible with some POS ESCs
 

Attachments

  • SD_EscPosPrinter 1.08.zip
    47.3 KB · Views: 568
Last edited:

Star-Dust

Expert
Licensed User
Longtime User
Example

1661413619040.png



NB
Starting from SDK33 runtime permissions are required for accessing Bluetooth, see this link
 

Attachments

  • Sample1.zip
    12.6 KB · Views: 14
Last edited:

Star-Dust

Expert
Licensed User
Longtime User
Coding Documentation

BLE:
Sub Activity_Create(FirstTime As Boolean)
    Activity.LoadLayout("Layout1")
 
    Ble.Initialize(Me,"Ble")
End Sub

Private Sub ButtonScan_Click
    Ble.ScanPrinter
End Sub

Private Sub Ble_PrinterFound(Name As String, ID As String)
    NamePrinter=Name
    Log($"Found device: ${NamePrinter} ${CRLF}(${ID})"$)
    Ble.connect(ID)
End Sub

Private Sub Ble_Connected(services As List)
    Log(NamePrinter}
End Sub

Private Sub ButtonSend_Click
    Ble.InitializePrinter
    Ble.RightJustify
    Ble.Writeline(ESC_POS.DoubleOn & "RIGHT PRINT" & ESC_POS.DoubleOff)
    Ble.PrintBitmap(LoadBitmap(File.DirAssets,"qr.jpg"))
End Sub


USB:
Dim USBp As USB_Printer
    USBp.Initialize(Me,"USB")
 
    If USBp.FindAdbDevice Then
        If USBp.HasPermission=False Then
            USBp.RequestPermission
            Wait For Activity_Resume ' Change for B4XPage
        End If
        USBp.OpenConnection
        USBp.WriteLine("TEXT")
        USBp.Writeline(ESC_POS.DoubleOn & "TEXT" & ESC_POS.DoubleOff)
        USBp.CloseConnection
    End If

Bluetooth SPP:
Sub Globals
    Dim rp As RuntimePermissions
    Dim Printer As BT_Printer
End Sub

Sub Activity_Create(FirstTime As Boolean)
    'Do not forget to load the layout file created with the visual designer. For example:
    Activity.LoadLayout("Layout1")
   
    Printer.Initialize(Me,"Printer")
    Ble.Initialize(Me,"Ble")
End Sub

Sub ButtonScanPrinter_Click
    ' Scan for find Bluetooth Printer
    rp.CheckAndRequest(rp.PERMISSION_ACCESS_COARSE_LOCATION)
'   Change for B4XPage
    Wait For Activity_PermissionResult (Permission As String, Result As Boolean)
    If Result = False Then
        ToastMessageShow("No permission...", False)
        Return
    End If
    Printer.SearchNewPrinter
End Sub


Sub Printer_DiscoveryNewPrinter (PrinterFinded As Map, DeviceClass As Int)
    ' Find new printer
     Log(PrinterFinded.GetKeyAt(0)) ' Printer Name
     Printer.ConnectFromMac(PrinterFinded.GetValueAt(0)) ' Printer Mac
End Sub


Sub Printer_ConnectedToPrint (Success As Boolean)
    ' When is connect
    If Success Then
        Printer.ClearBuffer
       Printer.RightJustify
       Printer.AddBuffer_Writeline("TEST - Mixed Text and Image")
       Printer.SendBufferToPrinter
    Else
        ToastMessageShow("Error Connect in to BT PRINTER",False)
    End If
End Sub


LAN:
Dim Plan As LAN_Printer
Plan.Initialize(Me,"Plan")

Private Sub Plan_Connected(Success As Boolean)
    Plan.Connect(Host,Port)
    
    Plan.LeftJustify
    Plan.Write("Hallo")
    
    Plan.Disconnect
End Sub
 
Last edited:

Xfood

Expert
Licensed User
have you finally decided to implement everything? good boy

the serial is missing .. ;-)

and so it will be truly complete
 

Unobtainius

Active Member
Licensed User
Longtime User
Thanks you @Star-Dust. Your contribution level has far exceeded extraordinary
 

Hamied Abou Hulaikah

Well-Known Member
Licensed User
Longtime User
USB tested but no image printed!
B4X:
                U_Printer.OpenConnection
                U_Printer.PrintBitmap(LoadBitmap(File.DirAssets,"qr.jpg"))
                U_Printer.CloseConnection

Also in usb text test, I added paper cut command, it cut the page BEFORE text printed!
B4X:
                U_Printer.OpenConnection
                U_Printer.WriteLine("HALLO MY FRIENT")
                U_Printer.Writeline(ESC_POS.DoubleOn & "TEST OF TEXT" & ESC_POS.DoubleOff)
                Dim PrintBuffer =Chr(29) & Chr(86) & Chr(48)  'Full cut               
                U_Printer.WriteLine(PrintBuffer)
                U_Printer.CloseConnection
 

Star-Dust

Expert
Licensed User
Longtime User
Hi @HaH ,

The demo version has disabled the printing of the images, the barcode and the raw sending of Bytes.
 

Star-Dust

Expert
Licensed User
Longtime User
As far as the paper cutting is concerned, it does not seem to depend on the library that sends commands directly to the printer without caching.

I can suggest you to put a sleep(100) before the cut to give time to print the text before the cut
 

Star-Dust

Expert
Licensed User
Longtime User
Try this
B4X:
U_Printer.OpenConnection
U_Printer.WriteLine("HALLO MY FRIENT")
U_Printer.Writeline(ESC_POS.DoubleOn & "TEST OF TEXT" & ESC_POS.DoubleOff)
U_Printer.CloseConnection
Sleep(200)
U_Printer.OpenConnection
Dim PrintBuffer =Chr(29) & Chr(86) & Chr(48)  'Full cut              
U_Printer.WriteLine(PrintBuffer)
U_Printer.CloseConnection
 

Hamied Abou Hulaikah

Well-Known Member
Licensed User
Longtime User
Try this
B4X:
U_Printer.OpenConnection
U_Printer.WriteLine("HALLO MY FRIENT")
U_Printer.Writeline(ESC_POS.DoubleOn & "TEST OF TEXT" & ESC_POS.DoubleOff)
U_Printer.CloseConnection
Sleep(200)
U_Printer.OpenConnection
Dim PrintBuffer =Chr(29) & Chr(86) & Chr(48)  'Full cut             
U_Printer.WriteLine(PrintBuffer)
U_Printer.CloseConnection
not solved!
it still cut then print!
 

Star-Dust

Expert
Licensed User
Longtime User
It's a strange thing, but I'm sure it doesn't depend on the library. Kindly write down the brand and model of the printer so that I can read up on it
 

Hamied Abou Hulaikah

Well-Known Member
Licensed User
Longtime User
Try this
B4X:
U_Printer.OpenConnection
U_Printer.WriteLine("HALLO MY FRIENT")
U_Printer.Writeline(ESC_POS.DoubleOn & "TEST OF TEXT" & ESC_POS.DoubleOff)
U_Printer.CloseConnection
Sleep(200)
U_Printer.OpenConnection
Dim PrintBuffer =Chr(29) & Chr(86) & Chr(48)  'Full cut             
U_Printer.WriteLine(PrintBuffer)
U_Printer.CloseConnection
I increased the time to 1000ms
the cut occurred between two lines.
If we depend on timing, a lot of cutting errors will happen, because some print jobs are short and others are long!
My suggestion: I think timing is the problem, so you should create additional parameter (cut as Boolean) in closeconnection method for example, so if cut parameter is true, then you put it inside last print job finished then send it and close.
 

Attachments

  • WhatsApp Image 2022-08-27 at 5.10.12 PM.jpeg
    WhatsApp Image 2022-08-27 at 5.10.12 PM.jpeg
    13.7 KB · Views: 412
  • WhatsApp Image 2022-08-27 at 5.10.53 PM.jpeg
    WhatsApp Image 2022-08-27 at 5.10.53 PM.jpeg
    21.2 KB · Views: 406

jahswant

Well-Known Member
Licensed User
Longtime User
You should send 1 or 2 empty line feeds to the printer in order to solve this issue. I don’t remember the commands but you can send 2 empty WriteLine.
 

jahswant

Well-Known Member
Licensed User
Longtime User
Send the line before cutting. I have that same printer and that method works well on my end.
 

Hamied Abou Hulaikah

Well-Known Member
Licensed User
Longtime User
Send the line before cutting. I have that same printer and that method works well on my end.
I tried your approach, every empty line sent means delay some milliseconds, in practice we don't know how much times (i.e empty lines here).
if you print a lot of lines, writing two or more empty lines is not enough.
We need a practical approach.
 

jahswant

Well-Known Member
Licensed User
Longtime User
When I reach home I will send you a code for empty line feeds it should work correctly.
B4X:
    SendMsg = SendMsg & Chr(13) & Chr(10)
    SendMsg = SendMsg & Chr(13) & Chr(10)
    SendMsg = SendMsg & Chr(13) & Chr(10)
    SendMsg = SendMsg & Chr(13) & Chr(10)
    SendMsg = SendMsg & Chr(13) & Chr(10)
    SendMsg = SendMsg & Chr(13) & Chr(10)
    SendMsg = SendMsg & Chr(13) & Chr(10)
    SendMsg = SendMsg & Chr(13) & Chr(10)
    SendMsg = SendMsg &  Chr(27) & "i" & CRLF

This is the code I use to send empty line feed to the printer and cut the paper. Reduce according to your needs.
 
Top