Convert pdf to image with pdftoppm in php without writing files on disk

1.5k views Asked by At

I need to convert pdf to png in php. Because of quality reasons we don't want to use Imagemagick but prefer to use pdftoppm.

For performance we prefer not to use the filesystem, but the memory.

pdftoppm is properly installed on Ubuntu and works.

For another project (html -> pdf) we use the following code:

//input is $html

$descriptorSpec =
[
    0 => ['pipe', 'r'],
    1 => ['pipe', 'w'],
    2 => ['pipe', 'w']
];

$command = 'wkhtmltopdf --quiet  - -';

$process = proc_open($command, $descriptorSpec, $pipes);

fwrite($pipes[0], $html);
fclose($pipes[0]);
$pdf = stream_get_contents($pipes[1]);
$errors = stream_get_contents($pipes[2]);
if ($errors)
{
    $errors = ucfirst(strtr($errors, [
        'sh: wkhtmltopdf: ' => '',
        PHP_EOL => ''
    ]));
    throw new Exception($errors); 
}
fclose($pipes[1]);
$return_value = proc_close($process);

//output is $pdf

This works perfect!

But if I use this code to do the same with pdftoppm, it does not work, what do I do wrong ?

//input is $pdf

$descriptorSpec =
[
    0 => ['pipe', 'r'],
    1 => ['pipe', 'w'],
    2 => ['pipe', 'w']
];

$command = 'pdftoppm -png  - -';

$process = proc_open($command, $descriptorSpec, $pipes);

fwrite($pipes[0], $pdf);
fclose($pipes[0]);
$png = stream_get_contents($pipes[1]);
$errors = stream_get_contents($pipes[2]);
if ($errors)
{
    $errors = ucfirst(strtr($errors, [
        'sh: pdftoppm: ' => '',
        PHP_EOL => ''
    ]));
    throw new Exception($errors); 
}
fclose($pipes[1]);
$return_value = proc_close($process);

//output is $png

Thanks upfront for tips and sugestions Sorry for my bad English..

1

There are 1 answers

0
David Van De Walle On BEST ANSWER

Ok, fixed it myself!

removed the hyphens.

$command = 'pdftoppm -png ';

Thanks for all the support !