使用 composer require spatie/pdf-to-image标签:fileSystem,fileName,pageNumber,env,列表,pdf,fileUrl,php From: https://www.cnblogs.com/sdfgdrg/p/18074878
服务器需要安装ImageMagick,并且将/etc/ImageMagick-6/policy.xml
找到pdf这一行,注释掉或者增加读、写、编译
<policy domain="coder" rights="read|write|decode" pattern="PDF" />
public function pdfToImage(RequestInterface $request): ResponseInterface
{
$fileUrl = $request->input('fileUrl');
$client = new Client();
$ossclient = new OssClient(env('accessId'), env('accessSecret'), env('endpoint'));
// 下载PDF文件内容
$response = $client->get($fileUrl);
$pdfContent = (string)$response->getBody();
// 获取存储路径或创建一个Filesystem实例(假设你使用了Flysystem适配器)
$fileSystem = new Filesystem();
$fileName = md5($fileUrl);
$check = BookshelfPdf::where('uuid', $fileName)->pluck('path');
if (count($check) == 0) {
$savePath = "public/pdf/{$fileName}.pdf"; // 替换为实际保存PDF的路径和文件名
// 将PDF内容写入本地文件
$fileSystem->append($savePath, $pdfContent);
$pdf = new Pdf($savePath);
$imageList = [];
foreach (range(1, $pdf->getNumberOfPages()) as $pageNumber) {
$imagePath = "public/images/page_$pageNumber.jpg";
$pdf->setPage($pageNumber)->saveImage($imagePath);
// 将生成的图片路径添加到图片列表
$ossclient->uploadFile(env('bucket'), "upload/pdfToImage/{$fileName}_page_$pageNumber.jpg", $imagePath);
$imageList[] = env('domain') . "/upload/pdfToImage/{$fileName}_page_$pageNumber.jpg";
$fileSystem->delete($imagePath);
BookshelfPdf::create([
'uuid' => $fileName,
'file_url' => $fileUrl,
'path' => env('domain') . "/upload/pdfToImage/{$fileName}_page_$pageNumber.jpg"
]);
}
$fileSystem->delete($savePath);
} else {
$imageList = $check;
}
return $this->response->success("查询成功",$imageList);
}