android设备连接USB打印机的打印方法

找了各方资料,自己写了一个USBPrinter类,代码如下:

public class USBPrinter {
    public static final String ACTION_USB_PERMISSION = "com.usb.printer.USB_PERMISSION";

    private static USBPrinter mInstance;

    private Context mContext;
    private PendingIntent mPermissionIntent;
    private UsbManager mUsbManager;
    private UsbDeviceConnection mUsbDeviceConnection;

    private UsbEndpoint ep,printerEp;
    private UsbInterface usbInterface;

    private static final int TIME_OUT = 100000;

    public static USBPrinter getInstance() {
        if (mInstance == null) {
            synchronized (USBPrinter.class) {
                if (mInstance == null) {
                    mInstance = new USBPrinter();
                }
            }
        }
        return mInstance;
    }

    /**
     * 初始化打印机,需要与destroy对应
     *
     * @param context 上下文
     */
    public static void initPrinter(Context context) {
        getInstance().init(context);
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private void init(Context context) {
//        list.clear();
        mContext = context;
        mUsbManager = (UsbManager) mContext.getSystemService(Context.USB_SERVICE);
        mPermissionIntent = PendingIntent.getBroadcast(mContext, 0, new Intent(ACTION_USB_PERMISSION), 0);
        IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
        filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
        filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
        mContext.registerReceiver(mUsbDeviceReceiver, filter);

        // 列出所有的USB设备,并且都请求获取USB权限
        HashMap deviceList = mUsbManager.getDeviceList();

        for (UsbDevice device : deviceList.values()) {
            usbInterface = device.getInterface(0);
            if (usbInterface.getInterfaceClass() == 7) {
                Log.d("device", device.getProductName() + "     " + device.getManufacturerName());
                Log.d("device", device.getVendorId() + "     " + device.getProductId() + "      " + device.getDeviceId());
                Log.d("device", usbInterface.getInterfaceClass() + "");
                if (!mUsbManager.hasPermission(device)) {
                    mUsbManager.requestPermission(device, mPermissionIntent);
                }else {
                    connectUsbPrinter(device);
                }
            }
        }

    }

    private final BroadcastReceiver mUsbDeviceReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            Log.d("action", action);
            UsbDevice mUsbDevice = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
            if (ACTION_USB_PERMISSION.equals(action)) {
                synchronized (this) {
                    if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false) && mUsbDevice != null) {
                        Log.d("receiver", action);
                        connectUsbPrinter(mUsbDevice);
                    } else {
                        ToastUtil.showShort(context, "USB设备请求被拒绝");
                    }
                }
            } else if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) {
                if (mUsbDevice != null) {
                    ToastUtil.showShort(context, "有设备拔出");
                }
            } else if (UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(action)) {
                ToastUtil.showShort(context, "有设备插入");
                if (mUsbDevice != null) {
                    if (!mUsbManager.hasPermission(mUsbDevice)) {
                        mUsbManager.requestPermission(mUsbDevice, mPermissionIntent);
                    }
                }
            }
        }
    };

    public void close() {
        if(mUsbDeviceConnection != null){
            mUsbDeviceConnection.close();
            mUsbDeviceConnection = null;
        }
        mContext.unregisterReceiver(mUsbDeviceReceiver);
        mContext = null;
        mUsbManager = null;
    }

    private void connectUsbPrinter(UsbDevice mUsbDevice) {
        if (mUsbDevice != null) {
            for (int i = 0; i < usbInterface.getEndpointCount(); i++) {
                ep = usbInterface.getEndpoint(i);
                if (ep.getType() == UsbConstants.USB_ENDPOINT_XFER_BULK) {
                    if (ep.getDirection() == UsbConstants.USB_DIR_OUT) {
                        mUsbDeviceConnection = mUsbManager.openDevice(mUsbDevice);
                        printerEp = ep;
                        if (mUsbDeviceConnection != null) {
                            ToastUtil.showShort(mContext, "设备已连接");
                            mUsbDeviceConnection.claimInterface(usbInterface, true);
                            mUsbDeviceConnection.releaseInterface(usbInterface);
                        }
                    }
                }
            }
        } else {
            ToastUtil.showShort(mContext, "未发现可用的打印机");

        }
    }

    private void write(byte[] bytes) {
        if (mUsbDeviceConnection != null) {
            int b = mUsbDeviceConnection.bulkTransfer(printerEp, bytes, bytes.length, TIME_OUT);
            Log.i("Return Status", "b-->" + b);
        } else {
            Looper.prepare();
            handler.sendEmptyMessage(0);
            Looper.loop();
        }
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            ToastUtil.showShort(mContext, "未发现可用的打印机");
        }
    };

    /**
     * 打印文字
     * @param msg
     */
    public void printText(String msg) {
        byte[] bytes = new byte[0];
        try {
            bytes = msg.getBytes("gbk");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        write(bytes);
    }

    /**
     * 换行打印文字
     * @param msg
     */
    public void printTextNewLine(String msg) {
        byte[] bytes = new byte[0];
        try {
            bytes = msg.getBytes("gbk");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        write(new String("\n").getBytes());
        write(bytes);
    }

    /**
     * 打印空行
     * @param size
     */
    public void printLine(int size) {
        for (int i = 0; i < size; i++) {
            printText("\n");
        }
    }

    /**
     * 设置字体大小
     * @param size 0:正常大小 1:两倍高 2:两倍宽 3:两倍大小 4:三倍高 5:三倍宽 6:三倍大 7:四倍高 8:四倍宽 9:四倍大小 10:五倍高 11:五倍宽 12:五倍大小
     */
    public void setTextSize(int size) {
        write(ESCUtil.setTextSize(size));
    }

    /**
     * 字体加粗
     * @param isBold
     */
    public void bold(boolean isBold) {
        if (isBold) write(ESCUtil.boldOn());
        else write(ESCUtil.boldOff());
    }

    /**
     * 打印一维条形码
     * @param data
     */
    public void printBarCode(String data) {
        write(ESCUtil.getPrintBarCode(data, 5, 90, 5, 2));
    }

    /**
     * 设置对齐方式
     * @param position
     */
    public void setAlign(int position) {
        byte[] bytes = null;
        switch (position) {
            case 0:
                bytes = ESCUtil.alignLeft();
                break;
            case 1:
                bytes = ESCUtil.alignCenter();
                break;
            case 2:
                bytes = ESCUtil.alignRight();
                break;
        }
        write(bytes);
    }

    /**
     * 切纸
     */
    public void cutPager() {
        write(ESCUtil.cutter());
    }

}

请自行替换代码里的ToastUtil
里面的ESCUtil是ESC指令工具类,代码如下:

//常用指令封装
public class ESCUtil {

    public static final byte ESC = 0x1B;// Escape
    public static final byte FS =  0x1C;// Text delimiter
    public static final byte GS =  0x1D;// Group separator
    public static final byte DLE = 0x10;// data link escape
    public static final byte EOT = 0x04;// End of transmission
    public static final byte ENQ = 0x05;// Enquiry character
    public static final byte SP =  0x20;// Spaces
    public static final byte HT =  0x09;// Horizontal list
    public static final byte LF =  0x0A;//Print and wrap (horizontal orientation)
    public static final byte CR =  0x0D;// Home key
    public static final byte FF =  0x0C;// Carriage control (print and return to the standard mode (in page mode))
    public static final byte CAN = 0x18;// Canceled (cancel print data in page mode)

    //初始化打印机
    public static byte[] init_printer() {
        byte[] result = new byte[2];
        result[0] = ESC;
        result[1] = 0x40;
        return result;
    }

    //打印浓度指令
    public static byte[] setPrinterDarkness(int value){
        byte[] result = new byte[9];
        result[0] = GS;
        result[1] = 40;
        result[2] = 69;
        result[3] = 4;
        result[4] = 0;
        result[5] = 5;
        result[6] = 5;
        result[7] = (byte) (value >> 8);
        result[8] = (byte) value;
        return result;
    }

    /**
     * 打印单个二维码 sunmi自定义指令
     * @param code:         二维码数据
     * @param modulesize:   二维码块大小(单位:点, 取值 1 至 16 )
     * @param errorlevel:   二维码纠错等级(0 至 3)
     *                0 -- 纠错级别L ( 7%)
     *                1 -- 纠错级别M (15%)
     *                2 -- 纠错级别Q (25%)
     *                3 -- 纠错级别H (30%)
     */
    public static byte[] getPrintQRCode(String code, int modulesize, int errorlevel){
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        try{
            buffer.write(setQRCodeSize(modulesize));
            buffer.write(setQRCodeErrorLevel(errorlevel));
            buffer.write(getQCodeBytes(code));
            buffer.write(getBytesForPrintQRCode(true));
        }catch(Exception e){
            e.printStackTrace();
        }
        return buffer.toByteArray();
    }

    /**
     * 横向两个二维码 sunmi自定义指令
     * @param code1:            二维码数据
     * @param code2:            二维码数据
     * @param modulesize:   二维码块大小(单位:点, 取值 1 至 16 )
     * @param errorlevel:   二维码纠错等级(0 至 3)
     *                0 -- 纠错级别L ( 7%)
     *                1 -- 纠错级别M (15%)
     *                2 -- 纠错级别Q (25%)
     *                3 -- 纠错级别H (30%)
     */
    public static byte[] getPrintDoubleQRCode(String code1, String code2, int modulesize, int errorlevel){
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        try{
            buffer.write(setQRCodeSize(modulesize));
            buffer.write(setQRCodeErrorLevel(errorlevel));
            buffer.write(getQCodeBytes(code1));
            buffer.write(getBytesForPrintQRCode(false));
            buffer.write(getQCodeBytes(code2));

            //加入横向间隔
            buffer.write(new byte[]{0x1B, 0x5C, 0x18, 0x00});

            buffer.write(getBytesForPrintQRCode(true));
        }catch(Exception e){
            e.printStackTrace();
        }
        return buffer.toByteArray();
    }

    /**
     * 光栅打印二维码
     */
    public static byte[] getPrintQRCode2(String data, int size){
        byte[] bytes1  = new byte[4];
        bytes1[0] = GS;
        bytes1[1] = 0x76;
        bytes1[2] = 0x30;
        bytes1[3] = 0x00;

        byte[] bytes2 = BytesUtil.getZXingQRCode(data, size);
        return BytesUtil.byteMerger(bytes1, bytes2);
    }

    /**
     * 打印一维条形码
     */
    public static byte[] getPrintBarCode(String data, int symbology, int height, int width, int textposition){
        if(symbology < 0 || symbology > 10){
            return new byte[]{LF};
        }

        if(width < 2 || width > 6){
            width = 2;
        }

        if(textposition <0 || textposition > 3){
            textposition = 0;
        }

        if(height < 1 || height>255){
            height = 162;
        }

        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        try{
            buffer.write(new byte[]{0x1D,0x66,0x01,0x1D,0x48,(byte)textposition,
                    0x1D,0x77,(byte)width,0x1D,0x68,(byte)height,0x0A});

            byte[] barcode;
            if(symbology == 10){
                barcode = BytesUtil.getBytesFromDecString(data);
            }else{
                barcode = data.getBytes("GB18030");
            }

            if(symbology > 7){
                buffer.write(new byte[]{0x1D,0x6B,0x49,(byte)(barcode.length+2),0x7B, (byte) (0x41+symbology-8)});
            }else{
                buffer.write(new byte[]{0x1D,0x6B,(byte)(symbology + 0x41),(byte)barcode.length});
            }
            buffer.write(barcode);
        }catch(Exception e){
            e.printStackTrace();
        }
        return buffer.toByteArray();
    }


    //光栅位图打印
    public static byte[] printBitmap(Bitmap bitmap){
        byte[] bytes1  = new byte[4];
        bytes1[0] = GS;
        bytes1[1] = 0x76;
        bytes1[2] = 0x30;
        bytes1[3] = 0x00;

        byte[] bytes2 = BytesUtil.getBytesFromBitMap(bitmap);
        return BytesUtil.byteMerger(bytes1, bytes2);
    }

    //光栅位图打印 设置mode
    public static byte[] printBitmap(Bitmap bitmap, int mode){
        byte[] bytes1  = new byte[4];
        bytes1[0] = GS;
        bytes1[1] = 0x76;
        bytes1[2] = 0x30;
        bytes1[3] = (byte) mode;

        byte[] bytes2 = BytesUtil.getBytesFromBitMap(bitmap);
        return BytesUtil.byteMerger(bytes1, bytes2);
    }

    //光栅位图打印
    public static byte[] printBitmap(byte[] bytes){
        byte[] bytes1  = new byte[4];
        bytes1[0] = GS;
        bytes1[1] = 0x76;
        bytes1[2] = 0x30;
        bytes1[3] = 0x00;

        return BytesUtil.byteMerger(bytes1, bytes);
    }


    /*
    *   选择位图指令 设置mode
    *   需要设置1B 33 00将行间距设为0
     */
    public static byte[] selectBitmap(Bitmap bitmap, int mode){
        return BytesUtil.byteMerger(BytesUtil.byteMerger(new byte[]{0x1B, 0x33, 0x00}, BytesUtil.getBytesFromBitMap(bitmap, mode)), new byte[]{0x0A, 0x1B, 0x32});
    }

    /**
     * 跳指定行数
     */
    public static byte[] nextLine(int lineNum) {
        byte[] result = new byte[lineNum];
        for (int i = 0; i < lineNum; i++) {
            result[i] = LF;
        }

        return result;
    }

    // ------------------------underline-----------------------------
    //设置下划线1点
    public static byte[] underlineWithOneDotWidthOn() {
        byte[] result = new byte[3];
        result[0] = ESC;
        result[1] = 45;
        result[2] = 1;
        return result;
    }

    //设置下划线2点
    public static byte[] underlineWithTwoDotWidthOn() {
        byte[] result = new byte[3];
        result[0] = ESC;
        result[1] = 45;
        result[2] = 2;
        return result;
    }

    //取消下划线
    public static byte[] underlineOff() {
        byte[] result = new byte[3];
        result[0] = ESC;
        result[1] = 45;
        result[2] = 0;
        return result;
    }

    // ------------------------bold-----------------------------
    /**
     * 字体加粗
     */
    public static byte[] boldOn() {
        byte[] result = new byte[3];
        result[0] = ESC;
        result[1] = 69;
        result[2] = 0xF;
        return result;
    }

    /**
     * 取消字体加粗
     */
    public static byte[] boldOff() {
        byte[] result = new byte[3];
        result[0] = ESC;
        result[1] = 69;
        result[2] = 0;
        return result;
    }

    // ------------------------character-----------------------------
    /*
    *单字节模式开启
     */
    public static byte[] singleByte(){
        byte[] result = new byte[2];
        result[0] = FS;
        result[1] = 0x2E;
        return result;
    }

    /*
    *单字节模式关闭
    */
    public static byte[] singleByteOff(){
        byte[] result = new byte[2];
        result[0] = FS;
        result[1] = 0x26;
        return result;
    }

    /**
     * 设置单字节字符集
     */
    public static byte[] setCodeSystemSingle(byte charset){
        byte[] result = new byte[3];
        result[0] = ESC;
        result[1] = 0x74;
        result[2] = charset;
        return result;
    }

    /**
     * 设置多字节字符集
     */
    public static byte[] setCodeSystem(byte charset){
        byte[] result = new byte[3];
        result[0] = FS;
        result[1] = 0x43;
        result[2] = charset;
        return result;
    }

    // ------------------------Align-----------------------------

    /**
     * 居左
     */
    public static byte[] alignLeft() {
        byte[] result = new byte[3];
        result[0] = ESC;
        result[1] = 97;
        result[2] = 0;
        return result;
    }

    /**
     * 居中对齐
     */
    public static byte[] alignCenter() {
        byte[] result = new byte[3];
        result[0] = ESC;
        result[1] = 97;
        result[2] = 1;
        return result;
    }

    /**
     * 居右
     */
    public static byte[] alignRight() {
        byte[] result = new byte[3];
        result[0] = ESC;
        result[1] = 97;
        result[2] = 2;
        return result;
    }

    //切刀
    public static byte[] cutter() {
        byte[] data = new byte[]{0x1d, 0x56, 0x01};
        return data;
    }

    //走纸到黑标
    public static byte[] gogogo(){
        byte[] data = new byte[]{0x1C, 0x28, 0x4C, 0x02, 0x00, 0x42, 0x31};
        return data;
    }


    ////////////////////////////////////////////////////////////////////////////////////
    //////////////////////////          private                /////////////////////////
    ////////////////////////////////////////////////////////////////////////////////////
    private static byte[] setQRCodeSize(int modulesize){
        //二维码块大小设置指令
        byte[] dtmp = new byte[8];
        dtmp[0] = GS;
        dtmp[1] = 0x28;
        dtmp[2] = 0x6B;
        dtmp[3] = 0x03;
        dtmp[4] = 0x00;
        dtmp[5] = 0x31;
        dtmp[6] = 0x43;
        dtmp[7] = (byte)modulesize;
        return dtmp;
    }

    private static byte[] setQRCodeErrorLevel(int errorlevel){
        //二维码纠错等级设置指令
        byte[] dtmp = new byte[8];
        dtmp[0] = GS;
        dtmp[1] = 0x28;
        dtmp[2] = 0x6B;
        dtmp[3] = 0x03;
        dtmp[4] = 0x00;
        dtmp[5] = 0x31;
        dtmp[6] = 0x45;
        dtmp[7] = (byte)(48+errorlevel);
        return dtmp;
    }


    private static byte[] getBytesForPrintQRCode(boolean single){
        //打印已存入数据的二维码
        byte[] dtmp;
        if(single){     //同一行只打印一个QRCode, 后面加换行
            dtmp = new byte[9];
            dtmp[8] = 0x0A;
        }else{
            dtmp = new byte[8];
        }
        dtmp[0] = 0x1D;
        dtmp[1] = 0x28;
        dtmp[2] = 0x6B;
        dtmp[3] = 0x03;
        dtmp[4] = 0x00;
        dtmp[5] = 0x31;
        dtmp[6] = 0x51;
        dtmp[7] = 0x30;
        return dtmp;
    }

    private static byte[] getQCodeBytes(String code) {
        //二维码存入指令
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        try {
            byte[] d = code.getBytes("GB18030");
            int len = d.length + 3;
            if (len > 7092) len = 7092;
            buffer.write((byte) 0x1D);
            buffer.write((byte) 0x28);
            buffer.write((byte) 0x6B);
            buffer.write((byte) len);
            buffer.write((byte) (len >> 8));
            buffer.write((byte) 0x31);
            buffer.write((byte) 0x50);
            buffer.write((byte) 0x30);
            for (int i = 0; i < d.length && i < len; i++) {
                buffer.write(d[i]);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return buffer.toByteArray();
    }


    /**
     * 设置字体大小
     */

    public static byte[] setTextSize(int size) {
        byte[] bytes = CMD_FontSize(size).getBytes();
        return bytes;
    }

    // 字体的大小
    // 0:正常大小 1:两倍高 2:两倍宽 3:两倍大小 4:三倍高 5:三倍宽 6:三倍大小
    // 7:四倍高 8:四倍宽 9:四倍大小 10:五倍高 11:五倍宽 12:五倍大小
    public static String CMD_FontSize(int nfontsize) {
        String _cmdstr = "";
        // 设置字体大小
        switch (nfontsize) {
            case -1:
                _cmdstr = new StringBuffer().append((char) 29).append((char) 33)
                        .append((char) 0).toString();// 29 33
                break;

            case 0:
                _cmdstr = new StringBuffer().append((char) 29).append((char) 33)
                        .append((char) 0).toString();// 29 33
                break;

            case 1:
                _cmdstr = new StringBuffer().append((char) 29).append((char) 33)
                        .append((char) 1).toString();
                break;

            case 2:
                _cmdstr = new StringBuffer().append((char) 29).append((char) 33)
                        .append((char) 16).toString();
                break;

            case 3:
                _cmdstr = new StringBuffer().append((char) 29).append((char) 33)
                        .append((char) 17).toString();
                break;

            case 4:
                _cmdstr = new StringBuffer().append((char) 29).append((char) 33)
                        .append((char) 2).toString();
                break;

            case 5:
                _cmdstr = new StringBuffer().append((char) 29).append((char) 33)
                        .append((char) 32).toString();
                break;

            case 6:
                _cmdstr = new StringBuffer().append((char) 29).append((char) 33)
                        .append((char) 34).toString();
                break;

            case 7:
                _cmdstr = new StringBuffer().append((char) 29).append((char) 33)
                        .append((char) 3).toString();
                break;

            case 8:
                _cmdstr = new StringBuffer().append((char) 29).append((char) 33)
                        .append((char) 48).toString();
                break;

            case 9:
                _cmdstr = new StringBuffer().append((char) 29).append((char) 33)
                        .append((char) 51).toString();
                break;

            case 10:
                _cmdstr = new StringBuffer().append((char) 29).append((char) 33)
                        .append((char) 4).toString();
                break;

            case 11:
                _cmdstr = new StringBuffer().append((char) 29).append((char) 33)
                        .append((char) 64).toString();
                break;

            case 12:
                _cmdstr = new StringBuffer().append((char) 29).append((char) 33)
                        .append((char) 68).toString();
                break;

        }
        Log.d("textSize",_cmdstr);
        return _cmdstr;
    }
}

补一个BytesUtil工具类代码,

public class BytesUtil {

    //字节流转16进制字符串
    public static String getHexStringFromBytes(byte[] data) {
        if (data == null || data.length <= 0) {
            return null;
        }
        String hexString = "0123456789ABCDEF";
        int size = data.length * 2;
        StringBuilder sb = new StringBuilder(size);
        for (int i = 0; i < data.length; i++) {
            sb.append(hexString.charAt((data[i] & 0xF0) >> 4));
            sb.append(hexString.charAt((data[i] & 0x0F) >> 0));
        }
        return sb.toString();
    }

    //单字符转字节
    private static byte charToByte(char c) {
        return (byte) "0123456789ABCDEF".indexOf(c);
    }

    //16进制字符串转字节数组
    @SuppressLint("DefaultLocale")
    public static byte[] getBytesFromHexString(String hexstring){
        if(hexstring == null || hexstring.equals("")){
            return null;
        }
        hexstring = hexstring.replace(" ", "");
        hexstring = hexstring.toUpperCase();
        int size = hexstring.length()/2;
        char[] hexarray = hexstring.toCharArray();
        byte[] rv = new byte[size];
        for(int i=0; i> 8);//xH
        data[2] = (byte)hh;
        data[3] = (byte)(hh >> 8);

        int k = 4;
        int m = 31;
        for(int i=0; i hints = new Hashtable();
            hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
            //图像数据转换,使用了矩阵转换
            BitMatrix bitMatrix = new QRCodeWriter().encode(data, BarcodeFormat.QR_CODE, size, size, hints);
            //System.out.println("bitmatrix height:" + bitMatrix.getHeight() + " width:" + bitMatrix.getWidth());
            return getBytesFromBitMatrix(bitMatrix);
        } catch (WriterException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    public static byte[] getBytesFromBitMatrix(BitMatrix bits) {
        if (bits == null) return null;

        int h = bits.getHeight();
        int w = (bits.getWidth() + 7) / 8;
        byte[] rv = new byte[h * w + 4];

        rv[0] = (byte) w;//xL
        rv[1] = (byte) (w >> 8);//xH
        rv[2] = (byte) h;
        rv[3] = (byte) (h >> 8);

        int k = 4;
        for (int i = 0; i < h; i++) {
            for (int j = 0; j < w; j++) {
                for (int n = 0; n < 8; n++) {
                    byte b = getBitMatrixColor(bits, j * 8 + n, i);
                    rv[k] += rv[k] + b;
                }
                k++;
            }
        }
        return rv;
    }

    private static byte getBitMatrixColor(BitMatrix bits, int x, int y) {
        int width = bits.getWidth();
        int height = bits.getHeight();
        if (x >= width || y >= height || x < 0 || y < 0) return 0;
        if (bits.get(x, y)) {
            return 1;
        } else {
            return 0;
        }
    }

    /**
     * 将bitmap图转换为头四位有宽高的光栅位图
     */
    public static byte[] getBytesFromBitMap(Bitmap bitmap) {
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        int bw = (width - 1) / 8 + 1;

        byte[] rv = new byte[height * bw + 4];
        rv[0] = (byte) bw;//xL
        rv[1] = (byte) (bw >> 8);//xH
        rv[2] = (byte) height;
        rv[3] = (byte) (height >> 8);

        int[] pixels = new int[width * height];
        bitmap.getPixels(pixels, 0, width, 0, 0, width, height);

        for (int i = 0; i < height; i++) {
            for (int j = 0; j < width; j++) {
                int clr = pixels[width * i + j];
                int red = (clr & 0x00ff0000) >> 16;
                int green = (clr & 0x0000ff00) >> 8;
                int blue = clr & 0x000000ff;
                byte gray = (RGB2Gray(red, green, blue));
                rv[(width * i + j) / 8 + 4] = (byte) (rv[(width * i + j) / 8 + 4] | (gray << (7 - ((width * i + j) % 8))));
            }
        }

        return rv;
    }

    /**
     * 将bitmap转成按mode指定的N点行数据
     */
    public static byte[] getBytesFromBitMap(Bitmap bitmap, int mode) {
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        int[] pixels = new int[width*height];
        if(mode == 0 || mode == 1){
            byte[] res = new byte[width*height/8 + 5*height/8];
            bitmap.getPixels(pixels, 0, width, 0, 0, width, height);
            for(int i = 0; i < height/8; i++){
                res[0 + i*(width+5)] = 0x1b;
                res[1 + i*(width+5)] = 0x2a;
                res[2 + i*(width+5)] = (byte) mode;
                res[3 + i*(width+5)] = (byte) (width%256);
                res[4 + i*(width+5)] = (byte) (width/256);
                for(int j = 0; j < width; j++){
                    byte gray = 0;
                    for(int m = 0; m < 8; m++){
                        int clr = pixels[j + width*(i*8+m)];
                        int red = (clr & 0x00ff0000) >> 16;
                        int green = (clr & 0x0000ff00) >> 8;
                        int blue = clr & 0x000000ff;
                        gray = (byte) ((RGB2Gray(red, green, blue)<<(7-m))|gray);
                    }
                    res[5 + j + i*(width+5)] = gray;
                }
            }
            return res;
        }else if(mode == 32 || mode == 33){
            byte[] res = new byte[width*height/8 + 5*height/24];
            bitmap.getPixels(pixels, 0, width, 0, 0, width, height);
            for(int i = 0; i < height/24; i++){
                res[0 + i*(width*3+5)] = 0x1b;
                res[1 + i*(width*3+5)] = 0x2a;
                res[2 + i*(width*3+5)] = (byte) mode;
                res[3 + i*(width*3+5)] = (byte) (width%256);
                res[4 + i*(width*3+5)] = (byte) (width/256);
                for(int j = 0; j < width; j++){
                    for(int n = 0; n < 3; n++){
                        byte gray = 0;
                        for(int m = 0; m < 8; m++){
                            int clr = pixels[j + width*(i*24 + m + n*8)];
                            int red = (clr & 0x00ff0000) >> 16;
                            int green = (clr & 0x0000ff00) >> 8;
                            int blue = clr & 0x000000ff;
                            gray = (byte) ((RGB2Gray(red, green, blue)<<(7-m))|gray);
                        }
                        res[5 + j*3 + i*(width*3+5) + n] = gray;
                    }
                }
            }
            return res;
        }else{
            return new byte[]{0x0A};
        }

    }

    private static byte RGB2Gray(int r, int g, int b) {
        return (false ? ((int) (0.29900 * r + 0.58700 * g + 0.11400 * b) > 200)
                : ((int) (0.29900 * r + 0.58700 * g + 0.11400 * b) < 200)) ? (byte) 1 : (byte) 0;
    }

    /**
     * 生成间断性黑块数据
     * @param w : 打印纸宽度, 单位点
     * @return
     */
    public static byte[] initBlackBlock(int w){
        int ww = (w + 7)/8 ;
        int n = (ww + 11)/12;
        int hh = n * 24;
        byte[] data = new byte[ hh * ww + 5];

        data[0] = (byte)ww;//xL
        data[1] = (byte)(ww >> 8);//xH
        data[2] = (byte)hh;
        data[3] = (byte)(hh >> 8);

        int k = 4;
        for(int i=0; i < n; i++){
            for(int j=0; j<24; j++){
                for(int m =0; m> 8);//xH
        data[2] = (byte)hh;
        data[3] = (byte)(hh >> 8);

        int k = 4;
        for(int i=0; i

使用方法示例:

USBPrinter usbPrinter = USBPrinter.getInstance();
usbPrinter.initPrinter(this);
usbPrinter.bold(true);
usbPrinter.setTextSize(3);
usbPrinter.setAlign(1);
usbPrinter.printTextNewLine(tableName);
usbPrinter.printLine(1);
usbPrinter.bold(false);
usbPrinter.printTextNewLine("出品单号:"+bean.getKitExpNumber());
usbPrinter.printTextNewLine("出品员:"+bean.getChefName());
usbPrinter.printBarCode("6936983800013");
usbPrinter.printLine(5);
usbPrinter.cutPager();

记得在Actvity的onDestroy生命周期里调用USBPrinter.getInstance().close()方法

你可能感兴趣的:(android设备连接USB打印机的打印方法)