I've some as base64 stored images in a database. Is it possible to print those data directly in a PDF document, using FPDF?
Data sctructure of the image
data:image/png;base64,iVBORw0KGgoAAAANSUhEUg7AAAfQAAACWCAYAAAAonXpvAAAfgUlEQVR4Ae2dC9BuVVnHuSN3QaBENA9h5A2IcJxMj8hUkymoQDfClIkmrQZr1EydMqapnKRMc8JmHLBBHadJJaV0lKQDZCmCQiqQ2KERUFARDhcFDpx /33W tznPe/ 3ttaa9/ a2Z9/32Xvt5nvVbl2evtdfee9dtS27bt4mACJmACJm8ACJtBvArv123xbbwImYAImYAImIAJ26K4HJmACJmACJjAAAnboAyhEZ8EETMAETMAE7NBdB0zABEzABExgAATs0AdQiM6CCZiACZiACdihuw6YgAmYgAmYwAAI2KEPoBCdBRMwARMwAROwQ3cdMAETMAETMIEBELBDH0AhOgsmYAImYAImYIfuOmACJm
I think $pdf->imagepng()
should be the right function in FPDF.
While the comments suggested a TCPDF solution, I did want to state that there is a way to do this entirely with FPDF. The thought process is like this:
data:image/png;base64,
from the URI using explode
base64_decode
file_put_contents
Image
unlink
Always remember to error check. If the image fails to save to the server you obviously do not want to continue execution. Make sure to always strictly check if the functions return false!
Here is my solution. I used a tiny image for a small URI in this example.
const TEMPIMGLOC = 'tempimg.png';
$dataURI = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAPCAMAAADarb8dAAAABlBMVEUAAADtHCTeKUOwAAAAF0lEQVR4AWOgAWBE4zISkMbDZQRyaQkABl4ADHmgWUYAAAAASUVORK5CYII=";
$dataPieces = explode(',',$dataURI);
$encodedImg = $dataPieces[1];
$decodedImg = base64_decode($encodedImg);
// Check if image was properly decoded
if( $decodedImg!==false )
{
// Save image to a temporary location
if( file_put_contents(TEMPIMGLOC,$decodedImg)!==false )
{
// Open new PDF document and print image
$pdf = new FPDF();
$pdf->AddPage();
$pdf->Image(TEMPIMGLOC);
$pdf->Output();
// Delete image from server
unlink(TEMPIMGLOC);
}
}