Find out number of pages in a file (Doc,TXT.PDF .etc)

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • sharugan
    New Member
    • Sep 2006
    • 1

    Find out number of pages in a file (Doc,TXT.PDF .etc)

    Hi All,

    I have requirement to find out the number of pages in a document.
    The document could be DOC , TXT ,PDF images etc.I want to be able to upload and find out number of pages in an uploaded document.

    Can any expert guid me a way in PHP to accomblish this tak.

    Help would be appreciated.!

    thanks'
  • coffeemist
    New Member
    • Nov 2007
    • 1

    #2
    You can find the number of pages in a PDF document by using the following code, using PHP4:

    Code:
    		//where $file is the full path to your PDF document.
    		if(file_exists($file)) {
                            //open the file for reading
    			if($handle = @fopen($file, "rb")) {
    				$count = 0;
    				$i=0;
    				while (!feof($handle)) {
    					if($i > 0) {
    						$contents .= fread($handle,8152);
    					}
    					else {
    		  				$contents = fread($handle, 1000);
    						//In some pdf files, there is an N tag containing the number of
    						//of pages. This doesn't seem to be a result of the PDF version.
    						//Saves reading the whole file.
    						if(preg_match("/\/N\s+([0-9]+)/", $contents, $found)) {
    							return $found[1];
    						}
    					}
    					$i++;
    				}
    				fclose($handle);
    				
    				//get all the trees with 'pages' and 'count'. the biggest number
    				//is the total number of pages, if we couldn't find the /N switch above.				
    				if(preg_match_all("/\/Type\s*\/Pages\s*.*\s*\/Count\s+([0-9]+)/", $contents, $capture, PREG_SET_ORDER)) {
    					foreach($capture as $c) {
    						if($c[1] > $count)
    							$count = $c[1];
    					}
    					return $count;			
    				}
    			}
    		}
    		return 0;
    it has worked with all the PDF docs i've used it with so far, irrelevant of PDF version. I imagine a similar approach could be used for at least .DOC files though i haven't tested that out.

    Comment

    • assimlation
      New Member
      • Nov 2007
      • 9

      #3
      for txt and probably doc you can use:

      [code=php]
      <?php
      $filename = "file.php";
      $num = count(file($fil ename));
      echo $num;
      ?>
      [/code]

      Comment

      • amyh2028
        New Member
        • Oct 2009
        • 1

        #4
        Hi coffeemist,

        I tested your code. It works some of the pdf files, but it doesn't work for the pdf files that contain all the images. It returns page count 0. I need to determine page count in user uploaded pdf files either in php or perl. Any help will be greatly appreciated.

        Thank you very much!

        Amy

        Comment

        Working...