Yii框架不内置PDF提取功能,需用Smalot/PdfParser等第三方库;安装后创建PdfTextExtractor服务类封装extractText和extractFromUploadedFile方法,在Controller中调用实现上传解析。

Yii 框架本身不内置 PDF 内容提取功能,需借助第三方 PHP PDF 解析库(如 Smalot/PdfParser、setasign/Fpdi 或 spipu/html2pdf 的反向解析能力有限,不推荐用于提取),并在 Yii 应用中封装调用。以下以轻量、稳定、支持中文(需注意编码)的 Smalot/PdfParser 为例,给出在 Yii 2.x 中实现 PDF 文本提取的完整操作流程与代码。
安装 PDF 解析依赖
在项目根目录执行:
- composer require smalot/pdfparser
安装后,Composer 会自动注册 autoloader,无需手动引入。
创建 PDF 提取服务类(推荐放于 common/services/ 或 components/)
新建 PdfTextExtractor.php:
namespace common\services;
<p>use Smalot\PdfParser\Parser;</p><p>class PdfTextExtractor
{
/**</p>
-
从本地 PDF 文件路径提取纯文本内容
@param string $filePath PDF 文件绝对路径(需存在且可读)
-
@return string 提取的文本,失败时返回空字符串 */ public static function extractText($filePath) { if (!is_file($filePath) || !is_readable($filePath)) { return ''; }
try { $parser = new Parser(); $pdf = $parser->parseFile($filePath); return trim($pdf->getText()); } catch (\Exception $e) { \Yii::error('PDF text extraction failed: ' . $e->getMessage(), 'pdf.extract'); return ''; } }
/**
* 从上传的 UploadedFile 实例提取文本(常用于表单上传后立即处理)
* @param \yii\web\UploadedFile $uploadedFile
* @return string
*/
public static function extractFromUploadedFile($uploadedFile)
{
if (!$uploadedFile || !$uploadedFile->tempName) {
return '';
}
return self::extractText($uploadedFile->tempName);
}
}
在 Controller 中调用提取逻辑
例如在 SiteController 中添加一个上传并提取接口:
use yii\web\UploadedFile;
use common\services\PdfTextExtractor;
<p>public function actionExtractPdf()
{
$model = new \yii\base\Model(); // 简单场景可不用 ActiveRecord</p><pre class="brush:php;toolbar:false;">if (\Yii::$app->request->isPost) {
$uploadedFile = UploadedFile::getInstance($model, 'pdf_file');
if ($uploadedFile && $uploadedFile->extension === 'pdf') {
$text = PdfTextExtractor::extractFromUploadedFile($uploadedFile);
if (!empty($text)) {
// 示例:保存到数据库或返回 API 响应
return $this->asJson(['success' => true, 'text' => mb_substr($text, 0, 1000)]); // 截断防超长
} else {
return $this->asJson(['success' => false, 'message' => 'PDF 内容为空或解析失败']);
}
} else {
return $this->asJson(['success' => false, 'message' => '请上传有效的 PDF 文件']);
}
}
return $this->render('extract-pdf');
}
注意事项与增强建议
- 中文支持:Smalot/PdfParser 能较好识别多数含中文字体的 PDF(尤其 Adobe Acrobat 生成的),但若 PDF 使用非标准嵌入字体或图片型 PDF(即扫描件),则无法提取文字——此时需先 OCR(如 Tesseract + imagick),Yii 中需额外集成。
-
内存与超时:大 PDF(>50MB)可能导致内存溢出或超时,建议在
php.ini中临时调整:memory_limit=256M、max_execution_time=120,生产环境应加队列异步处理。 -
安全校验:务必验证上传文件 MIME 类型(不能只靠扩展名),可用
$uploadedFile->getMimeType()判断是否为application/pdf。 -
结构化提取:如需提取标题、表格、页码等,Smalot 支持获取页面对象、元数据、字体信息,可进一步遍历
$pdf->getPages()手动解析布局(较复杂,需结合 PDF 结构知识)。











