You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter使用esc_pos_bluetooth打印阿拉伯文报错的解决咨询

修复阿拉伯文蓝牙打印错误并实现打印

错误原因

你之前的代码把字符串的codeUnits(UTF-16编码的字符数组)直接当作图片二进制数据传入img.decodeImage,这不是有效的图片格式,导致解码返回null,调用ticket.image(image)时自然会触发width getter的空指针错误。

正确实现思路

要打印阿拉伯文,需要先将文字绘制到图片上(处理从右到左的RTL布局),再把图片转成有效字节传给打印机。

步骤1:添加依赖

确保pubspec.yaml包含必要依赖:

dependencies:
  flutter:
    sdk: flutter
  esc_pos_bluetooth: ^0.2.1 # 替换为最新版本
  image: ^4.0.17 # 替换为最新版本

步骤2:实现文字转图片函数

使用Flutter的Canvas API绘制阿拉伯文,处理RTL布局:

import 'dart:ui' as ui;
import 'dart:typed_data';
import 'package:image/image.dart' as img;

Future<Uint8List> arabicTextToImage(String text) async {
  // 适配打印机纸张宽度(80mm纸宽对应约384像素,可根据你的打印机调整)
  const imgWidth = 384;
  const imgHeight = 80;

  final recorder = ui.PictureRecorder();
  final canvas = ui.Canvas(recorder, ui.Rect.fromLTWH(0, 0, imgWidth.toDouble(), imgHeight.toDouble()));

  // 设置文字样式,确保使用支持阿拉伯文的字体
  final textStyle = ui.TextStyle(
    color: ui.Color(0xFF000000),
    fontSize: 24,
    // 若需自定义字体,先在pubspec.yaml导入,再指定fontFamily
    // fontFamily: 'Amiri',
  );

  // 配置文本绘制器,启用RTL方向
  final textPainter = ui.TextPainter(
    text: ui.TextSpan(text: text, style: textStyle),
    textDirection: ui.TextDirection.rtl,
    textAlign: ui.TextAlign.right,
  )..layout(minWidth: imgWidth.toDouble(), maxWidth: imgWidth.toDouble());

  // 将文本绘制到画布居中位置
  final offsetX = (imgWidth - textPainter.width) / 2;
  final offsetY = (imgHeight - textPainter.height) / 2;
  textPainter.paint(canvas, ui.Offset(offsetX, offsetY));

  // 生成图片并转成PNG字节
  final picture = recorder.endRecording();
  final image = await picture.toImage(imgWidth, imgHeight);
  final byteData = await image.toByteData(format: ui.ImageByteFormat.png);

  return byteData!.buffer.asUint8List();
}

步骤3:在打印流程中调用

// 假设你已获取到BluetoothPrinter和Ticket对象
final description = "النص العربي المطلوب الطباعة"; // 阿拉伯文示例
final imageBytes = await arabicTextToImage(description);
final image = img.decodeImage(imageBytes);

if (image != null) {
  ticket.image(image);
  // 执行打印
  await printer.printTicket(ticket);
} else {
  print("图片生成失败");
}

注意事项

  • 字体支持:确保设备安装了支持阿拉伯文的系统字体,或在项目中导入自定义阿拉伯字体(如Amiri、Scheherazade),并在pubspec.yaml中配置:
    fonts:
      - family: Amiri
        fonts:
          - asset: fonts/Amiri-Regular.ttf
    
  • 尺寸适配:根据打印机纸张宽度调整图片宽度,避免打印内容被截断。
  • RTL布局:必须设置textDirection: ui.TextDirection.rtl,否则阿拉伯文字会显示错乱。

内容的提问来源于stack exchange,提问作者Sibi Kumar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 04:46:46