Search code examples
phpfpdf

How to insert base64 image into fpdf?


I've seen various answer to this, but for whatever reason I cannot seem to get them to work.

First, I'm pulling the file from my database:

try {
    $getQuery = "SELECT * FROM firstForm WHERE id =:id";
    $statement = $db->prepare($getQuery);
    $statement->execute(array(':id' => 2));

    if($row = $statement->fetch()) {
        $fileName = $row['pic'];
    }
}

When I echo $fileName it produces "data:image/png;base64..."

How do I convert $fileName so I can use it in fpdf, like so:

$pdf = new FPDF('P','in','A4'); // orientation (portrait), inches, ??
$pdf->SetMargins(0.5,0.5,0.5);  // l, t, rs

$pdf->AddPage();
$pdf->Cell(4,3,'', 1, 2, 'C'); // w, h, text, border width, ???, align
$pdf->Image($fileName);
$pdf->Output();

Solution

  • Although, as suggested by James, the answer print BASE64 coded image into a FPDF document provides a pretty good solution. In your case you could save the following code as image.php and then add that image (with $_GET['id'] set) into the pdf: $pdf->Image('/image.php?id=2');. Make sure to check whether the image exists in the database before calling image.php.

    <?php
    if ($_SERVER['SERVER_ADDR'] != $_SERVER['REMOTE_ADDR']) { // Only allow requests from server.
        header($_SERVER["SERVER_PROTOCOL"] . "  791 The Internet shut down due to copyright restrictions", true, 791);
        die();
    }
    
    if (empty($_GET['id'])) {
        die('Handle this.');
    }
    
    // get your $db object in here.
    $getQuery = "SELECT * FROM firstForm WHERE id =:id";
    $statement = $db->prepare($getQuery);
    $statement->execute(array(':id' => 2));
    
    if ($row = $statement->fetch()) {
        $data = $row['pic'];
    } else {
        // This shouldn't happening, you should be checking whether firstForm with the id you're calling the image for exists.
    }
    
    $exploded = explode(';', $data);
    $mimetype = substr($exploded[0], 5);
    $data = explode(',', $exploded[1])[1];
    
    header('Content-type: ' . $mimetype);
    echo base64_decode($data);
    

    You pdf creation would look something like this:

    $pdf = new FPDF('P','in','A4'); // orientation (portrait), inches, ??
    $pdf->SetMargins(0.5,0.5,0.5);  // l, t, rs
    
    $pdf->AddPage();
    $pdf->Cell(4,3,'', 1, 2, 'C'); // w, h, text, border width, ???, align
    $pdf->Image('/image.php?id=2');
    $pdf->Output();