Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
PDF Compare with PHP and ImageMagick
<?php
declare(strict_types=1);
$controlDocument = new Imagick();
$compareDocument = new Imagick();
// Optionally control the fuzz distance
// $controlDocument->setOption('fuzz', '2%');
// Set image resolution
// $controlDocument->setResolution(100, 100);
// $compareDocument->setResolution(100, 100);
// Load documents
$controlDocument->readImage('control.pdf');
$compareDocument->readImage('compare.pdf');
// Compare images using AE metric
$result = $controlDocument->compareImages($compareDocument, Imagick::METRIC_ABSOLUTEERRORMETRIC);
// Calculate percentage
$diffPercentage = $result[1] * 100 / ($controlDocument->getImageWidth() * $controlDocument->getImageHeight());
echo "Document is " . number_format($diffPercentage, 4) . "% different.";
// Save reconstructed image
$result[0]->setImageFormat("png");
file_put_contents('test.png', $result[0]);
echo PHP_EOL;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment