printLines static method
Print multiple lines of text.
Prints a list of text lines with the specified formatting.
lines: List of text lines to printfontFamily: Font family to usefontSize: Font size in pointsfontWeight: Font weight (normal, bold, etc.)lineSpacing: Spacing between lines
Returns true if printing was successful.
Implementation
static Future<bool> printLines(
List<String> lines, {
String fontFamily = 'Siemreap',
double fontSize = 20,
FontWeight fontWeight = FontWeight.normal,
double lineSpacing = 1.5,
}) async {
if (lines.isEmpty) return true;
// Combine lines with newlines and proper spacing
final text = lines.join('\n');
// Check if we can print directly using ASCII
if (TextFormatter.isAsciiPrintable(text)) {
return await printText(text);
} else {
// We need to render as image if text contains non-ASCII characters
// This implementation would create an image with the text and print it
try {
final directory = await getTemporaryDirectory();
final tempPath =
'${directory.path}/lines_${DateTime.now().millisecondsSinceEpoch}.png';
// Create recorder and canvas
final recorder = PictureRecorder();
final canvas = Canvas(recorder);
// Calculate total height
double totalHeight = 0;
List<TextPainter> painters = [];
for (String line in lines) {
final textSpan = TextSpan(
text: line,
style: TextStyle(
fontFamily: fontFamily,
fontSize: fontSize,
fontWeight: fontWeight,
color: Colors.black,
),
);
final textPainter = TextPainter(
text: textSpan,
textDirection: TextDirection.ltr,
);
textPainter.layout(maxWidth: 576);
painters.add(textPainter);
totalHeight += textPainter.height * lineSpacing;
}
// Draw white background
canvas.drawRect(
Rect.fromLTWH(0, 0, 576, totalHeight),
Paint()..color = Colors.white,
);
// Draw text lines
double yPos = 0;
for (TextPainter painter in painters) {
painter.paint(canvas, Offset(0, yPos));
yPos += painter.height * lineSpacing;
}
// Convert to image
final picture = recorder.endRecording();
final img = await picture.toImage(576, totalHeight.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);
} catch (e) {
print('Error printing lines: $e');
return false;
}
}
}