Skip to content
Advertisement

Convert PDF to PNG without transparent background

I use the following code to convert PDF to PNG. As you can see, I use code setImageAlphaChannel(Imagick::ALPHACHANNEL_REMOVE ) to remove the background transparency. But in practice it only works for the last page. Do you think there is a problem with the code? Do you have a better solution with a higher speed?

$PDF = 'test.pdf';
$img = new imagick();
$img->readImage($PDF.'[0-9]'); //Convert 10 pages
$img->setImageAlphaChannel(Imagick::ALPHACHANNEL_REMOVE );
$pages = count($img);
$img->writeImages('./images/'.'pdf.png', true);

Advertisement

Answer

This looks like an iterator issue. You can try looping with something like this:

<?php

$PDF = 'test.pdf';
$img = new Imagick();
$img->readImage($PDF. '[0-9]');  //Convert 10 pages

$lastIndex = $img->getIteratorIndex();
$img->resetIterator();

for($i = $img->getIteratorIndex(); $i <= $lastIndex; $i++) {
    $img->setIteratorIndex($i);
    $img->setImageAlphaChannel(Imagick::ALPHACHANNEL_REMOVE);
}

$pages = count($img); // not sure why you need this
$img->writeImages('./images/'.'pdf.png', true);

You could also get the iterating part down to a simple loop, if you like it more, since the Imagick class implements Iterator:

foreach($img as $i)
{
    $img->setImageAlphaChannel(Imagick::ALPHACHANNEL_REMOVE);
}
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement