使用pdfparser读取PDF时地址行拆分问题及合并需求
解决PDF地址行被拆分为多行的问题
问题场景
使用pdfparser读取动态生成的PDF时,地址行因长度限制被拆分为多行,每行带有换行符,且地址长度不同导致拆分行数不固定,需要将完整地址合并为一行。
解决方案
方法1:基于文本特征的正则替换
如果地址前后有明确的标识(比如地址前有"Address:",后有"Phone:"这类固定字段),可以用正则匹配地址范围并替换内部换行。
修改后的代码示例:
$fileName = basename($_FILES["file"]["name"]); $fileType = pathinfo($fileName, PATHINFO_EXTENSION); // Allow certain file formats $allowTypes = array('pdf'); if(in_array($fileType, $allowTypes)){ // Include autoloader file include 'vendor/autoload.php'; // Initialize and load PDF Parser library $parser = new \Smalot\PdfParser\Parser(); // Source PDF file to extract text $file = $_FILES["file"]["tmp_name"]; // Parse pdf file using Parser library $pdf = $parser->parseFile($file); // Extract text from PDF $text = $pdf->getText(); // 合并地址行:匹配Address:到Phone:之间的内容,替换内部换行和多余空格 $pattern = '/(Address:)(.*?)(?=Phone:)/s'; $text = preg_replace_callback($pattern, function($matches) { $mergedAddress = preg_replace('/\s+/', ' ', $matches[2]); return $matches[1] . $mergedAddress; }, $text); // Add line break $pdfText = nl2br($text); }else{ $statusMsg = '<p>Sorry, only PDF file is allowed to upload.</p>'; }
方法2:利用PDF文本块位置信息合并
如果地址拆分是排版自动换行导致的(同一地址的多行左对齐且垂直间距极小),可以通过获取文本块的坐标判断是否属于同一地址。
修改后的代码示例:
$fileName = basename($_FILES["file"]["name"]); $fileType = pathinfo($fileName, PATHINFO_EXTENSION); // Allow certain file formats $allowTypes = array('pdf'); if(in_array($fileType, $allowTypes)){ // Include autoloader file include 'vendor/autoload.php'; // Initialize and load PDF Parser library $parser = new \Smalot\PdfParser\Parser(); // Source PDF file to extract text $file = $_FILES["file"]["tmp_name"]; // Parse pdf file using Parser library $pdf = $parser->parseFile($file); // 获取所有页面 $pages = $pdf->getPages(); $mergedText = ''; foreach ($pages as $page) { // 获取页面的文本块(包含内容和位置信息) $textBlocks = $page->getTextArray(); $previousBlock = null; $currentAddress = ''; foreach ($textBlocks as $block) { $blockText = trim($block['text']); if (empty($blockText)) continue; // 判断是否为地址续行:左坐标一致,垂直间距小于阈值(可根据PDF字号调整) if ($previousBlock && strpos($previousBlock['text'], 'Address:') !== false) { if (abs($block['bbox'][0] - $previousBlock['bbox'][0]) < 2 && abs($block['bbox'][1] - $previousBlock['bbox'][1]) < 15) { $currentAddress .= ' ' . $blockText; continue; } else { $mergedText .= 'Address:' . $currentAddress . "\n"; $currentAddress = ''; } } $mergedText .= $blockText . "\n"; $previousBlock = $block; } // 处理最后一个地址块 if (!empty($currentAddress)) { $mergedText .= 'Address:' . $currentAddress . "\n"; } } // 转换为HTML换行 $pdfText = nl2br($mergedText); }else{ $statusMsg = '<p>Sorry, only PDF file is allowed to upload.</p>'; }
方法3:通用换行合并(无明确标识场景)
如果地址本身不应有换行,且PDF中仅地址会被拆分,可以替换单个换行符为空格(保留段落间的空行):
// 在提取文本后添加: $text = preg_replace('/(?<!\n)\n(?!\n)/', ' ', $text);
注意:此方法可能误合并其他单行换行,需根据实际PDF内容调整。
内容的提问来源于stack exchange,提问作者Chaminda Chanaka
相关产品推荐
相关产品推荐

