Reputation: 453
I have an API in Symfony and a front with React. I'm trying to upload documents (jpg, png or pdf) but I only want to store pdf file in my directory. So, when a user send an image, i want to convert it in pdf before uploading.
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) ;
}
}
I've tried with Imagick library but it's give me an error like 'convert : Not a JPEG file'. What's wrong or is it another better library to do it?
Upvotes: 1
Views: 1530
Reputation: 453
I use finally fpdf and fpdi libraries
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);
}
}
My services.yml :
parameters:
tmpDir: '%kernel.project_dir%/public/tmp'
Upvotes: 1