PHP使用FPDF/FPDI合并PDF时如何检测页面方向避免内容裁切
解决方案
你可以通过FPDI内置的getTemplateSize()方法获取每一页的实际尺寸,判断方向后动态设置新页面的方向即可解决裁切问题。
核心修改逻辑
- 导入单页PDF后调用
getTemplateSize()获取页面宽高 - 对比宽高值:宽度大于高度为横向(L),反之为竖向(P)
- 调用
addPage()时传入对应方向参数,匹配原PDF页面的尺寸
修改后的完整代码
/* APPEND PDFs */ $files = []; array_push($files, $upload_folder . '/' . $pdf_name); if($new_path != 0 && $ext == 'pdf'){ array_push($files, $new_path); } if($new_path1 != 0 && $ext1 == 'pdf'){ array_push($files, $new_path1); } if($new_path2 != 0 && $ext2 == 'pdf'){ array_push($files, $new_path2); } if($new_path3 != 0 && $ext3 == 'pdf'){ array_push($files, $new_path3); } if($new_path4 != 0 && $ext4 == 'pdf'){ array_push($files, $new_path4); } if($new_path5 != 0 && $ext5 == 'pdf'){ array_push($files, $new_path5); } if($new_path6 != 0 && $ext6 == 'pdf'){ array_push($files, $new_path6); } $pdf = new \setasign\Fpdi\Fpdi(); // iterate over array of files and merge foreach ($files as $file) { $pageCount = $pdf->setSourceFile($file); for ($i = 0; $i < $pageCount; $i++) { $tpl = $pdf->importPage($i + 1, '/MediaBox'); // 获取导入页面的尺寸 $tplSize = $pdf->getTemplateSize($tpl); // 判断页面方向 $orientation = $tplSize['width'] > $tplSize['height'] ? 'L' : 'P'; // 按原页面方向、尺寸添加新页 $pdf->addPage($orientation, [$tplSize['width'], $tplSize['height']]); $pdf->useTemplate($tpl); } } // output the pdf as a file $pdf->Output('F',$upload_folder . '/' . $pdf_name);
补充说明
原代码中存在两处可优化点:
- 原
pdf = new ...漏了变量标识$,已修正 - 原判断条件中的
&是位运算符,判断逻辑建议改为逻辑与&&避免异常
内容的提问来源于stack exchange,提问作者Ele
相关产品推荐
相关产品推荐

