printMultipleColumn static method
Print multiple columns of text.
columns: List of column objects specifying text, position, and stylecanvasWidth: Width of the print canvas in dotslineHeight: Line height multiplieralignment: Overall alignmentpadding: Padding around the content
Returns true if printing was successful.
Implementation
static Future<bool> printMultipleColumn({
required List<PrintColumn> columns,
int canvasWidth = 832,
double lineHeight = 1.5,
Alignment alignment = Alignment.center,
double padding = 10,
}) async {
try {
final directory = await getTemporaryDirectory();
final tempPath =
'${directory.path}/multi_col_${DateTime.now().millisecondsSinceEpoch}.png';
final recorder = PictureRecorder();
final canvas = Canvas(recorder);
final backgroundPaint = Paint()..color = Colors.white;
final textPainters = columns.map((col) {
final span = TextSpan(
text: col.text,
style: TextStyle(
fontSize: col.fontSize,
fontWeight: col.fontWeight,
fontFamily: col.fontFamily,
color: col.color,
),
);
final painter = TextPainter(
text: span,
textAlign: col.align,
textDirection: TextDirection.ltr,
);
painter.layout();
return painter;
}).toList();
// Estimate canvas height based on tallest text
final maxHeight =
textPainters.map((p) => p.height).reduce((a, b) => a > b ? a : b);
final canvasHeight =
(maxHeight * lineHeight).ceil() + (padding * 2).ceil();
canvas.drawRect(
Rect.fromLTWH(0, 0, canvasWidth.toDouble(), canvasHeight.toDouble()),
backgroundPaint,
);
for (int i = 0; i < columns.length; i++) {
final col = columns[i];
final tp = textPainters[i];
double dx = col.x;
if (col.align == TextAlign.center) {
dx = col.x - tp.width / 2;
} else if (col.align == TextAlign.right) {
dx = col.x - tp.width;
}
tp.paint(canvas, Offset(dx, padding));
}
final picture = recorder.endRecording();
final img = await picture.toImage(canvasWidth, canvasHeight);
final byteData = await img.toByteData(format: ImageByteFormat.png);
final buffer = byteData!.buffer.asUint8List();
await File(tempPath).writeAsBytes(buffer);
return await PrinterCore.printImage(
tempPath,
width: canvasWidth,
alignment: TextFormatter.convertAlignment(alignment),
);
} catch (e) {
print('Error printing multiple columns: $e');
return false;
}
}