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

Android 7.1.1 POS机:能否将PrintJob转Bitmap并传给内置打印机?

解决方案:从PrintJob提取JPEG/PNG并转为Bitmap适配POS打印机

针对Android 7.1.1(API 25)的场景,你可以直接通过PrintDocument的数据流获取应用提交的JPEG/PNG文件,再转换为Bitmap,具体实现如下:

核心步骤

  • 在自定义PrintService中获取打印数据流:在onPrintJobStarted或onPrintJobQueued方法中,通过PrintJob拿到对应的PrintDocument,再调用getData()获取包含JPEG/PNG内容的输入流。
  • 将输入流直接解码为Bitmap:利用BitmapFactory.decodeStream()将输入流转换为Bitmap,无需使用已废弃的ByteBuffer.NEW()写法。
  • 调用POS打印机API打印Bitmap:转换完成后,直接调用你拥有的打印机API处理Bitmap即可。

代码实现示例

@Override
protected void onPrintJobStarted(PrintJob printJob, String reason) {
    super.onPrintJobStarted(printJob, reason);

    PrintDocument printDoc = printJob.getDocument();
    InputStream inputStream = null;

    try {
        inputStream = printDoc.getData();
        if (inputStream == null) {
            printJob.fail("无法获取打印文档数据流");
            return;
        }

        // 将JPEG/PNG流解码为Bitmap
        Bitmap targetBitmap = BitmapFactory.decodeStream(inputStream);
        if (targetBitmap == null) {
            printJob.fail("打印内容无法转换为Bitmap");
            return;
        }

        // 适配热敏打印机分辨率(按需调整,比如384px宽度)
        Bitmap scaledBitmap = Bitmap.createScaledBitmap(targetBitmap, 384, 
            (int) (targetBitmap.getHeight() * 384f / targetBitmap.getWidth()), true);
        
        // 调用你的POS打印机API打印Bitmap
        yourPrinterApi.printBitmap(scaledBitmap);
        
        // 标记打印任务完成
        printJob.complete();
    } catch (IOException e) {
        e.printStackTrace();
        printJob.fail("读取打印数据失败:" + e.getMessage());
    } finally {
        // 关闭流释放资源
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

注意事项

  • 权限与服务注册:确保你的PrintService已在Manifest中正确注册,绑定android.permission.BIND_PRINT_SERVICE权限,并配置对应的print_service_info.xml元数据,保证自定义打印机能被系统识别。
  • Bitmap适配:热敏打印机通常有固定宽度(如384px),建议对转换后的Bitmap进行缩放,避免内容超出打印区域。
  • 异常处理:务必处理流读取、Bitmap解码过程中的异常,及时标记打印任务失败或完成。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 05:55:25