We help IT Professionals succeed at work.

Printing directly to a network printer via a socket connection

stephen_cattaneo
on
Medium Priority
532 Views
Last Modified: 2012-06-27
I need to print directly to a printer via a socket connection either over LPD/LPR port or 9100. This is a star thermal printer.

The code i am writing it in is Flex and as3 but i dont think that should matter. A socket connection is the same in any language. I dont need anything based on any libraries because that will not help me.
Comment
Watch Question

Nem SchlechtIT Supervisor
CERTIFIED EXPERT
Top Expert 2009
Commented:
Well, you included the Perl zone, so here it is in Perl:
#!/usr/bin/perl
use Socket;

my $printer_hostname="printer_name";
my $port = 9100;

my $inet = inet_aton($printer_hostname);
my $proto = getprotobyname('tcp');

socket(SOCKET_H, PF_INET, SOCK_STREAM, $proto) || die "No socket!";
connect(SOCKET_H, sockaddr_in($port, $inet)) || die "No socket connect!";

while (<>) {
    print SOCKET_H $_;
}

close(SOCKET_H);

Open in new window


This just reads from STDIN and send anything it gets directly to port 9100 on your printer.  Works great w/ postscript on my printer.  Not so much w/ plain text (it's expecting Windows carriage returns, which I don't have in my UNIX text files).
It seems that its easier then i thought. In air/flex you just need to use the byte array and the writebyte for special characters and the writeutfbytes for text.


Here is a small excerpt.

//init printer
	byteArray.writeByte(27);
	byteArray.writeUTFBytes("@");
	
	//center
	byteArray.writeByte(27);
	byteArray.writeUTFBytes("a");
	byteArray.writeByte(1);
	
	////font a
	byteArray.writeByte(27);
	byteArray.writeUTFBytes("!");
	byteArray.writeByte(30);
	
	//Header
	byteArray.writeUTFBytes(xmlConfig.printer.header);

Open in new window

Author

Commented:
The other answers and not applicable. I was looking for how to talk to the printer. I guess the real answer it in binary.