Total PDF Pages Count in PHP Tutorial

Reading Time: 3 minutes
3,935 Views

Inside this article we will see the concept of counting total pdf pages in php. Article contains classified information which provides total pdf pages count in PHP.

If you are looking for an article which makes you understand to count total pdf pages in PHP then you are at right place to get it.

Sometime, you just need to count how many pages are there in a pdf file and show it for admin panel or front-end. So this article give you very simple example of getting calculate number of pages in pdf file using core php. But you can also use the same concept in php, laravel, codeigniter framework too.

Learn More –

Let’s get started.


Create an Application – PDF Pages Count

Create a folder with name pdf-page-count at your localhost directory.

Create a file index.php inside this. Consider few PDF files in this folder for understanding.

Folder contains these files –

  • index.php
  • sample.pdf
  • sample-pdf-file.pdf

Open index.php and write this complete code into it.

<?php

// Pdf file path
$sample_pdf_path = 'sample.pdf';
$total_pdf_Pages = countPages($sample_pdf_path);
  
echo "PDF 1 Pages: ".$total_pdf_Pages;

echo "<br/>";

$sample_pdf2_path = 'sample-pdf-file.pdf';
$total_pdf2_Pages = countPages($sample_pdf2_path);

echo "PDF 2 Pages: ".$total_pdf2_Pages;

// Function to count total number of pages in pdf file
function countPages($path) {
  $pdftext = file_get_contents($path);
  $num = preg_match_all("/\/Page\W/", $pdftext, $dummy);
  return $num;
}

Concept to count total pdf pages –

// Function to count total number of pages in pdf file
 function countPages($path) {
   $pdftext = file_get_contents($path);
   $num = preg_match_all("/\/Page\W/", $pdftext, $dummy);
   return $num;
 }

Call function

$total_pdf_Pages = countPages($sample_pdf_path);

Application Testing

Open URL – http://localhost/pdf-page-count/index.php

We hope this article helped you to learn Total PDF Pages Count in PHP Tutorial in a very detailed way.

Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.

Sanjay KumarHello friends, I am Sanjay Kumar a Web Developer by profession. Additionally I'm also a Blogger, Youtuber by Passion. I founded Online Web Tutor and Skillshike platforms. By using these platforms I am sharing the valuable knowledge of Programming, Tips and Tricks, Programming Standards and more what I have with you all. Read more