Monday, October 29, 2018

Printing Receipt Using PHP again

Last blog on this subject is at Printing Receipt. It talks about a single use printing where there is only one printer for one purpose. There are requirements to use same type of printer for different receipts. Like for example, one company wants to print queue numbers, receipts and barcode travellers using the same type of printer.

It would be easy to just create three PHP page to do the work. Here the attempt is to use a single PHP page like a driver that can print to different printer for different purpose. It becomes like a class file. Also the print codes stays with the app that does the printing so that you do not need to look for specific PHP page for the printing code.

The PHP code is like the previous blog with a slight change. The printer is a Brother QL720NW which does not work with fwrite_stream. A simple fputs will work fine.

All that is required is to send the printer IP and the print code to the page as parameter using POST. Now the twist is that POST only sends AlphaNumeric not the full ASCII. Escape codes usually includes ASCII less than 32. The trick is to convert the print code into Base64 first before sending. At the PHP, just use base64_decode to convert it back before printing. The code is as below

$ipAddress = $_POST["IP"];
$printCode = $_POST['PrintCode"];
$printCode = Base64_decode($printCode);
$fp = fsockopen($ipAddress, 9100);
fputs($fp, $printCode, strlen($printCode));
fclose($fp)

With this, you can send to different printer with a different print code using the same PHP page. The advantage is that any app that can do a POST will be able to do printing.

Most programming codes will have base64_encode (or similar). If not then there are probably programmers who wrote a code library in the same programming language. If it does not have then you may have to create the code yourself. The trick is to convert the byte into Binary then take every 6 bit and convert it back to number to match against a table see https://en.wikipedia.org/wiki/Base64. to get the ASCII character. It is not that difficult.




No comments:

Post a Comment