Skip to content

LimePrinter 打印

  • 使用UTS通过蓝牙、网络、USB连接打印机,向打印机发送打印指令打印(小票、标签),目前只测了安卓蓝牙(TSC)
  • 插件做到蓝牙后,打印机就还回去了没有机会测试网络和USB。如果你有这条件可以完善一下

文档

printer

安装

插件市场入口 导入,引入插件后自定义基座

使用

典型工作流程

初始化 → 搜索设备 → 选择设备 → 连接 → 发送指令 → 打印

蓝牙连接

js
// 1. 引入插件
import { usePrinter,  SearchOption, ConnectOption, PrintOption} from '@/uni_modules/lime-printer'

type Bluetooth = {
	name : string,
	deviceId : string
}

const printer = usePrinter()
const bluetooths = ref<Bluetooth[]>([])
// 2. 初始化蓝牙连接
printer.setUpConnection('bluetooth')

// 3. 搜索设备
const search = () => {
	bluetooths.value = []
	printer.search({
		success: () => console.log('开始搜索'),
		fail: err => console.error('搜索失败', err)
	} as SearchOption)
}

// 4. 监听搜索结果
printer.onSearch((bt) => {
	console.log('发现设备:', device.deviceId);
	const bluetooth:Bluetooth = {
		name : bt.name,
		deviceId : bt.deviceId
	}
	bluetooths.value.push(bluetooth)
})


// 5. 连接打印机(替换为实际设备ID)
const connect = () => {
	printer.connect({
		deviceId: '60:6E:41:96:33:CD',
		success(res) {
			console.log('连接成功')
		},
		fail(err) {
			console.log('连接失败')
		}
	} as ConnectOption)
}

// 6. 发送打印指令
const print = () => {
	//TSC
	printer.print({
		data: "SIZE 40 mm, 30 mm\r\n" +
		"GAP 3 mm, 0 mm\r\n" +
		"DIRECTION 1,0\r\n" +
		"REFERENCE 0,0\r\n" +
		"SET TEAR 1\r\n" +
		"CLS\r\n" +
		"TEXT 20,10, \"test.ttf\",0,1,1,\"first line!\"\r\n" +
		"TEXT 20,51, \"test.ttf\",0,1,1,\"second line!\"\r\n" +
		"TEXT 20,92, \"test.ttf\",0,1,1,\"third line!\"\r\n" +
		"TEXT 20,133, \"test.ttf\",0,1,1,\"firth line!\"\r\n" +
		//"BARCODE 40,165,\"128\",40,1,0,2,2,\"1234567890\"\r\n" +
		"QRCODE 40,165,L, 4, A, 0,\"abcdefg\"\r\n" +
		"PRINT 1,2\r\n"
	} as PrintOption)
}

网络

使用方法同蓝牙一样,未经过测试

js
printer.setUpConnection('net')

USB

使用方法同蓝牙一样,未经过测试

js
printer.setUpConnection('usb')

API

search(option: SearchOption)

功能:扫描周边设备

js
interface SearchOption {
  allowDuplicatesKey?: boolean; // 是否允许重复上报
  interval?: number;           // 上报间隔(ms)
  services?: string[];         // 过滤服务UUID列表
  success?: (res: PrinterError) => void;
  fail?: (res: PrinterError) => void;
  complete?: (res: PrinterError) => void;
}

connect(option: ConnectOption)

功能:连接指定设备

js
interface ConnectOption {
  deviceId?: string;  // 目标设备ID
  autoReconnect?: boolean; // 是否启用自动重连
  maxReconnectAttempts?: number; //最大重连次数(默认3次
  success?: (res: PrinterError) => void;
  fail?: (res: PrinterError) => void;
  complete?: (res: PrinterError) => void;
}
js
printer.connect({
  deviceId: 'XX:XX:XX:XX:XX',
  success: () => {/* 连接成功处理 */}
});

功能:发送打印数据

js
interface PrintOption {
  data: string;  // 要发送的数据
  deviceId?: string;  // 重新连接打印机的ID,如果不设置则默认上次的
  delay?: number;  // 重新连接打印机的间隔
  success?: (res: PrinterError) => void;
  fail?: (res: PrinterError) => void;
  complete?: (res: PrinterError) => void;
}

onSearch

功能:监听扫描到的设备

js
printer.onSearch((device) => {
  console.log(`发现设备 - 名称: ${device.name}, ID: ${device.deviceId}`);
});

stop

功能:停止搜索

disconnect

功能:断开设备

源代码

组件源码