I'm new to php and made a code that takes some information from a database and converts it into code128 barcode. Echoing it to the page is no problem:
$finalvar = '<p>'.bar128(stripcslashes($row['Flowers'])).'</p>';
echo $finalvar;
So far so good. I now want to print this barcode on a network printer and use this:
$port = "9100";
$host = "10.64.33.33";
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket === false) {
echo "socket_create() failed, reason: " . socket_strerror(socket_last_error ()) . "
";
} else {
echo "OK.
";
}
$result = socket_connect($socket, $host, $port);
if ($result === false) {
echo "socket_connect() failed.
Reason: ($result) " . socket_strerror (socket_last_error($socket)) . "
";
} else {
echo "OK.
";
}
socket_write($socket, $finalvar);
socket_close($socket);
The printing works perfectly but instead of printing the barcode like in the picture, the paper looks like this:
<p><table cellpadding=0 cellspacing=0><tr><td><div class="128"
style"border-"
I think this is probably more of a formatting thing, but I didn't find anything that worked. How can I print $finalvar
like in the picture shown above?
For anyone who wonders how I made it:
Most label printers support their own languages like ZPL (Zebra Programming language) or DPL (Datamax Programming language). You can just send a command to convert and print your variable. You don't even need to convert it into barcode, the printer does that for you. You will need to send 1 line of ZPL to your printer. ZPL is very easy and you can see that for yourself here. As you can see in the link I provided, you can create a barcode with only this command:
^XA^BY5,2,270^FO100,550^BC^FD$yourvariable^FS^XZ
In my case, I used this exact code above to print a simple barcode. This is how you implement this in PHP and send it to the printer:
$variable = "ABC123"; //the variable you want to convert to barcode and print
$print_data = ^XA^BY5,2,270^FO100,550^BC^FD$variable^FS^XZ; //this is the ZPL Code
// Open a telnet connection to the printer, then push all the data into it.
try
{
$fp=pfsockopen("10.64.57.51",9100); //IP of your printer and port
fputs($fp,$print_data);
echo "Job sent";
fclose($fp);
}
catch (Exception $e)
{
echo "Job Failed";}
Note: The ZPL Code I provided is made for the size of my labels. You might need to change some X and Y numbers to fit yours. You can test this on the Website I provided.
Google search for "render html to image" gives a few results, e.g. here. Looking at the readme, it seems pretty straight forward to convert your html into an image/pdf like so (assuming you installed it)
use Spatie\Browsershot\Browsershot;
Browsershot::html($someHtml)->savePdf('example.pdf');
I am not familiar with using sockets and printing, but you should then be able to just read the file content via e.g.
file_get_contents('file.pdf')
and do what you did before.