如何使用PHP检测PDF文件或单页是否完全空白?
检测PDF页面是否完全空白的PHP方案
一、含文本的PDF检测(基于Smalot PDFparser)
- 通过Smalot PDFparser提取目标页面文本
- 去除所有空白字符后判断是否为空
- 示例代码:
use Smalot\PdfParser\Parser; $pdfParser = new Parser(); $pdf = $pdfParser->parseFile('target.pdf'); $pages = $pdf->getPages(); $targetPage = $pages[0]; // 检测第一页,索引从0开始 $cleanText = trim(preg_replace('/\s+/', '', $targetPage->getText())); if (empty($cleanText)) { echo "该页面无文本内容"; } else { echo "该页面包含文本"; }
二、纯图片型PDF的检测(基于Imagick像素分析)
对于仅含图片的PDF,需先将页面转成图片,再通过像素亮度判断是否空白:
实现步骤
- 用Imagick加载指定页码的PDF页面
- 转换为灰度图简化像素分析
- 统计像素亮度,判断是否全部接近纯白
示例代码
// 需确保服务器安装Imagick扩展及Ghostscript依赖 $imagick = new Imagick(); $imagick->setResolution(300, 300); // 分辨率越高检测精度越高 $imagick->readImage('target.pdf[0]'); // [0]对应第一页,索引从0开始 // 转为灰度图 $imagick->transformImageColorspace(Imagick::COLORSPACE_GRAY); $isBlank = true; $threshold = 250; // 接近纯白的像素阈值,可根据噪点情况调整 // 遍历所有像素 $pixelIterator = $imagick->getPixelIterator(); foreach ($pixelIterator as $row) { foreach ($row as $pixel) { $grayValue = $pixel->getColor()['r']; // 灰度图RGB值一致 if ($grayValue < $threshold) { $isBlank = false; break 2; // 跳出双层循环 } } } $imagick->clear(); $imagick->destroy(); echo $isBlank ? "该页面是空白页" : "该页面包含图片内容";
无Imagick时的替代方案(调用Ghostscript命令行)
若无法安装Imagick,可直接用Ghostscript生成单页图片再分析:
$pdfPath = 'target.pdf'; $pageNum = 1; // 页码从1开始 $tempImg = 'temp_page.png'; // 调用Ghostscript生成单页图片 $command = "gs -dQUIET -dBATCH -dNOPAUSE -sDEVICE=png16m -dFirstPage={$pageNum} -dLastPage={$pageNum} -r300 -sOutputFile={$tempImg} {$pdfPath}"; exec($command, $output, $returnCode); if ($returnCode !== 0) { echo "图片生成失败"; exit; } // 复用上面的像素分析逻辑 $imagick = new Imagick($tempImg); // ... 灰度转换、像素判断代码 ... // 清理临时文件 unlink($tempImg);
注意事项
- 阈值
$threshold可根据实际情况调整,避免误判带轻微噪点的空白页 - 分辨率设置需平衡检测精度和处理速度
- 确保服务器已安装Ghostscript,且PHP有exec命令执行权限(命令行方案)
内容的提问来源于stack exchange,提问作者azbatuk
相关产品推荐
相关产品推荐

