繁体   English   中英

PHP - 将 base64 文件内容转换为 PDF

[英]PHP - Convert base64 file content to PDF

我在 Symfony 中有一个 API,在 React 中有一个前端。 我正在尝试上传文档(jpg、png 或 pdf),但我只想将 pdf 文件存储在我的目录中。 因此,当用户发送图像时,我想在上传之前将其转换为 pdf。

    public function upload($rawData, $extension, $key, &$contentType)
    {
        $rawData = explode(';base64,', $rawData);
        $contentType = substr($rawData[0], 5);
        $rawFileData = $rawData[1];

        if ($extension !== "pdf" && $extension !== "PDF") {
            $tmpDir = '/tmp';
            $image = $tmpDir . '/' . $key . '.' . $extension;
            file_put_contents($image, base64_encode($rawFileData));

            $imagick = new \Imagick();
            $imagick->readImage($image) ;
            $imagick->writeImages($tmpDir. '.pdf', false) ;
        }
    }

我试过使用 Imagick 库,但它给了我一个错误,比如“转换:不是 JPEG 文件”。 有什么问题或者是另一个更好的图书馆来做这件事?

我最终使用 fpdf 和 fpdi 库

composer require setasign/fpdf
composer require setasign/fpdi
 public function upload($rawData, $extension, $key, &$contentType)
 {
     $rawData = explode(';base64,', $rawData);
     $contentType = substr($rawData[0], 5);
     $rawFileData = $rawData[1];

     if ($extension !== "pdf" && $extension !== "PDF") {
         // upload image
         $tmpDir = $this->getParameter('tmpDir');
         $image = $tmpDir . '/' . $key . '.' . $extension;
         file_put_contents($image, base64_decode($rawFileData));

         // create pdf and upload it
         $pdf = new Fpdi();
         $pdf->AddPage();
         $pdfFile = $tmpDir . '/' . $key . '.pdf';
         $pdf->Image($image,0,0,$pdf->GetPageWidth(),$pdf->GetPageHeight());
         $pdf->Output('F', $pdfFile);

         //get pdf raw data
         $data = file_get_contents($pdfFile);
         $rawData = 'data:application/pdf;base64,' . base64_encode($data);
         unlink($image);
     }
}

我的 services.yml :

parameters:
    tmpDir: '%kernel.project_dir%/public/tmp'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM