You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP提取PDF中#开头标题报错:调用未定义方法getPageContent()

解决PHP提取PDF中#开头标题的错误及方案

错误原因

你遇到的Call to undefined method setasign\Fpdi\Tcpdf\Fpdi::getPageContent()错误,是因为FPDI(Tcpdf版本)并没有提供getPageContent()方法。FPDI的定位是PDF页面导入与编辑工具,不具备文本提取能力,调用不存在的方法会触发致命错误。

解决方案:使用专门的PDF文本解析库

推荐使用Smalot/PdfParser,这是一款专门用于解析PDF并提取文本的PHP库,操作简单且适配性强。

步骤1:安装库

通过Composer安装:

composer require smalot/pdfparser

步骤2:编写提取代码

以下脚本会下载目标PDF,提取所有页面文本,匹配并输出以#开头的标题:

<?php
require_once 'vendor/autoload.php';

// 目标PDF链接
$pdfUrl = 'https://afxwebdesign.com/order.pdf';
// 临时保存PDF到本地
$localPdf = tempnam(sys_get_temp_dir(), 'pdf_');
file_put_contents($localPdf, file_get_contents($pdfUrl));

// 初始化PDF解析器
$parser = new \Smalot\PdfParser\Parser();
$pdf = $parser->parseFile($localPdf);

// 提取所有页面文本
$text = $pdf->getText();

// 匹配以#开头的标题(多行模式)
preg_match_all('/^#[^#].*$/m', $text, $headings);

// 输出结果
if (!empty($headings[0])) {
    foreach ($headings[0] as $heading) {
        echo trim($heading) . "\n";
    }
} else {
    echo "未找到以#开头的标题";
}

// 删除临时文件
unlink($localPdf);
?>

替代方案:使用TCPDF内置文本提取功能

若坚持使用TCPDF,可利用其内置的文本提取方法(注意:对部分PDF格式兼容性有限):

<?php
require_once('tcpdf.php');

// 目标PDF链接
$pdfUrl = 'https://afxwebdesign.com/order.pdf';
$localPdf = tempnam(sys_get_temp_dir(), 'pdf_');
file_put_contents($localPdf, file_get_contents($pdfUrl));

// 初始化TCPDF对象
$pdf = new TCPDF();
// 打开PDF文件
$pdf->setSourceFile($localPdf);
$pageCount = $pdf->getNumPages();

for ($pageNo = 1; $pageNo <= $pageCount; $pageNo++) {
    // 获取页面文本
    $text = $pdf->getPageText($pageNo);
    // 匹配标题
    preg_match_all('/^#[^#].*$/m', $text, $headings);
    
    foreach ($headings[0] as $heading) {
        echo trim($heading) . "\n";
    }
}

// 删除临时文件
unlink($localPdf);
?>

注意事项

  • 确保服务器允许file_get_contents()访问外部URL,若禁止可使用cURL替代下载PDF。
  • 若PDF为图片扫描件,无法直接提取文本,需配合OCR工具(如Tesseract)处理。
  • 正则表达式/^#[^#].*$/m匹配行首以单个#开头的内容,若需匹配多级标题(如##),可调整为/^#+.*/m。

内容的提问来源于stack exchange,提问作者Kamran Shah

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 21:07:43