1.佳博打印js copy到项目里
2.需要打印的vue页面引入js

var app = getApp();
var esc = require("@/viewsA/pages/qualityTest/js/esc.js");
var encode = require("@/viewsA/pages/qualityTest/js/encoding.js");

3.打印数据初始化

onLoad() {
//放data会报错,所以需要在写this.setData方法初始化
	this.setData({
	  buffSize: list,
	  oneTimeData: list[0],
	  printNum: numList,
	  printerNum: 2
	})
}

4.打印按钮事件

//先判断是否链接打印蓝牙
if(!app.$vm.BLEInformation.deviceId){
	uni.showModal({
		title: '提示',
		content: '打印机未连接,请前往连接',
		confirmText: '前往',
		success(res) {
			if (res.confirm) {
				//无连接跳转链接页面链接
				uni.navigateTo({
					url:'/viewsA/pages/qualityTest/bleConner'
				})
			} else if (res.cancel) {
	  
			}
		}
	})
}else{
	//已连接在做链接处理
	this.receiptTest();
}

蓝牙列表连接页面

<template>
	<view class="bleConner">
		<button class="button" hover-class="hover" @click="startSearch" :loading="isScanning">搜索蓝牙设备</button>
		<text class=".td">(Android8.0+系统需开启定位)</text>
		<scroll-view v-if="list.length > 0" class="device_list" scroll-y scroll-with-animation>
			<view
				v-for="item in list"
				:data-title="item.deviceId"
				:data-name="item.name"
				:data-advertisData="item.advertisServiceUUIDs"
				:key="item.deviceId"
				@click="bindViewTap"
				class="item"
				hover-class="item_hover"
				
			>
				<view>{{ item.name }}</view>
			</view>
		</scroll-view>
		<view v-else class="noList">请检查打印机设备是否开机</view>
	</view>
</template>

<script>
var app = getApp();
export default {
	data() {
		return {
			list: [],
			services: [],
			serviceId: 0,
			writeCharacter: false,
			readCharacter: false,
			notifyCharacter: false,
			isScanning: false
		};
	},
	onLoad() {
		app.$vm.BLEInformation.platform = app.getPlatform();
	},
	methods: {
		//搜索设备
		startSearch: function() {
			var that = this;
			wx.openBluetoothAdapter({
				success: function(res) {
					wx.getBluetoothAdapterState({
						success: function(res) {
							console.log('openBluetoothAdapter success', res);
							if (res.available) {
								if (res.discovering) {
									wx.stopBluetoothDevicesDiscovery({
										success: function(res) {
											console.log(res);
										}
									});
								} else {
									// that.startBluetoothDevicesDiscovery()
									that.getBluetoothDevices();
								}
								// that.checkPemission()
							} else {
								wx.showModal({
									title: '提示',
									content: '本机蓝牙不可用',
									showCancel: false
								});
							}
						}
					});
				},
				fail: function() {
					// if (res.errCode === 10001) {
					//   wx.onBluetoothAdapterStateChange(function (res) {
					//     console.log('onBluetoothAdapterStateChange', res)
					//     if (res.available) {
					//       this.startBluetoothDevicesDiscovery()
					//     }
					//   })
					// }

					wx.showModal({
						title: '提示',
						content: '蓝牙初始化失败,请到设置打开蓝牙',
						showCancel: false
					});
				}
			});
		},
		checkPemission: function() {
			//android 6.0以上需授权地理位置权限
			var that = this;
			var platform = app.$vm.BLEInformation.platform;
			if (platform == 'ios') {
				app.globalData.platform = 'ios';
				that.getBluetoothDevices();
			} else if (platform == 'android') {
				app.globalData.platform = 'android';
				console.log(app.getSystem().substring(app.getSystem().length - (app.getSystem().length - 8), app.getSystem().length - (app.getSystem().length - 8) + 1));
				if (app.getSystem().substring(app.getSystem().length - (app.getSystem().length - 8), app.getSystem().length - (app.getSystem().length - 8) + 1) > 5) {
					wx.getSetting({
						success: function(res) {
							console.log(res);
							if (!res.authSetting['scope.userLocation']) {
								wx.authorize({
									scope: 'scope.userLocation',
									complete: function(res) {
										that.getBluetoothDevices();
									}
								});
							} else {
								that.getBluetoothDevices();
							}
						}
					});
				}
			}
		},
		getBluetoothDevices: function() {
			//获取蓝牙设备信息
			var that = this;
			console.log('start search');
			wx.showLoading({
				title: '正在加载',
				icon: 'loading'
			});
			that.setData({
				isScanning: true
			});
			wx.startBluetoothDevicesDiscovery({
				// services: ['E7810A71-73AE-499D-8C15-FAA9AEF0C3F2'],
				// E7810A71-73AE-499D-8C15-FAA9AEF0C3F2
				success: function(res) {
					console.log(res);
					setTimeout(function() {
						wx.getBluetoothDevices({
							success: function(res) {
								console.log(res)
								var devices = [];
								var num = 0;
								for (var i = 0; i < res.devices.length; ++i) {
									if (res.devices[i].name != '未知设备') {
										devices[num] = res.devices[i];
										num++;
									}
								}
								that.setData({
									list: devices,
									isScanning: false
								});
								wx.hideLoading();
								wx.stopPullDownRefresh();
								wx.stopBluetoothDevicesDiscovery({
									success: function(res) {
										console.log('停止搜索蓝牙');
									}
								});
							}
						});
					}, 5000);
				}
			});
		},
		bindViewTap: function(e) {
			var that = this;
			wx.stopBluetoothDevicesDiscovery({
				success: function(res) {
					console.log(res);
				}
			});
			that.setData({
				serviceId: 0,
				writeCharacter: false,
				readCharacter: false,
				notifyCharacter: false
			});
			console.log(e.currentTarget.dataset.title);
			wx.showLoading({
				title: '正在连接'
			});
			wx.createBLEConnection({
				deviceId: e.currentTarget.dataset.title,
				success: function(res) {
					console.log(res);
					app.$vm.BLEInformation.deviceId = e.currentTarget.dataset.title;
					that.getSeviceId();
				},
				fail: function(e) {
					wx.showModal({
						title: '提示',
						content: '连接失败',
						showCancel: false
					});
					console.log(e);
					wx.hideLoading();
				},
				complete: function(e) {
					console.log(e);
				}
			});
		},
		getSeviceId: function() {
			var that = this;
			var platform = app.$vm.BLEInformation.platform;
			console.log(app.$vm.BLEInformation.deviceId);
			wx.getBLEDeviceServices({
				deviceId: app.$vm.BLEInformation.deviceId,
				success: function(res) {
					console.log(res);
					// var realId = ''
					// if (platform == 'android') {
					//   // for(var i=0;i<res.services.length;++i){
					//   // var item = res.services[i].uuid
					//   // if (item == "0000FEE7-0000-1000-8000-00805F9B34FB"){
					//   realId = "0000FEE7-0000-1000-8000-00805F9B34FB"
					//   //       break;
					//   //     }
					//   // }
					// } else if (platform == 'ios') {
					//   // for(var i=0;i<res.services.length;++i){
					//   // var item = res.services[i].uuid
					//   // if (item == "49535343-FE7D-4AE5-8FA9-9FAFD205E455"){
					//   realId = "49535343-FE7D-4AE5-8FA9-9FAFD205E455"
					//   // break
					//   // }
					//   // }
					// }
					// app.$vm.BLEInformation.serviceId = realId
					that.setData({
						services: res.services
					});
					that.getCharacteristics();
				},
				fail: function(e) {
					console.log(e);
				},
				complete: function(e) {
					console.log(e);
				}
			});
		},
		getCharacteristics: function() {
			var that = this;
			var list = that.services;
			var num = that.serviceId;
			var write = that.writeCharacter;
			var read = that.readCharacter;
			var notify = that.notifyCharacter;
			wx.getBLEDeviceCharacteristics({
				deviceId: app.$vm.BLEInformation.deviceId,
				serviceId: list[num].uuid,
				success: function(res) {
					console.log(res);
					for (var i = 0; i < res.characteristics.length; ++i) {
						var properties = res.characteristics[i].properties;
						var item = res.characteristics[i].uuid;
						if (!notify) {
							if (properties.notify) {
								app.$vm.BLEInformation.notifyCharaterId = item;
								app.$vm.BLEInformation.notifyServiceId = list[num].uuid;
								notify = true;
							}
						}
						if (!write) {
							if (properties.write) {
								app.$vm.BLEInformation.writeCharaterId = item;
								app.$vm.BLEInformation.writeServiceId = list[num].uuid;
								write = true;
							}
						}
						if (!read) {
							if (properties.read) {
								app.$vm.BLEInformation.readCharaterId = item;
								app.$vm.BLEInformation.readServiceId = list[num].uuid;
								read = true;
							}
						}
					}
					if (!write || !notify || !read) {
						num++;
						that.setData({
							writeCharacter: write,
							readCharacter: read,
							notifyCharacter: notify,
							serviceId: num
						});
						if (num == list.length) {
							wx.showModal({
								title: '提示',
								content: '找不到该读写的特征值',
								showCancel: false
							});
						} else {
							that.getCharacteristics();
						}
					} else {
						wx.showToast({
							title: '连接成功'
						});
						that.openControl();
					}
				},
				fail: function(e) {
					console.log(e);
				},
				complete: function(e) {
					console.log('write:' + app.$vm.BLEInformation.writeCharaterId);
					console.log('read:' + app.$vm.BLEInformation.readCharaterId);
					console.log('notify:' + app.$vm.BLEInformation.notifyCharaterId);
				}
			});
		},
		openControl: function() {
			//连接成功返回主页
			uni.navigateBack();
		},
		setData: function(obj) {
			let that = this;
			let keys = [];
			let val, data;
			Object.keys(obj).forEach(function(key) {
				keys = key.split('.');
				val = obj[key];
				data = that.$data;
				keys.forEach(function(key2, index) {
					if (index + 1 == keys.length) {
						that.$set(data, key2, val);
					} else {
						if (!data[key2]) {
							that.$set(data, key2, {});
						}
					}
					data = data[key2];
				});
			});
		}
	}
};
</script>

<style lang="scss" scoped>
.bleConner {
	.button {
		margin-top: 20px;
		width: 90%;
		background: #456ae8;
		color: white;
		border-radius: 10rpx;
		font-size: 32upx;
		font-weight: 700;
		color: #ffffff;
		height: 96upx;
		line-height: 96upx;
	}

	/* 按下变颜色 */
	.hover {
		background: #dcdcdc;
	}
	.td {
		display: flex;
		align-items: center;
		justify-content: center;
		margin-top: 24upx;
		color: #7E7E8F;
		font-size: 24upx;
	}
	.device_list {
		height: auto;
		margin: 24rpx;
		border: 1upx solid #f4f4f4;
		border-radius: 10upx;
		width: auto;
	}
	.item {
		display: block;
		border-bottom: 1px solid #F4F4F4;
		padding: 24upx;
		color: #39394F;
	}
	.item_hover {
		background-color: rgba(0, 0, 0, 0.1);
	}
	.noList{
		display: flex;
		align-items: center;
		justify-content: center;
		margin-top: 24upx;
		color: #7E7E8F;
		font-size: 24upx;
	}
}
</style>

已连接处打印方法

receiptTest() { //票据测试
	var that = this;
	var canvasWidth = that.canvasWidth
	var canvasHeight = that.canvasHeight
	var command = esc.jpPrinter.createNew()
	command.init() //初始化打印机
	command.setCutter();
	// 标题
	command.setSelectJustification(0);
	command.setCharacterSize(17); //设置倍高倍宽
	command.setText("大洋智慧快检收费单");
	command.setPrint(); //打印并换行
	command.setPrint(); //打印并换行
	// 虚线
	command.setCharacterSize(0); //设置倍高倍宽
	command.setSelectJustification(0)
	command.setText("----------------------------------------------");
	command.setPrint() //打印并换行
	command.setPrint() //打印并换行
	// 订单号
	command.setSelectJustification(0)
	command.setText("订单号:");
	command.setAbsolutePrintPosition(158);
	command.setText(that.orderInfo.order_no);
    command.setPrint() //打印并换行
	command.setPrint() //打印并换行
	// 车牌号
	command.setSelectJustification(0)
	command.setText("车牌号:");
	command.setAbsolutePrintPosition(158);
	command.setText(that.submission_goods_car_number);
	command.setPrint() //打印并换行
	command.setPrint() //打印并换行
	// 检测商品
	command.setSelectJustification(0)
	command.setText("检测商品:");
	command.setAbsolutePrintPosition(158);
	// command.setText('#' + that.testDetail.day_num + that.testDetail.submission_goods_name);
	command.setText(that.printGoodsName);
	command.setPrint() //打印并换行
	command.setPrint() //打印并换行
	// 支付方式
	command.setSelectJustification(0)
	command.setText("支付方式:");
	command.setAbsolutePrintPosition(158);
	command.setText(that.payType);
	command.setPrint() //打印并换行
	command.setPrint() //打印并换行
	// 支付时间
	command.setSelectJustification(0)
	command.setText("支付时间:");
	command.setAbsolutePrintPosition(158);
	command.setText(that.testDetail.pay_time);
	command.setPrint() //打印并换行
	command.setPrint() //打印并换行
	// 支付金额
	command.setSelectJustification(0)
	command.setText("支付金额:");
	command.setAbsolutePrintPosition(158);
	command.setCharacterSize(17); //设置倍高倍宽
	// command.setText("RMB "+that.testDetail.price);
	command.setText("RMB "+that.printPrice);
	command.setPrint() //打印并换行
	command.setPrint() //打印并换行
	// 虚线
	command.setCharacterSize(0); //设置倍高倍宽
	command.setSelectJustification(0)
	command.setText("----------------------------------------------");
	command.setPrint() //打印并换行
	command.setPrint() //打印并换行
	// 送检人签名
	command.setSelectJustification(0)
	command.setText("送检人签名:");
	command.setPrint() //打印并换行
	command.setPrint() //打印并换行
	// 虚线
	command.setSelectJustification(0)
	command.setText("----------------------------------------------");
	command.setPrint() //打印并换行
	command.setPrint() //打印并换行
	// 开票员 开票时间
	command.setSelectJustification(0)
	command.setText("开票员:" + that.adminName);
	command.setAbsolutePrintPosition(220);
	command.setText("开票时间:" + that.printTime);
	command.setPrint() //打印并换行
	command.setPrint() //打印并换行
	// 北京大洋路农副产品有限公司
	command.setSelectJustification(0)
	command.setText("北京大洋路农副产品有限公司");
	command.setPrint() //打印并换行
	command.setPrint()
	command.setPrint()
	command.setPrint()
	command.setPrint()
	command.setCutter();
	// 调用出票接口
	let idStr = '';
	if(that.payType == '现金支付'){
		if(that.selCashList.length > 0){
			idStr = that.selCashList.map(item=> item.check_object_id).join(",");
		}else{
			idStr = that.testDetail.check_object_id;
		}
	}
	if(that.payType == '线上支付'){
		idStr = that.payList.map(item=> item.check_object_id).join(",");
	}
	let data = {
		check_object_ids : idStr
	}
	API.printMore(data).then(res => {
		if (res.status == 200) {
			
		} else {
			
		}
	})
	that.prepareSend(command.getData())//准备发送数据
},

prepareSend: function(buff) { //准备发送,根据每次发送字节数来处理分包数量
  //console.log(buff)
  var that = this
  var time = that.oneTimeData
  var looptime = parseInt(buff.length / time);
  var lastData = parseInt(buff.length % time);
  //console.log(looptime + "---" + lastData)
  that.setData({
    looptime: looptime + 1,
    lastData: lastData,
    currentTime: 1,
  })
  that.Send(buff)
},
Send: function(buff) { //分包发送
	var that = this
	var currentTime = that.currentTime
	var loopTime = that.looptime
	var lastData = that.lastData
	var onTimeData = that.oneTimeData
	var printNum = that.printerNum
	var currentPrint = that.currentPrint
	var buf
	var dataView
	if (currentTime < loopTime) {
		buf = new ArrayBuffer(onTimeData)
		dataView = new DataView(buf)
		for (var i = 0; i < onTimeData; ++i) {
			dataView.setUint8(i, buff[(currentTime - 1) * onTimeData + i])
		}
	} else {
		buf = new ArrayBuffer(lastData)
		dataView = new DataView(buf)
		for (var i = 0; i < lastData; ++i) {
			dataView.setUint8(i, buff[(currentTime - 1) * onTimeData + i])
		}
	}
	wx.writeBLECharacteristicValue({
		deviceId: app.$vm.BLEInformation.deviceId,
		serviceId: app.$vm.BLEInformation.writeServiceId,
		characteristicId: app.$vm.BLEInformation.writeCharaterId,
		value: buf,
		success: function(res) {
			
			if (currentTime <= loopTime) {
				// wx.showLoading({
				//   title: '传输中...',
				// })
			} else {
				wx.showToast({
				  title: '已打印第' + currentPrint + '张成功',
				})
			}
			//console.log(res)
		},
		fail: function(e) {
			wx.showToast({
			  title: '打印第' + currentPrint + '张失败',
			  icon: 'none',
			})
			
			//console.log(e)
		},
		complete: function() {
			currentTime++
			if (currentTime <= loopTime) {
				that.setData({
					currentTime: currentTime
				})
				that.Send(buff)
			} else {
				if (currentPrint == printNum) {
					that.setData({
						looptime: 0,
						lastData: 0,
						currentTime: 1,
						isReceiptSend: false,
						currentPrint: 1
					})
				} else {
					currentPrint++
					that.setData({
						currentPrint: currentPrint,
						currentTime: 1,
					})
					that.Send(buff)
				}
			}
		}
	})
},
setData: function(obj) {
	let that = this;
	let keys = [];
	let val, data;
	Object.keys(obj).forEach(function(key) {
		keys = key.split(".");
		val = obj[key];
		data = that.$data;
		keys.forEach(function(key2, index) {
			if (index + 1 == keys.length) {
				that.$set(data, key2, val);
			} else {
				if (!data[key2]) {
				that.$set(data, key2, {});
				}
			}
		  data = data[key2];
		});
	});
},
Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐