Printer Service

Printer service is a service which provides a simplified api for printer related operations. This document describes usage of the available printer functions.

Integration

v19.6 is deprecated. v20.0 contains major changes that will lock the main thread while printing long content. Please test it with long print content before using it.

  1. Copy most recent aar lib file into your project.

  2. Make sure you include aar lib in your Project. In this example project, it is done in /app/.build.gradle file like this:

dependencies {
    implementation fileTree(dir: "libs", include: ["*.jar", "*.aar"])
    ...
}

You can access example usage from example project.

Definitions

Line Width: Thermal printer has a fixed line width in pixels. It's 48x8, that is 384 pixels. It should be taken into consideration when using functions like drawLine, setCursorPosition, addTextToLine.

Cursor Position: Cursor position is the horizontal position where the text added by addText() function will be processed into line bitmap. It is incremented automatically.

LineSpacing: Vertical placement of the lines. If linespacing is 1, lines are spaced tightly, If linespacing is 1.5 there will be a half line sized gap between them etc. Line spacing cannot be less than 1.

Print Density: It is the setting that determines energy applied to thermal head. Inappropriate values of this setting may cause text to be too dark or indistinct. Note that use of energy also means battery drainage and heat generation. Here is a quote from original documentation of printer hardware:

Excessive energy may cause shortening the life of thermal head, or may cause the paper feed problem, so specify the accurate thermal paper selection and print density selection. When the using thermal paper is different from the one specified or the print density is other than 100%, the reliability of the product specification may not be satisfied. Verify the performance with your actual device before printing.

Functions

Function List

int printerStatus()

Returns error code or 0 if no error.

Possible errorcodes (as listed in PrinterErrorCode enumeration):

NO_ERROR (0),
VP_VOLTAGE_ERROR (-1),
VP_VOLTAGE_INITIALIZATION_ERROR (-2),
HEAD_TEMPERATURE_ERROR (-3),
FUSE_BLOWN_ERROR (-4),
OUT_OF_PAPER_ERROR (-5),
PAPER_SENSOR_ERROR (-6),
UNEXPECTED_FIELD_IDENTIFIER_ERROR (-7),
UNEXPECTED_RESPONSE_SIZE_ERROR (-8),
READ_TIMEOUT_ERROR (-9),
READ_WRITE_ERROR (-10),
CANNOT_OPEN_DEVICE_ERROR (-11),
OTHER_ERROR (-99),
DEAD_SERVICE (-101),
COULD_NOT_GET_STATUS (-102);

void setFontFace(int font)

Sets fonts face given the enumeration of it.

// Example
printerService.setFontFace(PrinterDefinitions.Font_E.SourceSansPro.ordinal());

void setFontSize(int fontSize)

Sets fontSize to given value. Minimum fontSize value is 8, maximum value is 144

Note that this function is not effective when a fixed size fonts is selected ( Bitmap array size fonts like "Basic Font 8x8").

void addTextToLine(String text, Alignment alignment)

Draws given string into line buffer, does not print bitmap automatically. Useful for creating lines that has different fonts and sizes within. Alignment enumertaion has following values

enum Alignment { Left, Center, Right };

If alignment Left is selected, text is added starting from cursor position. Otherwise cursor position is ignored and not incremented.

void printLine()

Prints buffer for current line.

void drawLine(int thickness, int verticalMargin, int horizontalMargin)

Draws and prints a horizontal line with given thickness and margins

thickness: Vertical thickness of the line in pixels verticalMargin: The empty space that will be left before and after line, in pixels horizontalMargin: The horizontal space (on left and right) to be left on the edges of the line

Horizontal margin should be a multiple of 8 or it will be rounded down.

void printText(String text)

Prints given text, it can be multiline and can contain tabs. Print is excuted immediately, does not require another command to start.

Text can also include styling commands like setFontFace, setFontSize. This enables user to send multiline and multi style text with a single transaction.

Styled text should start with tag "<s>". You can put styling codes into text yourself, or use StyledString class which provides functions and processes a member string to send. To see a full implementation and example usage of it, see the example project (All available functionality is commented in StyledString class).

void printBitmap(String name, int verticalMargin)

Prints a preloaded monochrome bitmap file

name: name of the preloaded monochrome bitmap file without .bmp extension verticalMargin: The empty space that will be left before and after bmp picture, in pixels

// Example
printerService.printBitmap("ykb", 0); // print ykb.bmp with no extra margin

//For Visa PayWave logos. "contactless32" and "contactless64".
StyledString styledText = new StyledString();
addTextToNewLine(styledText, "Visa PayWave", PrinterDefinitions.Alignment.Center);
styledText.printBitmap("contactless32", 0);
styledText.newLine();
styledText.addSpace(100);
styledText.print(PrinterService.getService(ctx));

void printBitmap(Context ctx, byte[] bitmapArray)

Prints given bitmap array

context: Android app context bitmapArray: Monochrome bitmap array to be printed

To make sure if your byte array is properly formatted bitmap, you can check it by BitmapChecker before printing:

if (BitmapChecker.isMonochromeBitmap(byteArray))
{
    printerService.printExternalBitmap(byteArray);
}

This function is available only if you are using StyledString markup.

Receipts using this function will be printed with a reduced printDensity. Output might look faded if you use thin fonts.

// Example
StyledString styledText = new StyledString();
styledText.printBitmap(ctx, bitmap);
styledText.addSpace(bottomMargin);
styledText.print(PrinterService.getService(ctx));

void printLogo(Context context, int verticalMargin)

Prints the logo of your app

context: Android app context verticalMargin: The empty space that will be left before and after the logo, in pixels

1) Add a drawable monochrome bmp file whose dimensions are 384 pixels (width) by H pixels (height, it can be any size). 2) Add the android:logo attribute to your AndroidManifest.xml that refers to your drawable file 3) Make sure that your app has the "app_name" meta-data that starts with "BNK"

// Example In AndroidManifest.xml
<manifest >
<application
...
android:logo="@drawable/my_bank_logo">
...
</application>
<meta-data android:name="app_name" android:value="BNK_000_TMPLT" />
</manifest>
// In source code
StyledString styledText = new StyledString();
styledText.printLogo(ctx, 0); // print your app's logo with no extra margin
styledText.print(PrinterService.getService(ctx));

void addSpace(int pixelHeight)

Leaves a blank space of given height in pixels. Takes effect immediately, not a buffered command.

void addEmptyLines(float lines)

Leaves a blank space of given height in lineHeights (1.5 lines, for example). Takes effect immediately, not a buffered command.

float lineSpacing()

Gets line spacing.

void setLineSpacing(float f)

Sets line spacing.

int printDensity()

Returns current print density. See definition of printer density.

void setPrintDensity(int density)

Sets print density. It can take values from 60 to 140 percent. Values out of this ranges are ignored. See definition of printer density.

void printExternalBitmap(byte[] bitmapArray)

Prints a monochrome bitmap file which is provided in byte array form.

byte array should be smaller than 300 KB and must be a monochrome bitmap format

To make sure if your byte array is properly formatted bitmap, you can check it by BitmapChecker before printing:

if (BitmapChecker.isMonochromeBitmap(byteArray))
{
    printerService.printExternalBitmap(byteArray);
}

Note: This function is suitable for printing small bitmaps like logos. If your bitmap exceeds a certain size (30kb for now), no bitmap will be printed. If you need a larger bitmap to be printed, use void printBitmap function instead.

void printQrCode(String text, ErrorCorrectionLevel correctionLvl, int verticalMargin)

Prints given text in Qr Code form.

text: Android app context correctionLvl: ErrorCorrection Level for Qr Code generation Process. verticalMargin: The empty space that will be left before and after Qr Code, in pixels.

correctionLvl and verticalMargin parameters is optional when this function is called via styled string method.

// Error Correction Level Options:
LOW  // The QR Code can tolerate about  7% erroneous codewords
MEDIUM  // The QR Code can tolerate about 15% erroneous codewords.
QUARTILE  // The QR Code can tolerate about 25% erroneous codewords
HIGH  // The QR Code can tolerate about 30% erroneous codewords

MEDIUM is the default and suggested version. High level of correction may result in bigger square code, which may cause each dot to be printed smaller, especially if text is long.

void finishPrintingProcedure()

Should be called at the end of each receipt. Cuts the paper or adds necessary space for manuel cutting (depends on device).

Fonts

PrinterService supports usage of different fonts and it is possible to add new fonts.

Definitions

Monospace Font: All characters represented with same width in these kind of fonts. Font size: How large the characters printed on a page are.

Font_24_Strike

It is a monospace font.

Font size is 12.

24 characters fit on a line.

Font_Bold_21

It is a monospace font.

Font size is 12.

21 characters fit on a line.

Font24

It is a monospace font.

Font size is 12.

24 characters fit on a line.

Font_Bold_24

It is a monospace font.

Font size is 12.

24 characters fit on a line.

Font_Condensed_42

It is a monospace font.

Font size is 12.

42 characters fit on a line.

Font_Condensed_48

It is a monospace font.

Font size is 12.

48 characters fit on a line.

Miscellaneous

Subscribing to 'Printer State Changed' Broadcast (Not Supported On 330TR)

In order to check printer status in a event listener style method, an application can subscribe to 'Printer State Changed' broadcast. This can be achieved by following steps:

  1. Create a BroadcastReceiver Class

public class PrinterBroadcastReceiver extends BroadcastReceiver {
    private static final String TAG = "PrinterBroadcastReceiver";
    @Override
    public void onReceive(Context context, Intent intent) {

        String errNoString = intent.getStringExtra("errNo") ;
        if(errNoString != null)
        {
            int errNo = Integer.parseInt(errNoString);
            // Use error no information here
        }

    }
}
  1. Subscribe to the Broadcast by create an Instance of the PrinterBroadcastReceiver class

This can be achieved by calling the following function in you mainActivity class:

private void subscribeToPrinterStatusBroadcast()
{
    BroadcastReceiver br = new PrinterBroadcastReceiver();
    IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
    filter.addAction("android.intent.action.PRINTER_STATUS_CHANGED");
    this.registerReceiver(br, filter);
}

Compatible Version Info:

330TR/400TR/1000TR:

AAR Ver.DetailDateOTA VersionBSP Ver.

v19.6

NatoSansMono font enum is added for 330TR.

27.03.2024

-

-

v20.0

Await print for long print content is added.

08.08.2024

-

-

Last updated