Enoon
Enoon

Reputation: 421

Correct way to send escape codes (raw data) to printer

In the context of a bigger application, my applet needs to print some data to a Zebra or a Dymo (depending on what the user has installed) label printer.

The data i receive is in an escaped form, data that i just need to send to the printer and let it interpret it.

Searching i've found two solutions. Method 1:

byte[] printdata;
PrintService pservice = PrintServiceLookup.lookupDefaultPrintService(); //or get the printer in some other way
DocPrintJob job = pservice.createPrintJob();
DocFlavor flavor = DocFlavor.BYTE_ARRAY.AUTOSENSE;
Doc doc = new SimpleDoc(printdata, flavor, null);

and method 2:

PrintStream printStream = new PrintStream(new FileOutputStream(“LPT1”));
printStream.print(“Hello World”);
printStream.close();

I need this to work cross-platform, with printers using the USB or the serial port. What is the correct way to implement this behaviour?

One problem with method 2 is that i would need to find the URL of the printer in same way...

Upvotes: 2

Views: 3589

Answers (2)

Dexter Varela Campos
Dexter Varela Campos

Reputation: 46

public String rawprint(String printerName, String conte) {
    String res = "";
    PrintServiceAttributeSet printServiceAttributeSet = new HashPrintServiceAttributeSet();
    printServiceAttributeSet.add(new PrinterName(printerName, null));
    PrintService printServices[] = PrintServiceLookup.lookupPrintServices(null, printServiceAttributeSet);
    if (printServices.length != 1) {
        return "Can't  select printer :" + printerName;
    }
    byte[] printdata = conte.getBytes();
    PrintService pservice = printServices[0];
    DocPrintJob job = pservice.createPrintJob();
    DocFlavor flavor = DocFlavor.BYTE_ARRAY.AUTOSENSE;
    Doc doc = new SimpleDoc(printdata, flavor, null);
    PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
    try {
        job.print(doc, aset);
    } catch(Exception e){
        res = e.getMessage();

    }
    return res;
}

Works cool in javafx

Upvotes: 3

mcandre
mcandre

Reputation: 24602

Hex printouts are trustworthy. Call String.getBytes(encoding), then use System.out.format to print each byte as a hexadecimal number.

Upvotes: 0

Related Questions