Convert PDF multiple page with imagick php create double files

887

I upload a file, if is type "pdf" it search if it has multiple pages. If pages are > 1 so create two images conversion. So it works but I have a duplicate conversion, so if I have a pdf with 2 pages it create 4 files, 2 are sales with different names. why?

if (isset($_POST)) {

    // setto il tipo di file
    $type = "png";

    // se ho caricaato il file
    if (!empty($_FILES['fileToUpload'])) {
        $file_name = $_FILES['fileToUpload']['name'];//Get file name with extension
        $file_type = $_FILES['fileToUpload']['type'];//Get only extension
        $file_size = $_FILES['fileToUpload']['size'];//Get File Size
        $file_tmp  = $_FILES['fileToUpload']['tmp_name'];//Temporary file name that saves in the computer to be processed
        $filesplit = pathinfo($file_name, PATHINFO_FILENAME);//Get only the name of file without extension
        // I haven't set file size restriction as DICOM files would be more than 5MB
        // If you wanna restrict files with size greater than 1MB just add the condition
        // if($file_size > 1048576){ and finish the 'if' at appropriate line. Size is defined in KB

        $file = $uploadpath.$file_name;
        move_uploaded_file($file_tmp, $file);

        // recupero il nome + estensione del file caricato
        $path_parts = pathinfo($_FILES["fileToUpload"]["name"]);

        // recupero solo il nome del file SENZA estensione
        $nome_file = $path_parts["filename"];

        // trasformo il nome del file nella notazione seo friendly
        $nome_file = seo_friendly_url($nome_file);

        // recupero estensione del file
        $estensione_file = $path_parts['extension'];

        // rinomino il file che ho caricato originale con nome seo friendly e aggiungo _BAK
        $file_copia_rinominato = $uploadpath.$nome_file.'_BAK'.'.'.$estensione_file;

        // copio il file nella stessa directory
        copy($file, $file_copia_rinominato);

        // leggo tutti i file a 288 dpi

        $newname = time().'_converted.'.$type;//Rename file and set extension

        // imposto la variabile che conta il numero di pagine
        $variabile_nome = 0;

        //preparo array per memorizzare il nome delle pagine
        $array_multiplagina = array();

        if ($estensione_file == "pdf") {
            $imagick = new Imagick();//Define imagick function

            $imagick->setResolution(288, 288);

            $imagick->readImage($file);//Read the file
            $imageprops = $imagick->getImageGeometry();
            $imagick->setImageUnits(imagick::RESOLUTION_PIXELSPERINCH);
            $imagick->setImageResolution(288, 288);
            $imagick->resampleImage(288, 288, imagick::FILTER_UNDEFINED, 0);

            $imagick->setImageBackgroundColor('white');
            $imagick->setCompressionQuality(100);
            $imagick->setCompression(Imagick::COMPRESSION_NO);
            $imagick->setImageFormat("png");
            $imagick->setImageDepth(8/* bits */);
            // Set all other properties

            $pages = $imagick->getNumberImages();

            // vedo il numero di pagine
            echo "il numero di pagine è:".$pages;// debug
            echo "<br>";// debug
            if ($pages > 1) {
                foreach ($imagick as $index => $pdf_image) {
                    $variabile_nome++;

                    $nome_file_multiplo = "m".$variabile_nome."-".$newname;

                    echo $nome_file_multiplo;// debug
                    echo "<br>";// debug

                    $create = $imagick->writeImages('uploads/'.$nome_file_multiplo, false);//Write the file to uploads folder

                    echo $create; // debug
                    echo "<br>"; // debug

                    echo "pdf multipagina"; // debug

                    //$pdf_image->writeImage('destination/path/' . $index . '-image_file.jpg');
                    $nome_ogni_file = $nome_file_multiplo;
                    echo "<br>";// debug
                    // trick to retrieve the name
                    $array_multipagina[] = str_replace(".png", "-1.png", $nome_ogni_file);

                }

                // stampo array se è multipagina
                print_r($array_multipagina);
            } else {
                echo 'PDF non è multipagina';
            }
        }

    }
}

So, the conversion is ok but if pdf has 2 pages I have 4 files:

- m1-1556471596_converted-0.png
- m1-1556471596_converted-1.png
- m2-1556471596_converted-0.png
- m2-1556471596_converted-1.png

the couple m1-.... are same the couple m2-...

187

Answer

Solution:

So, this is right, but I'm not able to retrieve the new sequential filename without using a "trick" with the str_replace. If I use getImageFilename () I get only the last filename

if ($estensione_file == "pdf") {
            $imagick = new Imagick();//Define imagick function

            $imagick->setResolution(288, 288);

            $imagick->readImage($file);//Read the file
            $imageprops = $imagick->getImageGeometry();
            $imagick->setImageUnits(imagick::RESOLUTION_PIXELSPERINCH);
            $imagick->setImageResolution(288, 288);
            $imagick->resampleImage(288, 288, imagick::FILTER_UNDEFINED, 0);

            $imagick->setImageBackgroundColor('white');
            $imagick->setCompressionQuality(100);
            $imagick->setCompression(Imagick::COMPRESSION_NO);
            $imagick->setImageFormat("png");
            $imagick->setImageDepth(8/* bits */);
            // Set all other properties

            // recupero il numero di pagine del pdf
            $pages = $imagick->getNumberImages();

            // vedo il numero di pagine
            echo "il numero di pagine è:".$pages;
            echo "<br>";

            // converto tutte le pagine in png e vengono numerate aggiungendo -0 prima dell'estensione del file
            $create = $imagick->writeImages('uploads/'.$newname, false);//Write the file to uploads folder

            // se le pagine sono maggiori di 1 allora riempio un array con i nomi sequenziali delle pagine
            if ($pages > 1) {

                echo '<br>';
                echo $newname;
                echo '<br>';
                // inizializzo a 0 una variabile per recuperare il nome
                $conta_pagine = 0;
                for ($indice = 1; $indice <= $pages; $indice++) {

                    echo "pdf multipagina";

                    $nome_ogni_file = str_replace('.png', '-'.$conta_pagine.'.png', $newname);
                    echo "<br>";

                    $array_multipagina[] = $nome_ogni_file;
                    $conta_pagine++;

                }

                // stampo array se è multipagina
                print_r($array_multipagina);
            } else {
                echo 'PDF non è multipagina';
            }
        }

People are also looking for solutions to the problem: The second method in controller doesn't work PHP MVC

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.