Конвертируйте PDF несколько страниц с помощью imagick php, создавайте двойные файлы - PullRequest
0 голосов
/ 28 апреля 2019

Я загружаю файл, если он типа "PDF", он ищет, если он имеет несколько страниц.Если страницы> 1, создайте преобразование двух изображений.Так что это работает, но у меня есть двойное преобразование, поэтому, если у меня есть PDF-файл с 2 страницами, он создает 4 файла, 2 - это продажи с разными именами.почему?

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';
            }
        }

    }
}

Итак, преобразование в порядке, но если у pdf есть 2 страницы, у меня есть 4 файла:

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

пара m1 -.... - это та же пара m2-...

1 Ответ

0 голосов
/ 29 апреля 2019

Итак, это правильно, но я не могу получить новое последовательное имя файла без использования трюка с str_replace. Если я использую getImageFilename (), я получаю только последнее имя файла

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';
            }
        }
...