4

I spent really a lot of time to understand how to print a PCX image using CPCL on a Zebra Printer (via network) without downloading the image to the printer.

The sample on the documentation, in my opinion, is quite obscure.

I attach a sample class to show how to simply print an image. It requires a "zebra.pcx" image on your classpath.

Hope it helps.

Stefano Bertini
  • 292
  • 3
  • 11

1 Answers1

2
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Socket;

public class PrintZebraPCXImage {

    public static void main(String[] args) throws Exception {
        PrintZebraPCXImage instance = new PrintZebraPCXImage();
        instance.print("192.168.1.133", 6101);
    }

    public void print(String address, int port) throws Exception {
        Socket socket = null;
        DataOutputStream stream = null;

        socket = new Socket(address, port);

        try {
            stream = new DataOutputStream(socket.getOutputStream());
            ByteArrayOutputStream bos = readFileToString(this.getClass().getClassLoader().getResourceAsStream("zebra.pcx"));

            stream.writeBytes("! 0 200 200 300 1\r\n");
            stream.writeBytes("PCX 20 0\r\n");

            stream.write(bos.toByteArray());
            stream.writeBytes("PRINT\r\n");

        } finally {
            if (stream != null) {
                stream.close();
            }
            if (socket != null) {
                socket.close();
            }
        }
    }

    public ByteArrayOutputStream readFileToString(InputStream is) {
        InputStreamReader isr = null;
        ByteArrayOutputStream bos = null;
        try {
            isr = new InputStreamReader(is);
            bos = new ByteArrayOutputStream();

            byte[] buffer = new byte[2048];
            int n = 0;
            while (-1 != (n = is.read(buffer))) {
                bos.write(buffer, 0, n);
            }

            return bos;
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            if (isr != null) {
                try {
                    isr.close();
                } catch (IOException e) {
                }
            }
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                }
            }
        }
    }
}
Stefano Bertini
  • 292
  • 3
  • 11