如何使用php打印到包含ESC / P的通用文本文件?

So, I've been reading alot about the issues of printing, after a couple of days of research and reading a lot, it all starts making sense. Let's say I've this piece of code: (I'm using php and php_printer extension)

$boldon = chr(27)."E".chr(1);
$boldoff = chr(27)."E".chr(0);
$pcenter = chr(27)."a".chr(1);
$pleft = chr(27)."a".chr(0);
$handle = printer_open("Generic / Text Only File");
printer_set_option($handle, PRINTER_MODE, "RAW");
printer_write($handle, $boldon.$pcenter."Some text");
printer_write($handle, "
");
printer_write($handle, "Some more text");
printer_write($handle, "
");
printer_close($handle);

That works wonderfully when running on localhost, I'm using a thermal printer and it prints fine. As I've come to know(now it makes total sense) when I try this on my server, this doesn't work, I think that it is because the actual server tries to print it locally and the printer isn't found, I guess if the printer were installed in the server, the server's printer would print it, but that's not what I'm looking for.

Displaying the information in html or any sort and use window.print() has no use, as browsers doesn't send text only(or that's what I read many times) and generic text only, prints text only(I'm guessing).

So the solution is making a file of some sort that contains the text with ESC/P and then print it with javascript(I don't need to skip the print dialog as mentioned in other threads), and I can't change the driver, it has to be generic text only. So if I make a .txt file with the information I want, it will print, but the ESC/P is ignored, so I can't format my text in anyway, it will print with the default printer options, sending all in plain text(the irony) ignoring new lines and every piece of ESC/P.

So, the question here is, is there anyway to create a file(any type of file) that will send the text that I want and not ignore the ESC/P?

There is a way to create a binary file. In short, you create string, send it like binary file, download and then print with what you like.

$output= chr(27)."a".chr(1)."Some text"; // what you like to print

// headers to send file
header("Pragma: public"); // required
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false); // required for certain browsers 
header("Content-Type: application/octet-stream"); // send it like binary file
header("Content-Disposition: attachment; filename=\"print\";" );
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".strlen($output));
echo $output;
exit();

But I dont think you can print binary data with browser.

Another solution is to use local software (server) like proxy to printer:

  • remote server sends data to local server that send it to printer driver

or

  • local server request data from remote server and then print it