printCenteredText static method

Future<bool> printCenteredText({
  1. required String text,
  2. String fontFamily = 'Siemreap',
  3. double fontSize = 24,
  4. FontWeight fontWeight = FontWeight.normal,
  5. Color color = Colors.black,
  6. int? printerWidth,
})

Print centered text.

Creates an image with the text centered and prints it.

  • text: The text to print
  • fontFamily: Font family to use
  • fontSize: Font size in points
  • fontWeight: Font weight (normal, bold, etc.)
  • color: Text color
  • printerWidth: Printer width in dots (if null, uses printer default)

Returns true if printing was successful.

Implementation

static Future<bool> printCenteredText({
  required String text,
  String fontFamily = 'Siemreap',
  double fontSize = 24,
  FontWeight fontWeight = FontWeight.normal,
  Color color = Colors.black,
  int? printerWidth,
}) async {
  try {
    final directory = await getTemporaryDirectory();
    final tempPath =
        '${directory.path}/centered_text_${DateTime.now().millisecondsSinceEpoch}.png';

    // Create recorder and canvas
    final recorder = PictureRecorder();
    final canvas = Canvas(recorder);

    // Create text painter to measure the text
    final textSpan = TextSpan(
      text: text,
      style: TextStyle(
        fontFamily: fontFamily,
        fontSize: fontSize,
        fontWeight: fontWeight,
        color: color,
      ),
    );

    final textPainter = TextPainter(
      text: textSpan,
      textAlign: TextAlign.center,
      textDirection: TextDirection.ltr,
    );

    // First layout without constraints to get natural size
    textPainter.layout();

    // Determine image dimensions
    final width =
        printerWidth ?? 576; // Default printer width if not specified
    final double padding = 10;
    final double textHeight = textPainter.height;
    final double imageHeight = textHeight + (padding * 2);

    // Draw white background
    canvas.drawRect(
      Rect.fromLTWH(0, 0, width.toDouble(), imageHeight),
      Paint()..color = Colors.white,
    );

    // Position text in center of paper width
    final dx = (width - textPainter.width) / 2;
    textPainter.paint(canvas, Offset(dx > 0 ? dx : 0, padding));

    // Convert to image
    final picture = recorder.endRecording();
    final img = await picture.toImage(width, imageHeight.ceil());
    final byteData = await img.toByteData(format: ImageByteFormat.png);
    final buffer = byteData!.buffer.asUint8List();

    // Save to temp file
    await File(tempPath).writeAsBytes(buffer);

    // Print the image
    return await PrinterCore.printImage(tempPath,
        width: width,
        alignment: TextFormatter.convertAlignment(Alignment.center));
  } catch (e) {
    print('Error printing centered text: $e');
    return false;
  }
}