Create PDF from base64 String PHP
I am trying to create a .pdf file with base64 string from an image and I can generate it correctly, but when I try to open the file the program sends a message saying the file is corrupted or something like this ..
I got this code:
define('UPLOAD_DIR', '../image/');
$img = $_POST['image'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$uniqueNumber = uniqid();
$namefile = $uniqueNumber.'.png';
$file = UPLOAD_DIR . $namefile;
$success = file_put_contents($file, $data);
$namefile = $uniqueNumber.'.pdf';
$file = UPLOAD_DIR . $namefile;
$success = file_put_contents($file, $data);
I can open the .png file correctly, so I guess it is not a problem from the decoded base64 string. Thanks everyone!
EDIT:
I try this code and get the same problem.
$data = base64_decode ($img);
//Write data back to pdf file
$pdf = fopen ('test.pdf','w');
fwrite ($pdf,$data);
//close output file
fclose ($pdf);
echo 'Done';
Is it because I am saving the image from .pdf? I think not, because if I do fopen with .pdf, it should be with that format.
EDIT 2:
THE SOLUTION FOUND.
http://www.fpdf.org/en/script/script45.php
I followed these steps and I can get this, thanks everyone!
source to share
Have a look at DOMPDF: https://github.com/dompdf/dompdf
You can definitely use DOMPDF to generate a PDF with an image tag sourced from this Base64 string. and do it in PDF format.
<?php
require_once("dompdf_config.inc.php");
$img = $_POST['image'];
$html =
'<html><body>'.
'<img src="'.$img.
'"></body></html>';
$dompdf = new DOMPDF();
$dompdf->load_html($html);
$dompdf->render();
$dompdf->stream("sample.pdf");
?>
source to share