Boby
Boby

Reputation: 1202

How to Print PDF to Thermal Printer Using Flutter? 'byte[] cannot be cast to java.util.List' Error

I'm trying to print a PDF file to a thermal printer in my Flutter application using the print_bluetooth_thermal package. Here's what I've implemented so far:

1. Downloading

static Future<void> downloadFile(String url) async {
  try {
    final savePath = await getTemporaryDirectory();
    final fileName = url.split('/').last;
    final filePath = '${savePath.path}/$fileName';

    // Download the file
    await dio.download(url, filePath);

    // Retrieve the print controller and print the downloaded file
    PrintController printController = Get.find();
    await printController.printTicket(File(filePath));
  } catch (error) {
    print('Error downloading file: $error');
  }
}

2. Print Method:

Future<void> printTicket(File file) async {
  try {
    String enter = '\n';
    await PrintBluetoothThermal.writeBytes(enter.codeUnits);
    List<int> bytes = file.readAsBytesSync();
    await PrintBluetoothThermal.writeBytes(bytes);

    // Delete file after printing
    file.delete();
  } catch (e) {
    // Delete file if any error occurs
    file.delete();
  }
}

When trying to print the downloaded PDF file and try to print it, I encounter the following error:

[  +29 ms] E/MethodChannel#groons.web.app/print(13896): Failed to handle method call
[        ] E/MethodChannel#groons.web.app/print(13896): java.lang.ClassCastException: byte[] cannot be cast to java.util.List
[        ] E/MethodChannel#groons.web.app/print(13896):         at app.web.groons.print_bluetooth_thermal.PrintBluetoothThermalPlugin.onMethodCall(PrintBluetoothThermalPlugin.kt:156)
...
[        ] I/flutter (13896): Failed to write bytes: 'byte[] cannot be cast to java.util.List'.

I'm trying another way. I'm trying to convert the PDF to image first.

  Future<void> printPdfAsImage(File pdfFile) async {
    //check if file exists
    if (!pdfFile.existsSync()) {
      print('File does not exist');
      return;
    }
    final pdfBytes = pdfFile.readAsBytesSync();
    final pages =
        Printing.raster(pdfBytes, dpi: 203); // Adjust DPI based on your printer
    await for (final page in pages) {
      final image = await page.toImage();
      final byteData = await image.toByteData(format: ui.ImageByteFormat.png);
      final bytes = byteData!.buffer.asUint8List();
      bool conexionStatus = await PrintBluetoothThermal.connectionStatus;
      if (conexionStatus) {
        List<int> ticket = bytes;

        final result = await PrintBluetoothThermal.writeBytes(ticket);
        print("print result: $result");
      } else {
        print("the printer is disconnected ($conexionStatus)");
      }
    }
  }

But still no luck. So, how can i achieve print pdf (receipt) to thermal printer.

Upvotes: 0

Views: 82

Answers (0)

Related Questions