Additionally to Gokula's answer:
It's also possible to do this without having a file saved on device. In my case I used byte array or base 64 to print an image.
Code in kotlin =)
Printer Controller Call
override fun write(content: String, address: String?) {
address?.let {
val policy: StrictMode.ThreadPolicy = StrictMode.ThreadPolicy.Builder().permitAll().build()
StrictMode.setThreadPolicy(policy)
Base64.decode("Base64 image content goes here", Base64.DEFAULT).printByDeviceIp(address)
}
}
Printer Extension
fun ByteArray.printByDeviceIp(address: String) {
try {
val socket = Socket(address, PRINTER_DEFAULT_PORT)
val output = DataOutputStream(socket.getOutputStream())
val buffer = ByteArray(PRINTER_BUFFER_SIZE)
val inputStream = ByteArrayInputStream(this)
output.writeBytes(UEL)
output.writeBytes(PRINT_META_JOB_START)
output.writeBytes(PRINT_META_JOB_NAME)
output.writeBytes(PRINT_META_JOB_PAPER_TYPE)
output.writeBytes(PRINT_META_JOB_COPIES)
output.writeBytes(PRINT_META_JOB_LANGUAGE)
while (inputStream.read(buffer) != -1)
output.write(buffer)
output.writeBytes(ESC_SEQ)
output.writeBytes(UEL)
output.flush()
inputStream.close()
output.close()
socket.close()
} catch (e: Exception) {
when(e) {
is SocketException -> Log.e(this.javaClass.name, "Network failure: ${e.message}")
is SocketTimeoutException -> Log.e(this.javaClass.name, "Timeout: ${e.message}")
is IOException -> Log.e(this.javaClass.name, "Buffer failure: ${e.message}")
else -> Log.e(this.javaClass.name, "General failure: ${e.message}")
}
}
Printer Job Constants
private const val PRINT_META_JOB_LABEL = "@PJL"
private const val PRINT_META_BREAK = "\r\n"
private const val ESCAPE_KEY = 0x1b.toChar()
const val UEL = "$ESCAPE_KEY%-12345X"
const val ESC_SEQ = "$ESCAPE_KEY%-12345 $PRINT_META_BREAK"
const val PRINT_META_JOB_START = "$PRINT_META_JOB_LABEL $PRINT_META_BREAK"
const val PRINT_META_JOB_NAME = "$PRINT_META_JOB_LABEL JOB NAME = 'INBOUND_FINISH' $PRINT_META_BREAK"
const val PRINT_META_JOB_PAPER_TYPE = "$PRINT_META_JOB_LABEL SET PAPER = A4"
const val PRINT_META_JOB_COPIES = "$PRINT_META_JOB_LABEL SET COPIES = 1"
const val PRINT_META_JOB_LANGUAGE = "$PRINT_META_JOB_LABEL ENTER LANGUAGE = PDF $PRINT_META_BREAK"
const val PRINTER_DEFAULT_PORT: Int = 9100
const val PRINTER_BUFFER_SIZE: Int = 3000