Skip to content

Instantly share code, notes, and snippets.

@labibmuhajir
Created May 5, 2025 06:32
Show Gist options
  • Save labibmuhajir/b7c82e038c0bdcb3c4f8462dfb05dadc to your computer and use it in GitHub Desktop.
Save labibmuhajir/b7c82e038c0bdcb3c4f8462dfb05dadc to your computer and use it in GitHub Desktop.
java swing print
try {
val services = PrintServiceLookup.lookupPrintServices(null, null)
val printer = services.find {
it.name.lowercase().contains("star")
} ?: throw Exception("No printer")
val outputStream = ByteArrayOutputStream()
outputStream.write(byteArrayOf(27, 64)) // Initialize printer (ESC @)
outputStream.write("=== STRUK PEMBELIAN ===\n".toByteArray(charset("UTF-8")))
outputStream.write("Item 1 x2 Rp10.000\n".toByteArray(charset("UTF-8")))
outputStream.write("Item 2 x1 Rp7.500\n".toByteArray(charset("UTF-8")))
outputStream.write("----------------------\n".toByteArray(charset("UTF-8")))
outputStream.write("TOTAL: Rp27.500\n".toByteArray(charset("UTF-8")))
outputStream.write("\nTerima kasih\n\n\n".toByteArray(charset("UTF-8")))
outputStream.write(byteArrayOf(29, 86, 1)) // Cut paper
val data = outputStream.toByteArray()
val job: DocPrintJob = printer.createPrintJob()
val flavor: DocFlavor = DocFlavor.BYTE_ARRAY.AUTOSENSE
val doc: Doc = SimpleDoc(data, flavor, null)
job.print(doc, null)
} catch (t: Throwable) {
System.out.print(t.message)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment