把图片和PDF合并成一个pdf文件存储
注意:这个mdpf对有的PDF文件无效,建议使用wps转换的pdf.
1.composer 引入mdpf.
2.确认系统对文件路径有读写权限。
<?php
namespace App\Helpers;
use Mpdf\Mpdf;
class PdfHelper
{
/*
功能:使用Mpdf 把文件目录下的所有图片和pDF整合一起成为一个PDF
$directory 文件目录
$outputFile 输出的目录
*/
public static function mergeAndDeleteFiles($directory, $outputFile)
{
$filePaths = [];
// 获取目录中的所有图片和 PDF 文件路径
$files = scandir($directory);
foreach ($files as $file) {
if ($file != '.' && $file != '..') {
$filePath = $directory . '/' . $file;
$filePaths[] = $filePath;
}
}
// 创建一个新的 mPDF 实例
$mpdf = new Mpdf();
// 遍历文件路径,将每个文件添加到 PDF 中
foreach ($filePaths as $filePath) {
$fileExtension = pathinfo($filePath, PATHINFO_EXTENSION);
// 如果文件是图片,则将其添加为一个新的 PDF 页面并填充整个页面
if (in_array($fileExtension, ['jpg', 'jpeg', 'png', 'gif'])) {
$mpdf->AddPage();
// 调整图片尺寸以填充整个页面
$image = imagecreatefromstring(file_get_contents($filePath));
$width = imagesx($image);
$height = imagesy($image);
$pageWidth = $mpdf->w - ($mpdf->lMargin + $mpdf->rMargin);
$pageHeight = $mpdf->h - ($mpdf->tMargin + $mpdf->bMargin);
$imageRatio = $width / $height;
$pageRatio = $pageWidth / $pageHeight;
if ($imageRatio > $pageRatio) {
$newWidth = $pageWidth;
$newHeight = $pageWidth / $imageRatio;
} else {
$newWidth = $pageHeight * $imageRatio;
$newHeight = $pageHeight;
}
// 计算图片在页面上的位置
$x = ($pageWidth - $newWidth) / 2 + $mpdf->lMargin;
$y = ($pageHeight - $newHeight) / 2 + $mpdf->tMargin;
// 将调整后的图片添加到 PDF 页面中
$mpdf->Image($filePath, $x, $y, $newWidth, $newHeight);
}
}
// 遍历文件路径,将每个 PDF 文件合并到当前 PDF 中
foreach ($filePaths as $filePath) {
$fileExtension = pathinfo($filePath, PATHINFO_EXTENSION);
// 如果文件是 PDF,则将其合并到当前 PDF 中
if ($fileExtension == 'pdf') {
$mpdf->SetSourceFile($filePath);
for ($i = 1; $i <= $mpdf->SetSourceFile($filePath); $i++) {
$tplIdx = $mpdf->ImportPage($i);
$mpdf->AddPage();
$mpdf->UseTemplate($tplIdx);
}
}
}
// 将 PDF 写入输出文件
$mpdf->Output($outputFile, 'F');
// 删除原始的图片和 PDF 文件
foreach ($filePaths as $filePath) {
unlink($filePath);
}
}
}
本作品采用《CC 协议》,转载必须注明作者和本文链接
第一行 说明mypdf打错字了吧