You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

73 lines
1.8 KiB
PHP

<?php
/*
* Copyright 2020 Netsyms Technologies.
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
// Change these values if commands aren't on $PATH
$CMDS = [
"lp" => "lp",
"lpstat" => "lpstat",
"pdfinfo" => "pdfinfo"
];
header("Content-Type: application/json");
function getPrinters(): array {
global $CMDS;
$printerlist = `$CMDS[lpstat] -a`;
$lines = explode("\n", $printerlist);
$printers = [];
foreach ($lines as $line) {
$printer = explode(" ", $line, 2)[0];
if (empty($printer)) {
continue;
}
$printers[] = $printer;
}
return $printers;
}
if ($_GET["action"] == "list") {
exit(json_encode([
"printers" => getPrinters()
]));
} else if ($_GET["action"] == "print") {
if (empty($_GET["printer"]) || !in_array($_GET["printer"], getPrinters())) {
http_response_code(400);
exit(json_encode([
"error" => "No printer specified or printer does not exist."
]));
}
$printer = $_GET["printer"];
$content = file_get_contents("php://input");
$pdffile = tempnam(sys_get_temp_dir(), "WEB_PDF_PRINT");
file_put_contents($pdffile, $content);
$pdfinfo = `$CMDS[pdfinfo] $pdffile`;
preg_match('/Page size: *([0-9]*\.?[0-9]?) x ([0-9]*\.?[0-9]?)/', $pdfinfo, $matches);
$width = $matches[1];
$height = $matches[2];
$media = "Custom.$width" . "x$height";
`$CMDS[lp] -o media=$media -d $printer $pdffile`;
unlink($pdffile);
exit(json_encode([
"printed" => true
]));
} else {
http_response_code(404);
exit(json_encode([
"error" => "No action or invalid action specified."
]));
}