phpajaximagick

Convert multiple images to a pdf using Imagick


In the following code $_POST['images'] is sent via Ajax and the code is the response. The problem is all images are in a single page of the created pdf file, I want each image to be in a separate page.

$images = $_POST['images'];


$pdf = new Imagick();
$pdf->setFormat('pdf');

foreach ($images as $dataURL) {
    $data = substr($dataURL, strpos($dataURL, ',') + 1);
    $image = base64_decode($data);

    $imagick = new Imagick();
    $imagick->readImageBlob($image);

    $pdf->addImage($imagick);
}

$pdf->resetIterator();
$pdf = $pdf->appendImages(true);
        
header('Content-Type: applicaton/pdf');
echo $pdf->getImagesBlob();
$pdf->destory();

Solution

  • The function Imagick::writeImages takes two parameters file name and adjoin. If adjoin is set to true then each image is a separate page of the pdf (documentation). Furthermore if we call this function and set adjoin to true then when the PDF is echoed each image is on a separated page. Using this we can have something like the following code:

    $images = $_POST['images'];
    
    
    $pdf = new Imagick();
    $pdf->setFormat('pdf');
    
    foreach ($images as $dataURL) {
        $data = substr($dataURL, strpos($dataURL, ',') + 1);
        $image = base64_decode($data);
    
        $imagick = new Imagick();
        $imagick->readImageBlob($image);
    
        $pdf->addImage($imagick);
    }
    
    
    // First we create a temporary file and write the pdf to it
    $temp_name = '/tmp/output.pdf';
    $pdf->writeImages($temp_name, true); // adjoin is true
    unlink($temp_name); // Delete the temporary file
    
    header('Content-Type: applicaton/pdf');
    echo $pdf->getImagesBlob();
    $pdf->destory();
    

    Notice that we have removed

    $pdf->resetIterator();
    $pdf = $pdf->appendImages(true);
    

    in the above code