Count the total pages of a PDF using PHP

Asked

Viewed 221 times

-1

Good afternoon to all,

I developed a code that returns as output the total pages of Pdfs of a specific directory.

I could even read the total pages, but it stops running after reading the first PDF of the directory.

An Obs: My folder structure is as follows:

root
| _In
   |'anos'
      |'meses'
         |'Arqs'

If anyone can help me, I’d really appreciate it!

Follow the code below:

include 'vendor/autoload.php';

$_DS = DIRECTORY_SEPARATOR;
$rootPath = dirname(__FILE__);
$_In = $rootPath.$_DS.'_In';

if(isset($_POST['btn'])){ 

    for($ano = 1977; $ano <=2019; $ano++){ $subInY = $_In.$_DS.$ano; $Out = $_Out.$_DS.$ano;

        if(is_dir($subInY)){ /*echo "<br>".$subInY.'<br>';*/ } 

        for($mes = 1; $mes <= 12; $mes++){ $subInM = $subInY.$_DS.$mes; $subOutM = $Out.$_DS.$mes; 

            if(is_dir($subInM)){ /*echo $subInM.'<br>';*/ 

                $in = new DirectoryIterator($_In);
                $siy = new DirectoryIterator($subInY);

                foreach($in as $p1){ if($p1->isDot()) continue; foreach($siy as $p2){ if($p2->isDot()) continue; } }    


                $arq2 = glob("{$subInM}\*.pdf");

                foreach($arq2 as $file){ 


                    echo '<br>'.$file.'<br>';


                    // ======================= ParserPDF

                    $parser  = new \Smalot\PdfParser\Parser();
                    $pdf     = $parser->parseFile($file);

                    $details = $pdf->getDetails();                  
                    foreach ($details as $property => $value) { 
                        if (is_array($value)) {
                            $value = implode(', ', $value); }

                    if($property == "Pages"){  
                        echo "<br>" . $property . ' => ' . $value . "<br>\n";}

                    }

                    set_time_limit(3000);   

                    // ========================     

                }           
    } } }

}

2 answers

0

I use this function here:

function count_pages($pdfname) {
  $pdftext = file_get_contents($pdfname);
  $num = preg_match_all("/\/Page\W/", $pdftext, $dummy);
  return $num;
}
  • Jasar, this $dummy variable, would be what?

  • I’m sorry, but I couldn’t see how to enter my code.

  • knows where you upload the pdf as a file ? $file takes the address and the full file name and uses this function q passed

  • Jasar, this $dummy variable, would be what?

  • according to the documentation is where he plays the Matches of what he found in regex https://www.php.net/manual/en/function.preg-match-all.php , but we don’t need the results. Just count them

0

Use Imagick, I’ve come across this doubt once

$im = new Imagick();
$im->pingImage('name_of_pdf_file.pdf');
$pagesCount = $im->getNumberImages();

Browser other questions tagged

You are not signed in. Login or sign up in order to post.