esc_pos_printer

repository·master·Indexed 19 days ago

https://github.com/wwandreww/esc_pos_printer

A Dart and Flutter library for printing receipts on ESC/POS thermal printers via WiFi or Ethernet networks. It supports text styling via PosStyles, image and QR code printing, barcode generation, and hardware controls such as paper cutting and cash drawer triggering. Compatible with Android and iOS in Flutter, and pure Dart projects. Note: This library does not support Bluetooth printers.

Tokens
2.4K
Snippets
8
Records
11
Agent score
64%

What's inside esc_pos_printer

  1. Use esc_pos_printer for WiFi/Ethernet thermal printers

    master

    The esc_pos_printer library is designed for printing receipts using ESC/POS thermal printers connected via WiFi or Ethernet. It is compatible with both Flutter and pure Dart projects (supporting Android and iOS in Flutter).

    Important Notes:

    • Bluetooth Printers: This library does not support Bluetooth. Use the esc_pos_bluetooth library instead.
    • Printer Discovery: To find printers on your network, it is recommended to use the ping_discover_network package. Most ESC/POS printers listen on port 9100 by default.
  2. Connect to a Network Printer

    master

    To print, you must first initialize a NetworkPrinter with a PaperSize and a CapabilityProfile, then connect to the printer's IP address.

    1. Define the PaperSize (e.g., PaperSize.mm80).
    2. Load the CapabilityProfile using await CapabilityProfile.load().
    3. Instantiate NetworkPrinter.
    4. Call printer.connect(ipAddress, port: 9100).
    5. Check the PosPrintResult to ensure the connection was successful before sending print commands.
    6. Always call printer.disconnect() when finished.
    import 'package:esc_pos_printer/esc_pos_printer.dart';
    
    const PaperSize paper = PaperSize.mm80;
    final profile = await CapabilityProfile.load();
    final printer = NetworkPrinter(paper, profile);
    
    final PosPrintResult res = await printer.connect('192.168.0.123', port: 9100);
    
    if (res == PosPrintResult.success) {
      // Call your printing functions here
      printer.disconnect();
    }
    
    print('Print result: ${res.msg}');
  3. Generate a receipt with text styles and formatting

    master

    You can format receipt text using the printer.text() method by passing a PosStyles object.

    Supported Styling Options via PosStyles:

    • bold: Set to true for bold text.
    • reverse: Set to true for reverse video text.
    • underline: Set to true for underlined text.
    • align: Use PosAlign constants (PosAlign.left, PosAlign.center, PosAlign.right).
    • codeTable: Specify a character set (e.g., 'CP1252') for special characters.
    • height & width: Use PosTextSize (e.g., PosTextSize.size2) to scale text size.

    Other Commands:

    • printer.feed(n): Feeds the paper by n lines.
    • printer.cut(): Cuts the paper.
    • linesAfter: An optional parameter in printer.text() to specify how many lines to feed after the text.
    void testReceipt(NetworkPrinter printer) {
      printer.text('Regular text');
      printer.text('Bold text', styles: PosStyles(bold: true));
      printer.text('Reverse text', styles: PosStyles(reverse: true));
      printer.text('Underlined text', styles: PosStyles(underline: true), linesAfter: 1);
      printer.text('Align center', styles: PosStyles(align: PosAlign.center));
      printer.text('Text size 200%',
          styles: PosStyles(
            height: PosTextSize.size2,
            width: PosTextSize.size2,
          ));
    
      printer.feed(2);
      printer.cut();
    }
  4. Review tested WiFi/Ethernet printers

    master

    Before selecting a printer, review the list of tested WiFi/Ethernet models to ensure compatibility with your requirements (e.g., paper width, graphics support, or barcode support).

    Key considerations from the tested list:

    • Epson TM-m30 (Ethernet): No issues found.
    • Elgin i9 (Ethernet): No issues found.
    • Issyzonepos 80mm Wifi Thermal Receipt: Graphics and barcodes tested and working.
    • MUNBYN MU-ITPP047-IT WiFi/Ethernet: Graphics and barcodes tested and working.
    • Star Micronics SP700 / SP742 (Ethernet): Requires DIP switch 4 to be OFF to enable ESC/POS mode. Note that column spacing may need tweaking, font sizes are unavailable, and barcodes are not supported.
    • Xprinter XP-N160I: PosImageFn.graphics does not work, but other functions are tested on Desktop, Android, and iOS.
  5. Handle printing results with PosPrintResult

    master

    The PosPrintResult class is used to evaluate the outcome of printing operations. It provides several static constants representing different success and error states. You can check the result against these constants or use the .msg property to get a human-readable error string.

    if (result == PosPrintResult.success) {
      print('Print successful!');
    } else {
      print('Print failed: ${result.msg}');
    }
  6. Print images and barcodes with NetworkPrinter

    master

    Use the following methods to print graphical content:

    • image(Image imgSrc, {PosAlign align}): Prints a standard image.
    • imageRaster(Image image, {PosAlign align, ...}): Prints an image using raster mode for potentially better density control.
    • barcode(Barcode barcode, {int? width, int? height, BarcodeFont? font, BarcodeText textPos, PosAlign align}): Prints a 1D barcode.
    • qrcode(String text, {PosAlign align, QRSize size, QRCorrection cor}): Prints a QR code.
    // Print a QR Code
    printer.qrcode('https://example.com', align: PosAlign.center);
    
    // Print a Barcode
    printer.barcode(Barcode.code128(), width: 2, height: 50);
  7. Print text and styles with NetworkPrinter

    master

    The NetworkPrinter provides several methods to send commands to the printer. For text, use the text method.

    text parameters:

    • text: The string to print.
    • styles: A PosStyles object for formatting (bold, underline, etc.).
    • linesAfter: Number of empty lines to print after the text.
    • containsChinese: Boolean to enable Chinese character support.
    • maxCharsPerLine: Optional limit for characters per line.

    Other related text methods include:

    • textEncoded: Prints Uint8List bytes as text.
    • setGlobalFont: Sets the default font for the session.
    • setGlobalCodeTable: Sets the global code table.
    printer.text('Hello World', 
      styles: PosStyles(bold: true, align: PosAlign.center),
      linesAfter: 1,
    );
  8. Connect to a network printer using NetworkPrinter

    master

    To use a network ESC/POS printer, instantiate NetworkPrinter with a PaperSize and a CapabilityProfile. Use the connect method to establish a TCP connection to the printer's host and port.

    Parameters:

    • host: The IP address or hostname of the printer.
    • port: The TCP port (defaults to 91000).
    • timeout: The connection timeout duration (defaults to 5 seconds).

    Returns: Returns a Future<PosPrintResult>. Possible values include PosPrintResult.success or PosPrintResult.timeout.

    final printer = NetworkPrinter(PaperSize.mm80, CapabilityProfile.load());
    final result = await printer.connect('192.168.1.100', port: 9100); 
    
    if (result == PosPrintResult.success) {
      // Proceed with printing
    }
  9. Control printer hardware and layout

    master

    Use these methods to manage the physical state and layout of the printed receipt:

    • cut({PosCutMode mode}): Cuts the paper. Default mode is PosCutMode.full.
    • feed(int n): Feeds n lines of paper.
    • reverseFeed(int n): Reverse feeds n lines.
    • emptyLines(int n): Prints n empty lines.
    • hr({String ch, int? len, int linesAfter}): Prints a horizontal rule using character ch.
    • row(List<PosColumn> cols): Prints a row with multiple columns.
    • beep({int n, PosBeepDuration duration}): Triggers the printer's buzzer.
    • drawer({PosDrawer pin}): Opens the cash drawer (e.g., PosDrawer.pin2).
    • reset(): Resets the printer state.
  10. Reference PosPrintResult status codes and messages

    master

    The following status codes are available in PosPrintResult to identify the state of a printing operation:

    // PosPrintResult constants and their corresponding messages:
    // success: 'Success'
    // timeout: 'Error. Printer connection timeout'
    // printerNotSelected: 'Error. Printer not selected'
    // ticketEmpty: 'Error. Ticket is empty'
    // printInProgress: 'Error. Another print in progress'
    // scanInProgress: 'Error. Printer scanning in progress'