Search code examples
javaprintingescapingzebra-printers

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...


Solution

  • 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