微信小程序(uni)+蓝牙连接+Xprint打印机实现打印功能

1.蓝牙列表实现,蓝牙设备展示,蓝牙连接

<template>
	<view class="container">
			<view class="container_top">
				<view class="l">
					设备名称
				</view>
				<view class="r">
					{
  {state.phoneName}}
				</view>
			</view>
			<view class="container_bot">
				<view class="sub_t">
					<view class="sub_t_l">
						可用设备
					</view>
					<view class="sub_t_r" @click="initBlueTooth">
						<image src="../../static/image/refresh.svg" mode=""></image>
					</view>
				</view>
				<view class="wrapper">
					<view class="item" v-for="(item,index) in list">
						<view class="item_l">
							<image src="../../static/image/name.svg" mode=""></image>
						</view>
						<view class="item_m">
							<view class="name">
								{
  {item.name}}
							</view>
							<view class="status">
								{
  {item.status==0?'未连接':'已连接'}}
							</view>
						</view>
						<view class="item_r">
							<button v-if="item.status==0" :loading="item.loading" class="btn"
								@click="connect(item.deviceId,index)">连接</button>
							<button v-else class="btn_d" @click="close(item.deviceId,index)">断开</button>
						</view>
					</view>
				</view>
			</view>
		</view>
</template>

<script setup>
	import {
		onLoad,
		onShow
	} from '@dcloudio/uni-app'
	import {
		showModal
	} from '@/utils/showModal';
	import {
		changePassApi
	} from '@/request/apiManage/commonApi.js'
	import {
		reactive,
		ref,
	} from 'vue'
	const state = reactive({
		phoneName: '',
	})
	const list = ref([])
	const openAuth = ref(false)
	
	const auth =() => {
		const data = uni.getAppAuthorizeSetting()
		console.log(data)
		if (data.locationAuthorized == 'denied') {
			uni.showModal({
				title: '提示',
				content: '获取可连接蓝牙设备,须授权当前位置',
				confirmText: '去授权',
				success: res => {
					if (res.confirm) {
						uni.openAppAuthorizeSetting({
							success: res => {
								console.log(res)
								openAuth.value = true
							}
						})
					}else{
						uni.navigateBack()
					}
				}
			})
		} else {
			initBlueTooth()
		}
	}
	//初始化蓝牙
	const initBlueTooth = () => {
		uni.showLoading({
			mask: true
		})
		console.log('初始化蓝牙')
		wx.openBluetoothAdapter({
			 mode: "central", //开启主机
			success: async res => {
				const data = await getBlueState()
				console.log(data)
				if (data.available) {
					//搜寻设备
					const result = await getBlueList()
					//获取蓝牙列表
					setTimeout(() => {
						onListenerBTDevFound()
					}, 2000)
				}
			},
			fail(err) {
				console.log(err)
				uni.showToast({
					title: '蓝牙设备未开启',
					icon: 'none',
					duration: 2000
				})
			}
		})
	}
	// 获取蓝牙设备状态
	const getBlueState = () => {
		return new Promise((resolve, reject) => {
			uni.getBluetoothAdapterState({
				success: res => {
					resolve(res)
				},
				fail: err => {
					reject(err)
				}
			})
		})
	}
	// 搜索附近蓝牙设备
	const getBlueList = ()=> {
		return new Promise((resolve, reject) => {
			uni.startBluetoothDevicesDiscovery({
				allowDuplicatesKey: true,
				success: res => {
					resolve(res)
				},
				fail: err => {
					reject(err)
				}
			})
		})
	}
	// 监听获取蓝牙列表
	const onListenerBTDevFound = () => {
		uni.getBluetoothDevices({
			success: r => {
				list.value = r.devices.filter(i => i.name && i.name != '未知设备').map(item => ({
					...item,
					status: 0,
					loading: false
				}))
				uni.hideLoading()
			},
			fail: err => {
				console.log(err)
			},
			complete: () => {
				uni.hideLoading()
			}
		})
	}
	// 蓝牙设备链接
	const connect = (deviceId, index) => {
		console.log('蓝牙设备链接---------------',deviceId,index)
		list.value[index].loading = true
		uni.createBLEConnection({
		deviceId: deviceId,
			success: res => {
			console.log('蓝牙连接成功',res)
			// 停止搜索
			if (!uni.getStorageSync('lanya') || !Object.values(JSON.parse(uni.getStorageSync('lanya'))).length) 
			{
				console.log('获取设备服务-------------')
				getBLEDeviceServices(deviceId, index)
			} else {
				list.value[index].loading = false
				list.value[index].status = 1
			}
				stopDiscovery()
			},
			fail(err) {
				console.log('连接失败')
					}
				})
			}
	//获取设备服务id
	const getBLEDeviceServices =(deviceId, index) =>{
		console.log('获取设备服务-------------')
		setTimeout(() => {
			uni.getBLEDeviceServices({
				deviceId,
				success: res => {
					console.log('获取设备服务成功',deviceId, res.services, index)
					getBLEDeviceCharacteristics(deviceId, res.services, index)
				},
				fail: err => {
					console.log('获取服务失败', err)
					}
				})
		}, 2000)
	}
	// 获取设备服务值
	const getBLEDeviceCharacteristics = async (deviceId, services, index) => {
	    const arr = ref([])
	    const results = await Promise.all(
	        services.map(service => 
	            getBLEDeviceCharacteristicsProxy(deviceId, service.uuid)
	        )
	    )
	    arr.value = results.filter(item => item)
	    if (arr.value.length > 0) {
	        const { startId, uuid } = arr.value[0]
	        await notifyBLECharacteristicValueChange(deviceId, startId, uuid, index)
			uni.setStorageSync('lanya', JSON.stringify({
				deviceId,
				serviceId: startId,
				characteristicId: uuid
			}))
	    } else {
	        uni.showToast({
	            title: '找不到蓝牙服务',
	            icon: 'error'
	        })
	    }
	}
	// 获取特征值
	const getBLEDeviceCharacteristicsProxy = (deviceId, uuid) =>{
					return new Promise((resolve, reject) => {
						uni.getBLEDeviceCharacteristics({
							deviceId,
							serviceId: uuid,
							success: res => {
								console.log('获取特征值成功-----',)
								console.log(res)
								const data = res.characteristics.filter(i => i.properties.write && i
									.properties.notify)
								if (data.length > 0) {
									resolve({
										...data[0],
										startId: uuid
									})
								} else {
									resolve('')
								}
							},
							fail: err => {
								console.log('获取特征值失败', err)
							}
						})
					})
				}
			// 特征值变化通知	
			const notifyBLECharacteristicValueChange = (deviceId, serviceId, characteristicId, index) => {
					console.log('notifyBLECharacteristicValueChange----------',deviceId, serviceId, characteristicId, index)
					setTimeout(() => {
						uni.notifyBLECharacteristicValueChange({
							state: true,
							deviceId,
							serviceId,
							characteristicId,
							success: res => {
								console.log('特征值变化通知连接成功')
								list.value[index].loading = false
								console.log(res)
								list.value[list.value.findIndex(item => item.deviceId == deviceId)].status =
									1
								console.log('特征值变化通知存蓝牙setStorageSync----------------------', deviceId, serviceId, characteristicId)
								uni.setStorageSync('lanya', JSON.stringify({
									deviceId,
									serviceId,
									characteristicId
								}))
							},
							fail: err => {
								console.log('特征值变化通知连接失败')
								console.log(err)
							}
						})
				
					}, 1000)
				}
	// 停止搜索设备	
	const stopDiscovery =()=> {
		uni.stopBluetoothDevicesDiscovery({
			success(res) {
				console.log('停止成功')
				console.log(res)
			},
			fail(err) {
				console.log('停止失败')
				console.error(err)
			}
		})
	}
	// 断开蓝牙
	const close = (deviceId, index) => {
		uni.closeBLEConnection({
			deviceId,
			success: res => {
				console.log(res)
				list.value[index].status = 0
				uni.removeStorageSync('lanya');
			}
		})
	}
	onLoad(() => {
		const data = uni.getSystemInfoSync()
		state.phoneName = data.brand
		auth()
	
	})
	onShow(()=>{
		if (openAuth.value) {
			const data = uni.getAppAuthorizeSetting()
			console.log(data, data.locationAuthorized)
			if (data.locationAuthorized == 'authorized') {
				initBlueTooth()
			} else {
				uni.showModal({
				title: '提示',
				content: '您已拒绝授权当前位置,当前蓝牙设备服务不可用',
				cancelText: '退出',
				confirmText: '重新授权',
				success: res => {
					if (res.confirm) {
						auth()
					} else {
						uni.navigateBack()
					}
				}
			})
			}
		}
	}) 
	
</script>

<style scoped lang="scss">
		.container {
			height: 100vh;
			background: #fff;
			display: flex;
			flex-direction: column;
			align-items: center;
		
			.container_top {
				width: 630rpx;
				background: #F5F6FA;
				box-shadow: inset 0px -2 0px 0px rgba(0, 0, 0, 0.05);
				border-radius: 16rpx;
				height: 96rpx;
				padding: 0 20rpx;
				margin-bottom: 38rpx;
				display: flex;
				align-items: center;
				justify-content: space-between;
				opacity: 1;
	
				.l {
					font-size: 32rpx;
					font-weight: bold;
					color: #000000;
				}
	
				.r {
					font-size: 32rpx;
					font-weight: 400;
					color: #AEB1BC;
				}
			}
	
			.container_bot {
				width: 630rpx;
				// padding: 0 20rpx;
				// margin: auto;
				flex: 1;
				display: flex;
				flex-direction: column;
				overflow-y: hidden;
	
				.sub_t {
					display: flex;
					align-items: center;
					justify-content: space-between;
					margin-bottom: 20rpx;
	
					.sub_t_l {
						font-size: 32rpx;
						font-weight: 400;
						color: #000000;
					}
	
					.sub_t_r {
						
						image {
							display: block;
							width: 68rpx;
							height: 68rpx;
						}
					}
				}
	
				.wrapper {
					flex: 1;
					overflow-y: scroll;
	
					.item {
						// padding: 15rpx 15rpx;
						display: flex;
						align-items: center;
						justify-content: space-between;
						background: #FFFFFF;
						border-radius: 16rpx;
						margin-bottom: 20rpx;
	
						.item_l {
							width: 88rpx;
	
							image {
								width: 88rpx;
								height: 88rpx;
								display: block;
							}
						}
	
						.item_m {
							flex: 1;
							margin: 0 20rpx;
	
							.name {
								font-size: 36rpx;
								font-weight: bold;
								color: #000000;
								overflow: hidden;
								white-space: nowrap;
								text-overflow: ellipsis;
								word-break: break-all;
							}
	
							.status {
								
								font-size: 24rpx;
								font-weight: 400;
								color: #6D7284;
							}
						}
	
						.item_r {
							uni-button:after {
								padding: 0;
								border: none;
								width: 100%;
								height: 100%;
							}
	
							button {
								width: 130rpx;
								height: 56rpx;
								border-radius: 200rpx;
								opacity: 1;
								font-size: 24rpx;
								font-family: PingFang SC, PingFang SC;
								font-weight: 600;
								line-height: 56rpx;
								color: #FFFFFF;
							}
	
							.btn {
								background: linear-gradient(180deg, #74C8FB 0%, #4DA3FE 100%);
							}
	
							.btn_d {
								background: linear-gradient(180deg, #FC80A3 0%, #F8827F 100%);
							}
	
						}
					}
				}
			}
		}
</style>

2.蓝牙连接成功过后,实现打印机打印功能

2.1蓝牙打印接口封装


import { printer } from "./printer.js";

const initBlue = () => {
  return new Promise((resolve, reject) => {
    uni.openBluetoothAdapter({
      success: (res) => {
        console.log(res);
        resolve("success");
      },
      fail: (err) => {
        console.log(err);
        resolve("error");
      },
    });
  });
};
const getBlue = () => {
  return new Promise((resolve, reject) => {
    uni.getConnectedBluetoothDevices({
      success(res) {
        console.log(res);
        resolve("success");
      },
      fail(err) {
        console.log(err);
        resolve("error");
      },
    });
  });
};
const autoConnectBlue = () => {
  return new Promise((resolve, reject) => {
    const { deviceId } = JSON.parse(uni.getStorageSync("lanya"));
    uni.createBLEConnection({
      deviceId: deviceId,
      success(res) {
        console.log("连接成功");
        resolve("success");
      },
      fail(err) {
        console.log("连接失败");
        console.error(err);
        resolve("error");
      },
    });
  });
};
export const initPrinterData = async (data) => {
  uni.showLoading({
    title: "打印中...",
    mask: true,
  });
  const blueRes = await getBlue();
  if (blueRes == "error") {
    const res = await initBlue();
    if (res != "success") {
      uni.showToast({
        title: "蓝牙设备未开启",
        icon: "error",
		duration: 2000
      });
      uni.hideLoading();
      return;
    }
    const result = await autoConnectBlue();
    if (result != "success") {
      uni.showModal({
        title: "提示",
        content: "连接失败,请重新配置蓝牙",
        confirmText: "去配置",
        success: (res) => {
          if (res.confirm) {
            uni.navigateTo({
              url: "/pages/bluetoothPage/bluetoothPage",
            });
          }
        },
      });
      uni.hideLoading();
      return;
    }
  }
  setTimeout(() => {
	printer.AddPrintQueue('InitPos');
  		for (var i = 0; i < data.length; i++) {
  			if (data[i].type == 'PrintNameValue') {
  				printer.PrintNameValue(`${data[i].label}`, `${data[i].value}`)
  			}else if(data[i].type=='PPP'){
  				let goods=data[i].value.split(',')
  				printer[data[i].type](goods[0],goods[1],goods[2],goods[3])
  			}else{
  				printer[data[i].type](data[i].value)
  			}
  		}
  		printer.PrintJumpLines(5);
  		if (i >= data.length) {
  			uni.hideLoading()
  			setTimeout(() => {
  				printer.DaYin((res) => {
  					console.log('打印出错', res)
  					if (res == "err") {
  						printer.ClearQueue(); //清空打印列队
  						//提示,打印出错,请稍后再试,仍然出错请重新设置打印机
  					}
  					uni.hideLoading()
  				});
  			}, 2000)
  		}
  	}, 1000)
};

 2.2.打印机打印参数设置

var QueueWrite = new Array(); //等待写入蓝牙的执行队列

/*****************************  条形码 ******************************/
const ONE_UPC_A = 65;
const ONE_UPC_E = 66;
const ONE_CODE39 = 69;
const ONE_ITF = 70;
const ONE_CODE93 = 72;
const ONE_JAN13 = 67;
const ONE_CODE128 = 73;
const ONE_JAN8 = 68;
const ONE_CODABAR = 71;
// 二维码
const TWO_PDF417 = 100;
const TWO_DATAMATRIX = 101;
const TWO_QRCODE = 102;

/*************状态查询指令开始******************************************************/
var GS_Query_Printer_Status = new Uint8Array([0x1D, 0x61, 0x00]);
var GS_Query_Printer_Consistence = new Uint8Array([0x1D, 0x67, 0x31]);
var GS_Query_Printer_Speed = new Uint8Array([0x1D, 0x67, 0x32]);
var GS_Query_Printer_Language = new Uint8Array([0x1D, 0x67, 0x33]);
var GS_Query_Printer_BlackLabel = new Uint8Array([0x1D, 0x67, 0x34]);
var GS_Query_Printer_BlackLabelVol = new Uint8Array([0x1D, 0x67, 0x35]);
var GS_Query_Printer_Temperature = new Uint8Array([0x1D, 0x67, 0x36]);
var GS_Query_Printer_Baudrate = new Uint8Array([0x1D, 0x67, 0x37]);
var GS_Query_Printer_Bit = new Uint8Array([0x1D, 0x67, 0x38]);
var GS_Query_Printer_SerialNumber = new Uint8Array([0x1D, 0x67, 0x39]);
var GS_Query_Printer_MachineID = new Uint8Array([0x1D, 0x67, 0x61]);
var GS_Query_Printer_ProductDate = new Uint8Array([0x1D, 0x67, 0x62]);
var GS_Query_Printer_CutAutoReset = new Uint8Array([0x1D, 0x67, 0x63]);
var GS_Query_Printer_Code = new Uint8Array([0x1D, 0x67, 0x64]);
var GS_Query_Printer_FeedBeforeCut = new Uint8Array([0x1D, 0x67, 0x65]);
var GS_Query_Printer_SoftwareVersionNumber = new Uint8Array([0x1D, 0x67, 0x66]);
var GS_Query_Printer_Factory = new Uint8Array([0x1D, 0x67, 0x67]);
var GS_Query_Printer_Machine = new Uint8Array([0x1D, 0x67, 0x68]);
var GS_Query_Printer_PaperDistance = new Uint8Array([0x1D, 0x67, 0x69]);
var GS_Query_Printer_MachineType = new Uint8Array([0x1D, 0x67, 0x6B]);
var GS_Query_Printer_Power = new Uint8Array([0x1D, 0x67, 0x6C]);
var GS_Query_Printer_WorkLen = new Uint8Array([0x1D, 0x67, 0x6d, 0x00]);
/*************状态查询指令结束******************************************************/

/*******************************自检指令开始***********************************/
var GS_Self_Check = new Uint8Array([27, 35, 35, 83, 69, 76, 70]);
/*******************************自检指令结束***********************************/


export const printer = {
	QueueWrite: QueueWrite, //打印队列
	ClearQueue: ClearQueue, //清空打印机待执行队列
	AddPrintQueue: AddPrintQueue, //添加到打印队列
	PrintTitle: PrintTitle, //打印标题(居中加粗)
	PrintText: PrintText, //打印普通文字(从左至右,不加粗)
	PrintBigTitle: PrintBigTitle, //打印加粗文字(从左至右)
	PrintNameValue: PrintNameValue, //打印键值文字(左边加粗,右边不加粗)
	PrintMiddleText: PrintMiddleText, //居中打印,不加粗
	PrintMiddleTextBold: PrintMiddleTextBold, //居中打印,加粗
	PrintJumpLines: PrintJumpLines, //跳行 

	printCurve: printCurve, //打印曲线
	printCurveText: printCurveText, //打印曲线文字
	printCurveEnd: printCurveEnd, //结束打印

	PPP: PPP,
	DaYin: DaYin,
	startnotify: startnotify,
	printOnBarCode: printOnBarCode, //打印一维码
	printTwoBarCode: printTwoBarCode, //打印二维码 
	ONE_UPC_A: ONE_UPC_A,
	ONE_UPC_E: ONE_UPC_E,
	ONE_CODE39: ONE_CODE39,
	ONE_ITF: ONE_ITF,
	ONE_CODE93: ONE_CODE93,
	ONE_JAN13: ONE_JAN13,
	ONE_CODE128: ONE_CODE128,
	ONE_JAN8: ONE_JAN8,
	ONE_CODABAR: ONE_CODABAR,
	// 二维码
	TWO_PDF417: TWO_PDF417,
	TWO_DATAMATRIX: TWO_DATAMATRIX,
	TWO_QRCODE: TWO_QRCODE,

	// 查询指令
	GS_Query_Printer_Status: GS_Query_Printer_Status,
	GS_Query_Printer_Consistence: GS_Query_Printer_Consistence,
	GS_Query_Printer_Speed: GS_Query_Printer_Speed,
	GS_Query_Printer_Language: GS_Query_Printer_Language,
	GS_Query_Printer_BlackLabel: GS_Query_Printer_BlackLabel,
	GS_Query_Printer_BlackLabelVol: GS_Query_Printer_BlackLabelVol,
	GS_Query_Printer_Temperature: GS_Query_Printer_Temperature,
	GS_Query_Printer_Baudrate: GS_Query_Printer_Baudrate,
	GS_Query_Printer_Bit: GS_Query_Printer_Bit,
	GS_Query_Printer_SerialNumber: GS_Query_Printer_SerialNumber,
	GS_Query_Printer_MachineID: GS_Query_Printer_MachineID,
	GS_Query_Printer_ProductDate: GS_Query_Printer_ProductDate,
	GS_Query_Printer_CutAutoReset: GS_Query_Printer_CutAutoReset,
	GS_Query_Printer_Code: GS_Query_Printer_Code,
	GS_Query_Printer_FeedBeforeCut: GS_Query_Printer_FeedBeforeCut,
	GS_Query_Printer_SoftwareVersionNumber: GS_Query_Printer_SoftwareVersionNumber,
	GS_Query_Printer_Factory: GS_Query_Printer_Factory,
	GS_Query_Printer_Machine: GS_Query_Printer_Machine,
	GS_Query_Printer_PaperDistance: GS_Query_Printer_PaperDistance,
	GS_Query_Printer_MachineType: GS_Query_Printer_MachineType,
	GS_Query_Printer_Power: GS_Query_Printer_Power,
	GS_Query_Printer_WorkLen: GS_Query_Printer_WorkLen,

	//自检指令
	GS_Self_Check: GS_Self_Check,
}

function DaYin(cback) {
	if (isPrint) return;
	DaYin2(cback)
}

var isPrint = false; //记录是否正在打印
function DaYin2(cback) {
	while (QueueWrite.length > 0) {
		isPrint = true;
		var shuzu = QueueWrite.shift();
		let byteLength = shuzu.byteLength;
		while (byteLength > 0) {
			let speed = byteLength > 20 ? 20 : byteLength;
			let text = shuzu.slice(0, speed);
			lanyaposgo(text, cback);
			shuzu = shuzu.slice(speed, byteLength);
			byteLength = shuzu.byteLength;
		}
	}
	isPrint = false;
}

function lanyaposgo(text, cback) {
	const {
		deviceId,
		serviceId,
		characteristicId
	} = JSON.parse(uni.getStorageSync('lanya'))
	uni.writeBLECharacteristicValue({
		deviceId,
		serviceId,
		characteristicId,
		value: text.buffer,
		success: function(res) {
			// DaYin2(cback);
			console.log('打印成功')
			console.log(res)
		},
		fail: function(res) {
			// reject(res)
			isPrint = false;
			cback("err");
			console.log("打印错误writeBLECharacteristicValue:", res)
			console.log("打印错误writeBLECharacteristicValue:", res.errCode)
			console.log("打印数据:", "/" + text + "/")
			let mes = ''
			if(res.errCode===1000) {
				mes = '未初始化蓝牙适配器'
			} else if(res.errCode===10001) {
				mes = '当前蓝牙适配器不可用'
			} else if(res.errCode===10002) {
				mes = '没有找到指定设备'
			} else if(res.errCode===10003) {
				mes = '连接失败'
			}else if(res.errCode===10004) {
				mes = '没有找到指定服务'
			}else if(res.errCode===10006) {
				mes = '当前连接已断开'
			}else if(res.errCode===10012) {
				mes = '连接超时'
			}
			uni.showToast({
			  title: mes,
			  icon: "error",
			  duration: 4000
			});
		}
	})
}

function DaYin3(cback) {
	isPrint = true;
	var DD = new Uint8Array();
	for (var x in QueueWrite) {
		DD = Arry2Arry(DD, QueueWrite[x])
	}
	lanyaposgo3(DD, cback)
	QueueWrite = new Array()
	isPrint = false;
}


function lanyaposgo3(text, cback) {
	uni.writeBLECharacteristicValue({
		deviceId: LY.dayinji.uuid,
		serviceId: LY.dayinji.suuid,
		characteristicId: LY.dayinji.nuuid,
		value: text.buffer,
		success: function(res) {},
		fail: function(res) {
			isPrint = false;
			cback("err");
			console.log("打印错误:", res)
			console.log("打印数据:", "/" + text + "/")
		}
	})
}

function ab2hex(buffer) {
	var hexArr = Array.prototype.map.call(
		new Uint8Array(buffer),
		function(bit) {
			return '0x' + ('00 ' + bit.toString(16)).slice(-2)
		}
	)
	return hexArr.join(',');
}

function startnotify(that) {
	uni.notifyBLECharacteristicValueChange({
		state: true,
		deviceId: LY.dayinji.uuid,
		serviceId: LY.dayinji.suuid,
		characteristicId: LY.dayinji.nuuid,
		success: function(res) {
			console.log('notifyBLECharacteristicValueChange success', res.errMsg)
			uni.onBLECharacteristicValueChange(function(res) {
				// 作为全局变量
				let array = Array.prototype.slice.call(new Uint8Array(res.value));
				console.log(array);
				//弹出信息框
				var data = that.data.receiveData;
				that.setData({
					receiveData: data + ab2hex(array)
				});
			})
		}
	});
}

function jiequ(_buffer, _start, _end) {
	return _buffer.slice(_start, _end)
}

function ZhengChu(_len1, _len2) {
	return Math.ceil(_len1 / _len2)
}

function PPP(a, b, c,d) {
	var name = addSL(a);
	var SL = addSL(b);
	var DJ = addSL(c)
	if(d){
	var al=addSL(d)
	PrintText(name+SL+DJ+al)
	}else{
		var k=addSL('')
		PrintText(k+name+SL+DJ)
	}
	
}

function len(s) {
	var l = 0;
	var a = s.split("");
	for (var i = 0; i < a.length; i++) {
		if (a[i].charCodeAt(0) < 299) {
			l++;
		} else {
			l += 2;
		}
	}
	return l;
}

function addName(str) {
	str = "       " + str
	var l = len(str);
	var zl = 16;
	var bl = zl - l;
	for (var i = 0; i < bl; i++) {
		str += " ";
	}
	return str;
}

function addSL(str) {
	var l = len(str);
	var zl = 8;
	var bl = zl - l;
	for (var i = 0; i < bl; i++) {
		str += " ";
	}
	return str;
}

function addDJ(str) {
	var l = len(str);
	var zl = 8;
	var bl = zl - l;
	for (var i = 0; i < bl; i++) {
		str = " " + str;
	}
	return str;
}

function addZJ(str) {
	var l = len(str);
	var zl = 10;
	var bl = zl - l;
	for (var i = 0; i < bl; i++) {
		str += " ";
	}
	return str;
}

function PrintNameValue(name, value) {
	//AddPrintQueue('InitPos');
	// AddPrintQueue('Bold');
	AddPrintQueue('AlignLeft');
	AddPrintQueue('WriteText', name);
	AddPrintQueue('UnBold');
	AddPrintQueue('AlignLeft');
	AddPrintQueue('Print', value);
	AddPrintQueue('PrintJumpLine', 1);
}


function PrintBigTitle(text) {
	//AddPrintQueue('InitPos');
	AddPrintQueue('Bold');
	AddPrintQueue('FontDouble');
	AddPrintQueue('AlignMiddle');
	AddPrintQueue('Print', text);
	AddPrintQueue('PrintJumpLine', 1);
}


//  pos.PrintTitle(" 超市名(可自定义)");//打印标题
function PrintTitle(text) {
	//AddPrintQueue('InitPos');           // 初始化蓝牙打印机 [27,64]
	AddPrintQueue('Bold'); // 字体加粗       var GS_E_n = new Uint8Array([27, 69, 0]);
	AddPrintQueue('FontHighDouble'); // 字体高度增大
	AddPrintQueue('AlignMiddle'); // 
	AddPrintQueue('Print', text);
	AddPrintQueue('PrintJumpLine', 2);
}



function PrintMiddleTextBold(text) {
	AddPrintQueue('InitPos');
	AddPrintQueue('AlignMiddle');
	AddPrintQueue('Bold');
	AddPrintQueue('Print', text);
	AddPrintQueue('PrintJumpLine', 1);
}

// 打印并向前走纸n行
function PrintJumpLines(n) {
	AddPrintQueue('PrintJumpLine', n);
	//DaYin(function (res) {});
}

function PrintMiddleText(text) {
	//AddPrintQueue('InitPos');
	AddPrintQueue('AlignMiddle');
	AddPrintQueue('Print', text);
	AddPrintQueue
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

韩召华

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值