PHP Shell_exec not showing full output with Ghostscript

Viewed 28

I am making a script and need to know if a pdf-file contains colors.

I am working on a local linux server and have full access.

The terminal line of code that is working is:

gs -o - -sDEVICE=inkcov file.pdf

The output from the terminal is with a pdf that has been build up with only black is:

GPL Ghostscript 9.26 (2018-11-20)
Copyright (C) 2018 Artifex Software, Inc.  All rights reserved.
This software comes with NO WARRANTY: see the file PUBLIC for details.
Processing pages 1 through 1.
Page 1
 0.00000  0.00000  0.00000  0.12363 CMYK OK

Perfect so far. I am really happy with this output and need to get the last line back to my php-script.

What have I done:

function ink_coverage($file){
$file = str_replace(" ", "\ ", $file);
exec("gs -o - -sDEVICE=inkcov $file 2>&1",$output);
return $output;
}
$ink = ink_coverage($file);
echo 'ink = ' .$ink[5];

Another way I have tried using shell_exec:

function ink_coverage($file){
$file = str_replace(" ", "\ ", $file);
$output = shell_exec("gs -o - -sDEVICE=inkcov $file");
return $output;
}
    $ink = ink_coverage($file);
    echo 'ink = ' .$ink;

The output is always only the first three lines:

GPL Ghostscript 9.26 (2018-11-20) Copyright (C) 2018 Artifex Software, Inc. All rights reserved. This software comes with NO WARRANTY: see the file PUBLIC for details.

After a search on stackoverflow and google I have found a suggestion to add 2>&1 So for example I have also tried this with exec and shell_exec:

exec("gs -o - -sDEVICE=inkcov $file 2>&1",$output);

After adding this (2>&1) the output is still only the first three lines from the terminal output.

Is there anyone who can help me think in the right direction towards a solution.

1 Answers

Message

Processing pages 1 through 1.
Page 1
 0.00000 0.00000 0.12363 CMYK OK

it is sent much later and not as ghostscript therefore php does not receive it. But it will be more convenient for you to use ghostscript for php

Documentation

Github link

Example:

<?php
use Org_Heigl\Ghostscript\Ghostscript;

// Create the Ghostscript-Wrapper
$gs = new Ghostscript ();

// Set the output-device
$gs->setDevice('jpeg')
// Set the input file
   ->setInputFile('path/to/my/ps/or/pdf/file')
// Set the output file that will be created in the same directory as the input
   ->setOutputFile('output')
// Set the resolution to 96 pixel per inch
   ->setResolution(96)
// Set Text-antialiasing to the highest level
   ->setTextAntiAliasing(Ghostscript::ANTIALIASING_HIGH);
// Set the jpeg-quality to 100 (This is device-dependent!)
   ->getDevice()->setQuality(100);
// convert the input file to an image
if (true === $gs->render()) {
    echo 'success';
} else {
    echo 'some error occured';
}
?>
Related