Passing STDIN to Ghostscript in PHP proc_open
I want to use Ghostscript
command within PHP without writing the input or output in files.
$cmd = "gs -sOutputFile=%stdout% -sDEVICE=pdfwrite -dJOBSERVER -";
$descriptorspec = array(0 => array("pipe", "r"),1 => array("pipe", "w"));
$process = proc_open($cmd, $descriptorspec, $pipes);
if (is_resource($process)) {
fwrite($pipes[0], file_get_contents('file.ps'));
fclose($pipes[0]);
$pdf_content = stream_get_contents($pipes[1]);
fclose($pipes[1]);
$return_value = proc_close($process);
header('Content-type: application/pdf');
header('Content-Disposition: attachment; filename="output.pdf"');
echo $pdf_content;
}
Writting to STDOUT
works well, but I cannot get the STDIN
to work. If replacing the command line to
$cmd = "gs -sOutputFile=%stdout% -sDEVICE=pdfwrite -dNOSAFER file.ps";
it works well, but it doesn't when trying to read the input from $pipes[0]
. Where did I go wrong?
Solution 1:
You need to supply '-' as the input filename. So for example:
gs -sDEVICE=pdfwrite -o out.pdf - < /ghostpdl/examples/golfer.eps
Tells Ghostscript to take input from stdin, and directs the content of that file into stdin.
However, for PDF input if you send the input on stdin it is written to a temporary file on disk and then processed, because PDF requires random access to the file, it isn't a streamable format.
For PDF output I would very much advise against writing to stdout. There is already one feature which requires the code to seek inside the output file, and in future there may be more. Obviously that won't be possible if you write the output to stdout so I'd really recommend you don't do that.