Flutter热敏打印机控制插件pb_thermal_printers的使用
Flutter热敏打印机控制插件pb_thermal_printers的使用
包用于在58mm或80mm热敏打印机上打印票据或PDF(适用于Android或iOS)
此包作为当前使用位置权限并被Google Play阻止的应用程序的替代方案而出现。
如果您想提供C++代码,您需要接收原始字节以使用字节类。
开始使用
导入包
import 'package:pb_thermal_printers/pb_thermal_printers.dart';
iOS配置
在Info.plist文件中添加以下行:
<key>NSBluetoothAlwaysUsageDescription</key>
<string>蓝牙访问以连接58mm或80mm热敏打印机</string>
可用函数
命令 | 描述 |
---|---|
PrintBluetoothThermal.isPermissionBluetoothGranted |
如果启用了BLUETOOTH_CONNECT权限,则返回true,从Android 12开始才需要该权限 |
PrintBluetoothThermal.bluetoothEnabled |
如果蓝牙已开启,则返回true |
PrintBluetoothThermal.pairedBluetooths |
Android: 返回设备上的所有配对蓝牙设备;iOS: 返回附近的蓝牙设备 |
PrintBluetoothThermal.connectionStatus |
如果当前连接到打印机,则返回true |
PrintBluetoothThermal.connect |
发送连接到票据打印机的请求,并等待成功,需要发送打印机蓝牙的MAC地址 |
PrintBluetoothThermal.writeBytes |
发送字节进行打印,需要使用esc_pos_utils_plus 包,如果成功则返回true |
PrintBluetoothThermal.writeString |
发送字符串进行打印,PrintTextSize 类可以打印从大小1(50%)到大小5(400%)的文字 |
PrintBluetoothThermal.disconnect |
断开打印连接 |
PrintBluetoothThermal.platformVersion |
获取运行时的Android版本,返回字符串 |
PrintBluetoothThermal.batteryLevel |
获取电池电量百分比,返回整数 |
各平台可用命令
函数 | Android | iOS | Windows |
---|---|---|---|
PrintBluetoothThermal.isPermissionBluetoothGranted |
✅ | ✅ | ❌ |
PrintBluetoothThermal.bluetoothEnabled |
✅ | ✅ | ❌ |
PrintBluetoothThermal.pairedBluetooths |
✅ | ✅ | ✅ |
PrintBluetoothThermal.connectionStatus |
✅ | ✅ | ✅ |
PrintBluetoothThermal.connect |
✅ | ✅ | ✅ |
PrintBluetoothThermal.writeBytes |
✅ | ✅ | ✅ |
PrintBluetoothThermal.writeString |
✅ | ✅ | ❌ |
PrintBluetoothThermal.disconnect |
✅ | ✅ | ✅ |
PrintBluetoothThermal.platformVersion |
✅ | ✅ | ❌ |
PrintBluetoothThermal.batteryLevel |
✅ | ✅ | ❌ |
示例
检测蓝牙是否开启
final bool result = await PrintBluetoothThermal.bluetoothEnabled;
读取配对的蓝牙设备
final List<BluetoothInfo> listResult = await PrintBluetoothThermal.pairedBluetooths;
await Future.forEach(listResult, (BluetoothInfo bluetooth) {
String name = bluetooth.name;
String mac = bluetooth.macAdress;
});
连接打印机
String mac = "66:02:BD:06:18:7B";
final bool result = await PrintBluetoothThermal.connect(macPrinterAddress: mac);
断开打印机连接
final bool result = await PrintBluetoothThermal.disconnect;
检测连接状态
final bool connectionStatus = await PrintBluetoothThermal.connectionStatus;
打印不同大小的文字
bool conexionStatus = await PrintBluetoothThermal.connectionStatus;
if (conexionStatus) {
String enter = '\n';
await PrintBluetoothThermal.writeBytes(enter.codeUnits);
// 文字大小为1-5
String text = "Hello $enter";
await PrintBluetoothThermal.writeString(printText: PrintTextSize(size: 1, text: text + " size 1"));
await PrintBluetoothThermal.writeString(printText: PrintTextSize(size: 2, text: text + " size 2"));
await PrintBluetoothThermal.writeString(printText: PrintTextSize(size: 3, text: text + " size 3"));
await PrintBluetoothThermal.writeString(printText: PrintTextSize(size: 2, text: text + " size 4"));
await PrintBluetoothThermal.writeString(printText: PrintTextSize(size: 3, text: text + " size 5"));
} else {
print("打印机未连接 ($conexionStatus)");
}
使用esc_pos_utils_plus
包在打印机上打印
Future<void> printTest() async {
bool conecctionStatus = await PrintBluetoothThermal.connectionStatus;
if (conecctionStatus) {
List<int> ticket = await testTicket();
final result = await PrintBluetoothThermal.writeBytes(ticket);
print("打印结果: $result");
} else {
// 未连接
}
}
Future<List<int>> testTicket() async {
List<int> bytes = [];
// 使用默认配置文件
final profile = await CapabilityProfile.load();
final generator = Generator(PaperSize.mm58, profile);
bytes += generator.reset();
final ByteData data = await rootBundle.load('assets/mylogo.jpg');
final Uint8List bytesImg = data.buffer.asUint8List();
final image = img.decodeImage(bytesImg);
bytes += generator.image(image!);
bytes += generator.text('Regular: aA bB cC dD eE fF gG hH iI jJ kK lL mM nN oO pP qQ rR sS tT uU vV wW xX yY zZ', styles: PosStyles());
bytes += generator.text('Special 1: ñÑ àÀ èÈ éÉ üÜ çÇ ôÔ', styles: PosStyles(codeTable: 'CP1252'));
bytes += generator.text('Special 2: blåbærgrød', styles: PosStyles(codeTable: 'CP1252'));
bytes += generator.text('Bold text', styles: PosStyles(bold: true));
bytes += generator.text('Reverse text', styles: PosStyles(reverse: true));
bytes += generator.text('Underlined text', styles: PosStyles(underline: true), linesAfter: 1);
bytes += generator.text('Align left', styles: PosStyles(align: PosAlign.left));
bytes += generator.text('Align center', styles: PosStyles(align: PosAlign.center));
bytes += generator.text('Align right', styles: PosStyles(align: PosAlign.right), linesAfter: 1);
bytes += generator.row([
PosColumn(
text: 'col3',
width: 3,
styles: PosStyles(align: PosAlign.center, underline: true),
),
PosColumn(
text: 'col6',
width: 6,
styles: PosStyles(align: PosAlign.center, underline: true),
),
PosColumn(
text: 'col3',
width: 3,
styles: PosStyles(align: PosAlign.center, underline: true),
),
]);
final List<int> barData = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 4];
bytes += generator.barcode(Barcode.upcA(barData));
bytes += generator.qrcode('example.com');
bytes += generator.text('Text size 50%', styles: PosStyles(fontType: PosFontType.fontB));
bytes += generator.text('Text size 100%', styles: PosStyles(fontType: PosFontType.fontA));
bytes += generator.text('Text size 200%', styles: PosStyles(height: PosTextSize.size2, width: PosTextSize.size2));
bytes += generator.feed(2);
return bytes;
}
更多关于Flutter热敏打印机控制插件pb_thermal_printers的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter热敏打印机控制插件pb_thermal_printers的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
pb_thermal_printers
是一个用于在 Flutter 应用中控制热敏打印机的插件。通过这个插件,你可以连接并控制热敏打印机,打印文本、图像等内容。以下是如何使用 pb_thermal_printers
插件的基本步骤:
1. 添加依赖
首先,在你的 pubspec.yaml
文件中添加 pb_thermal_printers
插件的依赖:
dependencies:
flutter:
sdk: flutter
pb_thermal_printers: ^1.0.0 # 请确保使用最新的版本
然后运行 flutter pub get
来获取依赖。
2. 导入插件
在你的 Dart 文件中导入 pb_thermal_printers
插件:
import 'package:pb_thermal_printers/pb_thermal_printers.dart';
3. 初始化插件
在使用插件之前,你需要初始化它:
void initPrinter() async {
await PbThermalPrinters.init();
}
4. 搜索并连接打印机
你可以通过蓝牙或 USB 连接打印机。以下是使用蓝牙连接打印机的示例:
void searchAndConnectPrinter() async {
List<BluetoothDevice> devices = await PbThermalPrinters.getBluetoothDevices();
if (devices.isNotEmpty) {
BluetoothDevice printer = devices.first; // 选择第一个设备
bool isConnected = await PbThermalPrinters.connect(printer);
if (isConnected) {
print("Printer connected successfully!");
} else {
print("Failed to connect to the printer.");
}
} else {
print("No Bluetooth devices found.");
}
}
5. 打印内容
连接打印机后,你可以开始打印内容。以下是一些常见的打印操作:
打印文本
void printText() async {
await PbThermalPrinters.printText("Hello, World!");
}
打印图像
void printImage() async {
Uint8List imageBytes = await _loadImageFromAsset('assets/logo.png');
await PbThermalPrinters.printImage(imageBytes);
}
Future<Uint8List> _loadImageFromAsset(String path) async {
ByteData data = await rootBundle.load(path);
return data.buffer.asUint8List();
}
6. 断开连接
打印完成后,记得断开与打印机的连接:
void disconnectPrinter() async {
await PbThermalPrinters.disconnect();
}
7. 处理权限
在使用蓝牙功能时,你可能需要请求相关权限。确保在 AndroidManifest.xml
和 Info.plist
中添加必要的权限。
Android
在 AndroidManifest.xml
中添加以下权限:
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
iOS
在 Info.plist
中添加以下权限:
<key>NSBluetoothAlwaysUsageDescription</key>
<string>We need access to Bluetooth to connect to the printer.</string>
<key>NSBluetoothPeripheralUsageDescription</key>
<string>We need access to Bluetooth to connect to the printer.</string>
8. 示例代码
以下是一个完整的示例代码,展示了如何使用 pb_thermal_printers
插件连接蓝牙打印机并打印文本和图像:
import 'package:flutter/material.dart';
import 'package:pb_thermal_printers/pb_thermal_printers.dart';
import 'dart:typed_data';
import 'package:flutter/services.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
[@override](/user/override)
Widget build(BuildContext context) {
return MaterialApp(
home: PrinterScreen(),
);
}
}
class PrinterScreen extends StatefulWidget {
[@override](/user/override)
_PrinterScreenState createState() => _PrinterScreenState();
}
class _PrinterScreenState extends State<PrinterScreen> {
[@override](/user/override)
void initState() {
super.initState();
initPrinter();
}
void initPrinter() async {
await PbThermalPrinters.init();
}
void searchAndConnectPrinter() async {
List<BluetoothDevice> devices = await PbThermalPrinters.getBluetoothDevices();
if (devices.isNotEmpty) {
BluetoothDevice printer = devices.first;
bool isConnected = await PbThermalPrinters.connect(printer);
if (isConnected) {
print("Printer connected successfully!");
} else {
print("Failed to connect to the printer.");
}
} else {
print("No Bluetooth devices found.");
}
}
void printText() async {
await PbThermalPrinters.printText("Hello, World!");
}
void printImage() async {
Uint8List imageBytes = await _loadImageFromAsset('assets/logo.png');
await PbThermalPrinters.printImage(imageBytes);
}
Future<Uint8List> _loadImageFromAsset(String path) async {
ByteData data = await rootBundle.load(path);
return data.buffer.asUint8List();
}
void disconnectPrinter() async {
await PbThermalPrinters.disconnect();
}
[@override](/user/override)
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Thermal Printer Example'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
ElevatedButton(
onPressed: searchAndConnectPrinter,
child: Text('Connect Printer'),
),
ElevatedButton(
onPressed: printText,
child: Text('Print Text'),
),
ElevatedButton(
onPressed: printImage,
child: Text('Print Image'),
),
ElevatedButton(
onPressed: disconnectPrinter,
child: Text('Disconnect Printer'),
),
],
),
),
);
}
}