This commit is contained in:
KONE SOREL 2026-03-28 11:46:50 +00:00
parent 4009cc68b8
commit 8f823ac269

View File

@ -9,4 +9,88 @@ require_once 'Localisation.php';
abstract class Controleurrequete extends Controleur
{
}
function pdf_to_image($fichierSimple, $uniqid)
{
$inputPdf = dirname(__DIR__) . "/".$fichierSimple; // PDF dorigine
$path_parts = pathinfo($inputPdf);
$outputPdf = $path_parts["dirname"]."/TMP_$uniqid.pdf"; // PDF final "image-only"
$fichier="Temp/TMP_$uniqid.pdf";
// $dpi = 300; // 150 si tu veux alléger
$dpi = 150; // 150 si tu veux alléger
$quality = 90; // JPEG quality
// dossier temporaire
$tmpDir = sys_get_temp_dir() . '/pdf2img_' . uniqid();
if (!is_dir($tmpDir)) {
mkdir($tmpDir, 0777, true);
}
try {
$imagick = new Imagick();
// très important : définir la résolution AVANT readImage
$imagick->setResolution($dpi, $dpi);
$imagick->readImage($inputPdf);
$nbPages = $imagick->getNumberImages();
$imageFiles = [];
for ($i = 0; $i < $nbPages; $i++) {
$imagick->setIteratorIndex($i);
$page = $imagick->getImage();
// important : forcer un fond blanc si le PDF avait de la transparence
$page->setImageBackgroundColor('white');
$page = $page->mergeImageLayers(Imagick::LAYERMETHOD_FLATTEN);
// sortie en JPEG
$page->setImageFormat('jpeg');
$page->setImageCompression(Imagick::COMPRESSION_JPEG);
$page->setImageCompressionQuality($quality);
$imgPath = sprintf('%s/page-%03d.jpg', $tmpDir, $i + 1);
$page->writeImage($imgPath);
$imageFiles[] = $imgPath;
$page->clear();
$page->destroy();
}
// 1) on essaie img2pdf (plus propre)
$escapedImages = array_map('escapeshellarg', $imageFiles);
$cmd = 'img2pdf ' . implode(' ', $escapedImages) . ' -o ' . escapeshellarg($outputPdf);
exec($cmd, $o1, $r1);
if ($r1 !== 0) {
// 2) fallback : ImageMagick
// attention : certaines installations utilisent "convert" au lieu de "magick"
$cmd2 = 'magick ' . implode(' ', $escapedImages) . ' -density ' . intval($dpi) . ' -compress jpeg ' . escapeshellarg($outputPdf);
exec($cmd2, $o2, $r2);
if ($r2 !== 0) {
throw new Exception("Impossible de recomposer le PDF (img2pdf puis magick ont échoué)");
}
}
// nettoyage (optionnel)
foreach ($imageFiles as $f) {
@unlink($f);
}
@rmdir($tmpDir);
} catch (Exception $e) {
echo "Erreur : " . $e->getMessage();
exit();
}
// Fin conversion
// supprimer $inputPdf
@unlink($inputPdf);
$t_html =' <div id ="div_export_a" class="alert alert-info"> ';
$t_html .=' <a style="font-size:15pt;" href="'.$fichier.'" target="_blank" > TELECHARGER </a> ';
$t_html .=' </div ';
echo $t_html;
}