I’m developing Laravel and React application. Here need to print document to different printer in our network.
Now need to select printer Destination when execute window.print()
by clicking print button.
Already fetch all connected printer list by php.
Now need to open printer preview window with pre-defined Destinationo of printer
programmatically by JS or PHP.
Here how to fetch all connected printer.
// Get printer property by key
function getPrinterProperty($key){
$str = shell_exec('wmic printer get '.$key.' /value');
$keyname = "$key=";
$validValues = [];
$fragments = explode(PHP_EOL,$str);
foreach($fragments as $fragment){
if($fragment == ""){
continue;
}
if (preg_match('/('.$keyname.')/i', $fragment)) {
array_push($validValues,str_replace($keyname,"",$fragment));
}
}
return $validValues;
}
$Name = getPrinterProperty("Name");
$Description = getPrinterProperty("Description");
$Network = getPrinterProperty("Network");
$Local = getPrinterProperty("Local");
$PortName = getPrinterProperty("PortName");
$Default = getPrinterProperty("Default");
$Comment = getPrinterProperty("Comment");
$Printers = [];
foreach($Name as $i => $n){
$Printers[$i] = (object)[
"name" => $n,
"description" => $Description[$i],
"Portname" => $PortName[$i],
"isDefault" =>($Default[$i] == "TRUE")? true : false,
"isNetwork" => ($Network[$i] == "TRUE")? true : false,
"isLocal" =>($Local[$i] == "TRUE")? true : false,
"Comment" => $Comment[$i],
];
}
//var_dump($Printers);
echo json_encode($Printers);
Here is the result:
[
{
"name": "OneNote (Desktop)",
"description": "",
"Portname": "nul:",
"isDefault": false,
"isNetwork": false,
"isLocal": true,
"Comment": ""
},
{
"name": "Microsoft XPS Document Writer",
"description": "",
"Portname": "PORTPROMPT:",
"isDefault": false,
"isNetwork": false,
"isLocal": true,
"Comment": ""
},
{
"name": "Microsoft Print to PDF",
"description": "",
"Portname": "PORTPROMPT:",
"isDefault": true,
"isNetwork": false,
"isLocal": true,
"Comment": ""
},
{
"name": "Fax",
"description": "",
"Portname": "SHRFAX:",
"isDefault": false,
"isNetwork": false,
"isLocal": true,
"Comment": ""
},
{
"name": "EPSONED54D8 (L4160 Series)",
"description": "",
"Portname": "WSD-45eaf325-9cd7-4461-9a57-a3a14dd9ef18",
"isDefault": false,
"isNetwork": false,
"isLocal": true,
"Comment": ""
}
]
JS: Now want to open printer window.print()
by Portname or name.
PHP: shell_exec('Get-Printer -Name "Microsoft Print to PDF"');