以前一直找到的资料都是教你怎么生成pdf文档,好比:TCPDF、FPDF、wkhtmltopdf。而我碰到的项目里须要验证从远程获取的pdf文件是否受损、文件内容是否一致这些问题,这些都不能直接提供给我读取pdf的功能,碰巧找到了一个能够读取并解析PDF文档的第三方类库PDFParser,该类库很是简单好用,能够直奔官网了解。php
我这里用的是CI框架,但均可用composer包管理方式安装到项目中,进行开发调用html
项目根目录下打开命令行并执行:composer update smalot/pdfparser
json
若是发现update不下来,能够修改当前项目的 composer.json 配置文件,打开命令行窗口(windows用户)或控制台(Linux、Mac 用户),进入你的项目的根目录(也就是 composer.json 文件所在目录),执行以下命令:
composer config repo.packagist composer https://packagist.phpcomposer.com
,再重试。固然,若是本地没安装composer,请前往composer官网自行安装。segmentfault
//引入pdf解析第三方类库 $vendorAutoloadFile = APPPATH.'..'.DIRECTORY_SEPARATOR.'vendor'.DIRECTORY_SEPARATOR.'autoload.php'; require_once($vendorAutoloadFile); $pdfFile = '/temp/label/HnEms/LS955518275CN.pdf'; //读取pdf,验证跟踪号是否一致 // Parse pdf file and build necessary objects. $parser = new \Smalot\PdfParser\Parser(); $pdfPath = $_SERVER['DOCUMENT_ROOT'].$pdfFile; $pdf = $parser->parseFile($pdfPath); $text = $pdf->getText(); echo $text; echo '<hr>'; // Retrieve all details from the pdf file. $details = $pdf->getDetails(); var_dump($details); die;
执行结果展现:
windows
这里验证pdf文档中跟踪号是否和提供的一致,不一致返回假,若pdf是损坏的则返回false。函数也提供了返回异常消息。composer
$trackingNumber = 'LS955518275CN'; $pdfFile = '/temp/label/Chukou1/3559675.pdf'; //仅验证pdf文件是否有效 //$result = verifyValidLabelPdf($trackingNumber, $pdfFile); //验证pdf是否有效,无效则返回无效的缘由 $result = verifyValidLabelPdf($trackingNumber, $pdfFile, true); var_dump($result); /** * 验证面单pdf文件是否完整(文件不存在、损坏和跟踪号不一致等状况) * @param string $trackingNumber 跟踪号 * eg. $trackingNumber = 'LS955518275CN'; * @param string $pdfFile pdf文件路径 * @param bool $showExceptionMessage 默认为false,不返回异常消息,为true时,出现异常会返回异常消息 * @return bool true pdf有效,false pdf无效 * * Attention please : 该方法异常处理千万不要去掉,第三方类库PdfParser解析PDF出错时会抛异常, * 这里的异常处理也能够接收PdfParser抛出来的异常信息,进行友好提示 */ function verifyValidLabelPdf($trackingNumber, $pdfFile, $showExceptionMessage = false) { try{ $pdfPath = $_SERVER['DOCUMENT_ROOT'].$pdfFile; //验证文件是否存在 if (!file_exists($pdfPath) || !is_file($pdfPath)){ throw new Exception('pdf文件不存在'); } //引入PdfParser第三方类库 $vendorAutoloadFile = APPPATH.'..'.DIRECTORY_SEPARATOR.'vendor'.DIRECTORY_SEPARATOR.'autoload.php'; require_once($vendorAutoloadFile); //读取pdf,验证跟踪号是否一致 // Parse pdf file and build necessary objects. $parser = new \Smalot\PdfParser\Parser(); $pdf = $parser->parseFile($pdfPath); $text = $pdf->getText(); //验证跟踪号是否一致 if (strpos($text, $trackingNumber) === false){ throw new Exception('跟踪号不一致'); } return true; }catch (Exception $ex){ //获取错误类型 pdf文件可能不存在、损坏等没法加载 if ($showExceptionMessage === true){ //接收异常提示消息并返回 $message = $ex->getMessage(); return $message; } return false; } }