【问题标题】:PHP - Convert base64 file content to PDFPHP - 将 base64 文件内容转换为 PDF
【发布时间】:2019-12-19 16:55:04
【问题描述】:

我有一个 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 文件”。出了什么问题,或者它是另一个更好的图书馆吗?

【问题讨论】:

  • 你的问题是?
  • 我已经更新了我的帖子。
  • 可能是上传错误?如果你使用的是 symfony,我想知道你为什么要“生”这个......

标签: php symfony symfony4


【解决方案1】:

我最终使用 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'

【讨论】:

    猜你喜欢
    • 2018-03-28
    • 1970-01-01
    • 1970-01-01
    • 2022-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-23
    相关资源
    最近更新 更多