Tcpdf and Insert an Image Base64 Encoded

TCPDF and insert an image base64 encoded

You cannot use base64 stream in src rather first save the stream to a file then use it

$img_base64_encoded = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAA0gA...';
$imageContent = file_get_contents($img_base64_encoded);
$path = tempnam(sys_get_temp_dir(), 'prefix');

file_put_contents ($path, $imageContent);

$img = '<img src="' . $path . '">';
$pdf->writeHTML($img, true, false, true, false, '');

Does TCPDF have limits on base64 images?

This was a folder issue with the K_PATH_CACHE variable.

With more experimentation, I found that any PNG file would not be added to the PDF which had me looking into the tcpdf.php file. This led to the error log and ultimately to the constant K_PATH_CACHE.

The imgpng() function uses K_PATH_CACHE to define the location for /tmp in the PHP installation (Bitnami through a AWS Lightsail), but the location was defined incorrectly.

The default value for K_PATH_CACHE was set to /opt/bitnami/php/tmp but that folder was empty. The actual tmp folder is found at /tmp.

To resolve this, I redefined the location for K_PATH_CACHE to be the actual /tmp directory in a config file loaded before everything else:

define('K_PATH_CACHE', '/tmp/');

PNGs now load, both from a base64 string and when loaded as a file.

I hope this saves someone a few hours of searching!

Remove 'E' output headers from base64 string in TCPDF

TCPDF docs are huge but unusable – it's easier to read the source code directly. It has those extra headers because you're asking for them by using the E output mode, which is intended for generating email messages.

For sending the PDF data as a PHPMailer attachment, you want the straight binary PDF data as a string, as provided by the S output mode, which you can pass straight into addStringAttachment(), and PHPMailer will handle all the encoding for you. All you have to do is this:

$mail->addStringAttachment($pdf->Output('file.pdf', 'S'), 'file.pdf');

To convert the PDF binary into base64, for example to us it in a JSON string, simply pass it through base64_encode:

$base64String = base64_encode($pdf->Output('file.pdf', 'S'));


Related Topics



Leave a reply



Submit