PHP获取PDF文件页数

jerry thinkphp 2015年11月19日 收藏
这个函数虽然看起来好像没多大用处,不过在有些时候还是能用的上的。正在建立自己函数库的可以收藏一下。


提示:这个函数不是我原创的,原创的地址在这里http://hi.baidu.com/luanxian/item/06ab9d24be2b4e1409750879,我稍微添加了两行判断错误的代码。
下面给出代码:
  1. <?php
  2. /**
  3.  * 获取PDF文件页数的函数获取
  4.  * 文件应当对当前用户可读(linux下)
  5.  * @param  [string] $path [文件路径]
  6.  * @return [array]        [数组第一位表示成功与否,第二位表示提示信息]
  7.  */
  8. function getPdfPages($path){
  9.     if(!file_exists($path)) return array(false,"文件\"{$path}\"不存在!");
  10.     if(!is_readable($path)) return array(false,"文件\"{$path}\"不可读!");
  11.     // 打开文件
  12.     $fp=@fopen($path,"r");
  13.     if (!$fp) {
  14.         return array(false,"打开文件\"{$path}\"失败");
  15.     }else {
  16.         $max=0;
  17.         while(!feof($fp)) {
  18.             $line = fgets($fp,255);
  19.             if (preg_match('/\/Count [0-9]+/', $line, $matches)){
  20.                 preg_match('/[0-9]+/',$matches[0], $matches2);
  21.                 if ($max<$matches2[0]) $max=$matches2[0];
  22.             }
  23.         }
  24.         fclose($fp);
  25.         // 返回页数
  26.         return array(true,$max);
  27.     }
  28. }
  29.     /**
  30.      * 测试代码
  31.      */
  32.     $results=getPdfPages("demo.pdf");
  33.     if($results[0]){
  34.         // 在这里放置成功读取后的处理代码
  35.     }else{
  36.         // 在这里放置失败的处理代码
  37.     }
  38. ?>
性能方面,在我的ubuntu机器上读取1个600页左右的文件大概耗时1秒,应该是不会有太大问题。