Wednesday, July 17, 2013

Simple Printer Service


Hello guys,

Are you stuck with some printer control job in Java ? Well, the good news is, I've a solution and I'll make it short as much as possible for you.

I recently faced an issue while integrating a thermal printer to a Java based POS system.
My original plan was to follow JPOS (Java Point Of Sales) which is derived from UPOS (Unified Point Of Sales) interface which accommodates long range of devices.

But unfortunately I couldn't find proper device support for the JPOS from printer end but the printer drivers.
So I made the thermal printer into a usual printer by using Java Print Service.

Try this out with any printer, works totally fine..!
But if you are dealing with receipt printing via thermal printer, try to stick into UPOS defined API such as JPOS, OLEPOS etc, as much as possible.
But when all hopes go down the toilet, make your self comfortable with this..!

/**
*Definition Interface
*/
public interface PrintControlService {
public void print(String content);
}

/**
*Class level implementation
*/
public class PrintControlServiceImpl implements PrintControlService {

private String contentTicket = "{{nameLocal}}\n";

@Override
public void print(String content) {
contentTicket = contentTicket.replace("{{nameLocal}}", content);
DocFlavor flavor = DocFlavor.BYTE_ARRAY.AUTOSENSE;
PrinterJob printJob = PrinterJob.getPrinterJob();
PrintService service = printJob.getPrintService();
byte[] bytes;
bytes = this.contentTicket.getBytes();
Doc doc = new SimpleDoc(bytes, flavor, null);
DocPrintJob job = service.createPrintJob();
try {
job.print(doc, null);
} catch (PrintException er) {
JOptionPane.showMessageDialog(null, "Error " + er.getMessage());
}
}
}

Enjoy and Good Luck Guys..!

No comments:

Post a Comment