### Build and Print Text Receipts with BlueLine Basic Builder Source: https://context7.com/dilivva/blueline/llms.txt This code example shows how to use the `buildPrintData` function from the BlueLine basic builder API to construct formatted text receipts. It demonstrates adding styled text with various alignments, font sizes, styles (bold), and line breaks, and then sending the generated data to the printer. It also includes accessing a preview image of the print job. ```kotlin import com.dilivva.blueline.basic.builder.buildPrintData import com.dilivva.blueline.core.commands.Config val printData = buildPrintData { appendText { // Large centered header styledText( data = "INVOICE", alignment = Config.Alignment.CENTER, fontSize = Config.FontSize.LARGE_2, style = Config.Style.BOLD ) textNewLine() // Separator line styledText( data = "================================", alignment = Config.Alignment.CENTER, style = Config.Style.BOLD ) textNewLine(2) // Customer information styledText( data = "Customer:", fontSize = Config.FontSize.NORMAL, style = Config.Style.BOLD ) text(" John Doe") textNewLine() text("Phone: +1234567890") textNewLine() text("Date: 2025-12-08") textNewLine(2) // Items with right alignment styledText( data = "Total: $150.00", alignment = Config.Alignment.RIGHT, fontSize = Config.FontSize.LARGE, style = Config.Style.BOLD, color = Config.Color.BLACK ) textNewLine() // Footer styledText( data = "Thank you!", alignment = Config.Alignment.CENTER, font = Config.Font.FONT_B ) } } // Send to printer blueLine.print(printData.data) // Access preview image (PNG format) for UI display printData.preview?.let { previewBytes -> // Display preview in UI before printing displayPreview(previewBytes) } ``` -------------------------------- ### Basic BlueLine Usage: Print Text and Image Source: https://github.com/dilivva/blueline/blob/master/README.md Demonstrates how to use the BlueLine basic builder to print formatted text and an image. This includes scanning for printers, connecting, building print data with various text styles and newlines, and finally printing the data. ```kotlin import com.dilivva.blueline.basic.* fun main() { val blueLine = BlueLine() //Monitor Connection state val connectionState = bluetoothConnection.connectionState() //StateFlow //Scan for printers blueLine.scanForPrinters() //Connect blueLine.connect() //Build print data val result = buildPrintData { appendImage { imageBytes = bytes } appendText { styledText(data = "Send24", alignment = Config.Alignment.CENTER, font = Config.Font.LARGE_2, style = Config.Style.BOLD) textNewLine() styledText(data = "================================", alignment = Config.Alignment.CENTER, style = Config.Style.BOLD) textNewLine() text("Name: Bob Oscar") textNewLine(2) text("Phone: +111111111") textNewLine(2) styledText(data = "Variant:", font = Config.Font.NORMAL, style = Config.Style.BOLD) text("HUB_TO_HUB") } } //print blueLine.print(result.data) //preview result.preview } ``` -------------------------------- ### Initialize and Manage Bluetooth Connection with BlueLine Source: https://context7.com/dilivva/blueline/llms.txt This snippet demonstrates how to initialize the BlueLine library, monitor Bluetooth connection states, scan for discoverable printers, connect to a printer, and disconnect. It highlights error handling for common Bluetooth issues like disabled adapters or missing permissions. ```kotlin import com.dilivva.blueline.core.connection.bluetooth.BlueLine import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.launch // Create BlueLine instance (platform-specific implementation) val blueLine = BlueLine() // Initialize Bluetooth functionality blueLine.init() // Monitor connection state reactively val connectionState: StateFlow = blueLine.connectionState() // Observe connection state scope.launch { blueLine.connectionState().collect { state -> println("Device: ${state.deviceName}") println("Connected: ${state.isConnected}") println("Can Print: ${state.canPrint}") println("Scanning: ${state.isScanning}") // Handle errors state.bluetoothConnectionError?.let { error -> when (error) { ConnectionError.BLUETOOTH_DISABLED -> println("Enable Bluetooth") ConnectionError.BLUETOOTH_PERMISSION -> println("Grant permissions") ConnectionError.BLUETOOTH_PRINTER_DEVICE_NOT_FOUND -> println("No printer found") else -> println("Error: $error") } } } } // Scan for printers (suspending function, ~10 second timeout) launch { blueLine.scanForPrinters() // After scan completes, state.discoveredPrinter will be true if found } // Connect to discovered printer blueLine.connect() // Disconnect when done blueLine.disconnect() ``` -------------------------------- ### Print Images with Basic Builder in Kotlin Source: https://context7.com/dilivva/blueline/llms.txt This snippet demonstrates how to add images to print jobs using the basic builder. It supports automatic scaling, monochrome conversion, and alignment. Images must be in PNG format. Dependencies include core Blueline libraries. ```kotlin import com.dilivva.blueline.basic.builder.buildPrintData import com.dilivva.blueline.core.commands.Config // Load image bytes (must be PNG format) val logoBytes: ByteArray = loadImageFromResources("logo.png") val productBytes: ByteArray = loadImageFromResources("product.png") val printData = buildPrintData { // Company logo - fill full width appendImage { imageBytes = logoBytes fillWidth = true // Scale to printer width alignment = Config.Alignment.CENTER } newLine(2) // Company name appendText { styledText( data = "Acme Corporation", alignment = Config.Alignment.CENTER, fontSize = Config.FontSize.LARGE, style = Config.Style.BOLD ) textNewLine() text("123 Main Street, City") textNewLine(2) } // Product image with specific dimensions appendImage { imageBytes = productBytes width = 200 // Width in pixels height = 200 // Height in pixels alignment = Config.Alignment.CENTER useAsterisk = false // Use GS v 0 command (default) } newLine() // Product details appendText { text("Product: Premium Widget") textNewLine() text("SKU: WGT-001") } } blueLine.print(printData.data) // Preview shows exactly how image will appear on receipt val preview = printData.preview ``` -------------------------------- ### Create and Use PrintDataResult Objects with BlueLine (Kotlin) Source: https://context7.com/dilivva/blueline/llms.txt Demonstrates how to create and utilize PrintDataResult objects, which contain both the raw print data (ByteArray) and an optional PNG preview (ByteArray?). This is useful for displaying a preview to the user before printing. ```kotlin import com.dilivva.blueline.core.result.PrintDataResult import com.dilivva.blueline.basic.builder.buildPrintData // Build print data val result: PrintDataResult = buildPrintData { appendText { styledText(data = "Receipt", alignment = Config.Alignment.CENTER) } } // PrintDataResult contains: // 1. data: ByteArray - The actual print data to send to printer val printBytes: ByteArray = result.data // Contains ESC/POS commands + encoded text + configuration // 2. preview: ByteArray? - Optional PNG preview image val previewImage: ByteArray? = result.preview // Shows exactly what will be printed (monochrome) // Useful for displaying to user before printing // Use the result blueLine.print(result.data) // Display preview in UI result.preview?.let { // Convert to platform-specific image format val bitmap = decodePng(it) imageView.setImageBitmap(bitmap) } // Compose builder also returns PrintDataResult @Composable fun PrintExample() { val composeBuilder = rememberComposeBuilder() composeBuilder.drawContents { Text("Compose Content") } Button(onClick = { scope.launch { val result = composeBuilder.create() // Returns PrintDataResult blueLine.print(result.data) result.preview?.let { showPreview(it) } } }) { Text("Print") } } ``` -------------------------------- ### Add BlueLine Dependencies to Kotlin Multiplatform Project Source: https://github.com/dilivva/blueline/blob/master/README.md Integrate the BlueLine library into your Kotlin multiplatform project by adding the necessary dependencies to your root build.gradle.kts file. This includes specifying the mavenCentral repository and including the basic-builder or compose-builder artifact based on your needs. ```kotlin // In your root build.gradle.kts file repositories { mavenCentral() } kotlin{ sourceSets { commonMain.dependencies{ //old - pre 2.0.0 implementation("com.dilivva:blueline:${bluelineVersion}") //New 2.0.0 Basic implementation("com.dilivva.blueline:basic-builder:${bluelineVersion}") //New 2.0.0 Compose implementation("com.dilivva.blueline:compose-builder:${bluelineVersion}") } } } ``` -------------------------------- ### Compose BlueLine Usage: Draw and Print Content Source: https://github.com/dilivva/blueline/blob/master/README.md Illustrates how to use the BlueLine compose builder to draw custom content using Jetpack Compose for multiplatform and then print it. This involves remembering the compose builder, scanning and connecting to printers, drawing content using a composable function, creating the print data, and printing. ```kotlin import com.dilivva.blueline.compose.* fun main() { val blueLine = BlueLine() //Monitor Connection state val connectionState = bluetoothConnection.connectionState() //StateFlow val composeBuilder = rememberComposeBuilder() //Scan for printers blueLine.scanForPrinters() //Connect blueLine.connect() //Use compose multiplatform to draw print data composeBuilder.drawContents { PreviewPeopleTable() } //Build print data val result = composeBuilder.create() //print blueLine.print(result.data) //preview result.preview } ``` -------------------------------- ### Handle Image Processing and Scaling for Printing Source: https://context7.com/dilivva/blueline/llms.txt Configures image printing with automatic monochrome conversion, dithering, and scaling options. Supports filling printer width, specific pixel dimensions, and using ESC * command for compatibility. Includes features for grayscale conversion, adaptive thresholding, dithering, and aspect ratio maintenance. ```kotlin import com.dilivva.blueline.basic.builder.buildPrintData import com.dilivva.blueline.core.commands.Config val imageBytes = loadImage("photo.png") val printData = buildPrintData { // Example 1: Fill printer width appendImage { imageBytes = imageBytes fillWidth = true // Scale to full printer width (48mm default) alignment = Config.Alignment.CENTER } newLine(2) // Example 2: Specific dimensions (maintains aspect ratio) appendImage { imageBytes = imageBytes width = 384 // Width in pixels (203 DPI for thermal printers) height = 384 // Height in pixels alignment = Config.Alignment.LEFT } newLine(2) // Example 3: Use ESC * command instead of GS v 0 appendImage { imageBytes = imageBytes width = 200 useAsterisk = true // Use ESC * for compatibility alignment = Config.Alignment.RIGHT } } blueLine.print(printData.data) // Image processing features: // - Automatic grayscale conversion // - Adaptive thresholding based on image brightness // - Dithering for better quality on 1-bit output // - Maintains aspect ratio when scaling // - Preview generation to verify before printing // Access processed image preview printData.preview?.let { previewPng -> // Display monochrome preview to user displayImagePreview(previewPng) } ``` -------------------------------- ### Configure Text Formatting Options with ESC/POS Source: https://context7.com/dilivva/blueline/llms.txt Utilizes Config enums to control text appearance in ESC/POS command wrappers. This function allows for setting alignment, font sizes, font types, styles, and colors for printed text. It also demonstrates combined formatting options. ```kotlin import com.dilivva.blueline.core.commands.Config import com.dilivva.blueline.basic.builder.buildPrintData val printData = buildPrintData { appendText { // Alignment options styledText(data = "Left aligned", alignment = Config.Alignment.LEFT) textNewLine() styledText(data = "Center aligned", alignment = Config.Alignment.CENTER) textNewLine() styledText(data = "Right aligned", alignment = Config.Alignment.RIGHT) textNewLine(2) // Font sizes (from normal to very large) styledText(data = "Normal", fontSize = Config.FontSize.NORMAL) textNewLine() styledText(data = "Wide", fontSize = Config.FontSize.WIDE) textNewLine() styledText(data = "Tall", fontSize = Config.FontSize.TALL) textNewLine() styledText(data = "Large", fontSize = Config.FontSize.LARGE) textNewLine() styledText(data = "XL", fontSize = Config.FontSize.LARGE_2) textNewLine() styledText(data = "XXL", fontSize = Config.FontSize.LARGE_3) textNewLine(2) // Font types styledText(data = "Font A (default)", font = Config.Font.FONT_A) textNewLine() styledText(data = "Font B (condensed)", font = Config.Font.FONT_B) textNewLine(2) // Styles styledText(data = "Normal text", style = Config.Style.NORMAL) textNewLine() styledText(data = "Bold text", style = Config.Style.BOLD) textNewLine() styledText(data = "Underlined text", style = Config.Style.UNDERLINE) textNewLine(2) // Colors (printer dependent) styledText(data = "Black text", color = Config.Color.BLACK) textNewLine() styledText(data = "Red text", color = Config.Color.RED) textNewLine(2) // Combined formatting styledText( data = "BOLD CENTERED LARGE", alignment = Config.Alignment.CENTER, fontSize = Config.FontSize.LARGE_2, style = Config.Style.BOLD, color = Config.Color.BLACK ) } } blueLine.print(printData.data) ``` -------------------------------- ### Print Using Compose UI Components in Kotlin Source: https://context7.com/dilivva/blueline/llms.txt This snippet shows how to convert Jetpack Compose Multiplatform UI components directly into printable data. It's suitable for complex layouts and requires Compose UI dependencies and Blueline's Compose integration. Input is a Composable function, output is printable data. ```kotlin import com.dilivva.blueline.compose.rememberComposeBuilder import com.dilivva.blueline.core.commands.Config import androidx.compose.foundation.layout.* import androidx.compose.material.Text import androidx.compose.material.Divider import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp @Composable fun PrintReceiptExample() { val blueLine = remember { BlueLine() } // Assuming BlueLine is a defined class val composeBuilder = rememberComposeBuilder( printerWidthInMm = 58f, // 58mm thermal printer alignment = Config.Alignment.LEFT ) // Draw Compose UI content to be printed composeBuilder.drawContents { Column( modifier = Modifier .fillMaxWidth() .padding(8.dp) ) { // Header Text( text = "Sales Receipt", fontSize = 20.sp, fontWeight = FontWeight.Bold ) Spacer(modifier = Modifier.height(8.dp)) Divider() Spacer(modifier = Modifier.height(8.dp)) // Items table Row(modifier = Modifier.fillMaxWidth()) { Text("Item", modifier = Modifier.weight(2f), fontWeight = FontWeight.Bold) Text("Qty", modifier = Modifier.weight(1f), fontWeight = FontWeight.Bold) Text("Price", modifier = Modifier.weight(1f), fontWeight = FontWeight.Bold) } Divider() // Sample items listOf( Triple("Widget A", "2", "$10.00"), Triple("Widget B", "1", "$25.00"), Triple("Widget C", "3", "$15.00") ).forEach { (item, qty, price) -> Row(modifier = Modifier.fillMaxWidth()) { Text(item, modifier = Modifier.weight(2f)) Text(qty, modifier = Modifier.weight(1f)) Text(price, modifier = Modifier.weight(1f)) } } Spacer(modifier = Modifier.height(8.dp)) Divider(thickness = 2.dp) // Total Row(modifier = Modifier.fillMaxWidth()) { Text( "Total", modifier = Modifier.weight(3f), fontWeight = FontWeight.Bold, fontSize = 18.sp ) Text( "$60.00", modifier = Modifier.weight(1f), fontWeight = FontWeight.Bold, fontSize = 18.sp ) } } } // Create print data and print Button(onClick = { scope.launch { // Assuming 'scope' is a CoroutineScope val result = composeBuilder.create() blueLine.print(result.data) // Show preview before printing result.preview?.let { showPreview(it) } // Assuming showPreview is defined } }) { Text("Print Receipt") } } ``` -------------------------------- ### Send Raw ESC/POS Commands with BlueLine (Kotlin) Source: https://context7.com/dilivva/blueline/llms.txt Allows sending custom ESC/POS commands directly to the printer for advanced control. This method bypasses the builder and provides raw command access. It requires knowledge of ESC/POS command structures. ```kotlin import com.dilivva.blueline.core.commands.PrintCommands import com.dilivva.blueline.basic.builder.buildPrintData // Use predefined commands val newLine: Byte = PrintCommands.NEW_LINE // 0x0A val resetConfig: ByteArray = PrintCommands.RESET_CONFIGURATION // [0x1B, 0x40] val lineSpacing: ByteArray = PrintCommands.SET_LINE_SPACING_24 // [0x1B, 0x33, 24] // Build custom command sequence val customCommands = buildList { // Reset printer addAll(resetConfig.toList()) // Set line spacing addAll(lineSpacing.toList()) // Center alignment addAll(listOf(0x1B.toByte(), 0x61.toByte(), 0x01.toByte())) // Large bold text addAll(listOf(0x1D.toByte(), 0x21.toByte(), 0x11.toByte())) addAll(listOf(0x1B.toByte(), 0x45.toByte(), 0x01.toByte())) // Text data addAll("CUSTOM COMMAND".encodeToByteArray().toList()) // New line add(newLine) // Reset addAll(resetConfig.toList()) // Cut paper (if supported) addAll(listOf(0x1D.toByte(), 0x56.toByte(), 0x00.toByte())) }.toByteArray() // Send custom commands directly blueLine.print(customCommands) // Or mix with builder val printData = buildPrintData { appendText { text("Standard text") } // Builder automatically adds reset commands and line spacing } blueLine.print(printData.data) ``` -------------------------------- ### Display Bluetooth Connection State and Control in Jetpack Compose Source: https://context7.com/dilivva/blueline/llms.txt This Kotlin code snippet defines a Composable function 'BluetoothPrinterUI' that visualizes the Bluetooth connection state provided by the Blueline library. It displays device name, readiness, scanning status, discovered printers, connection status, printability, and printing progress. It also handles and displays specific Bluetooth connection errors and provides UI elements (buttons) for scanning, connecting, and disconnecting. Dependencies include Jetpack Compose UI, Kotlin Coroutines, and the Blueline library. ```kotlin import com.dilivva.blueline.core.connection.bluetooth.ConnectionState import com.dilivva.blueline.core.connection.bluetooth.ConnectionError import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import kotlinx.coroutines.flow.StateFlow @Composable fun BluetoothPrinterUI() { val blueLine = remember { BlueLine() } val state by blueLine.connectionState().collectAsState() Column(modifier = Modifier.padding(16.dp)) { // Connection status StatusRow("Device", state.deviceName) StatusRow("Bluetooth Ready", state.isBluetoothReady.toString()) StatusRow("Scanning", state.isScanning.toString()) StatusRow("Discovered", state.discoveredPrinter.toString()) StatusRow("Connected", state.isConnected.toString()) StatusRow("Can Print", state.canPrint.toString()) StatusRow("Printing", state.isPrinting.toString()) // Error display state.bluetoothConnectionError?.let { error -> val errorMessage = when (error) { ConnectionError.BLUETOOTH_DISABLED -> "Please enable Bluetooth in settings" ConnectionError.BLUETOOTH_PERMISSION -> "Grant Bluetooth permissions to continue" ConnectionError.BLUETOOTH_NOT_SUPPORTED -> "This device doesn't support Bluetooth" ConnectionError.BLUETOOTH_PRINT_ERROR -> "Failed to print. Check printer connection" ConnectionError.BLUETOOTH_PRINTER_DEVICE_NOT_FOUND -> "No printer found. Make sure printer is on" } Card( backgroundColor = Color.Red.copy(alpha = 0.1f), modifier = Modifier.padding(vertical = 8.dp) ) { Text( text = errorMessage, color = Color.Red, modifier = Modifier.padding(12.dp) ) } } Spacer(modifier = Modifier.height(16.dp)) // Action buttons Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp) ) { Button( onClick = { scope.launch { blueLine.scanForPrinters() } }, enabled = state.isBluetoothReady && !state.isScanning, modifier = Modifier.weight(1f) ) { Text(if (state.isScanning) "Scanning..." else "Scan") } Button( onClick = { blueLine.connect() }, enabled = state.discoveredPrinter && !state.isConnected && !state.isConnecting, modifier = Modifier.weight(1f) ) { Text(if (state.isConnecting) "Connecting..." else "Connect") } Button( onClick = { blueLine.disconnect() }, enabled = state.isConnected, modifier = Modifier.weight(1f) ) { Text("Disconnect") } } } } @Composable fun StatusRow(label: String, value: String) { Row( modifier = Modifier.fillMaxWidth().padding(vertical = 4.dp), horizontalArrangement = Arrangement.SpaceBetween ) { Text(label, fontWeight = FontWeight.Medium) Text(value, color = Color.Gray) } } ``` -------------------------------- ### Set Custom Printer Encoding for International Characters Source: https://context7.com/dilivva/blueline/llms.txt Configures text encoding for international character support using the PrinterEncoding class. Allows setting a custom name and charset command value. Provides common charset command values for reference. ```kotlin import com.dilivva.blueline.core.commands.PrinterEncoding import com.dilivva.blueline.basic.builder.buildPrintData // Create custom encoding (default is windows-1252, charset 6) val encoding = PrinterEncoding( name = "windows-1252", charsetCommand = 6 ) // Get encoding command bytes val encodingCommand: ByteArray = encoding.getCommand() // Returns: [0x1B, 0x74, 0x06] // Common charsets: // 0 = PC437 (USA, Standard Europe) // 1 = Katakana // 2 = PC850 (Multilingual) // 3 = PC860 (Portuguese) // 4 = PC863 (Canadian-French) // 5 = PC865 (Nordic) // 6 = windows-1252 (Western European) // Example with international characters val printData = buildPrintData { appendText { text("English: Hello World") textNewLine() text("Spanish: ¡Hola Mundo!") textNewLine() text("French: Bonjour le Monde") textNewLine() text("German: Hallo Welt") } } blueLine.print(printData.data) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.