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
How Does Codeigniter Receive the Ajax Post Data in Controller
Alternative to MySQLi_Fetch_All Needed
Sort Array by Date in Descending Order by Date in PHP
Filter_Sanitize VS Filter Validate, Whats the Difference - and Which to Use
Hightest Value of an Associative Array
Differences Between a While Loop and a for Loop in PHP
How to Get Include Contents as a String
PHP MySQL Character Set: Storing HTML of International Content
Why Is My Database Backup Script Not Working in PHP
Php: What Is the Purpose of Session_Name
Laravel 5 - Session Doesn't Work
File_Get_Contents Is Not Working for Some Url
Set Cart Item Price from a Hidden Input Field Custom Price in Woocommerce 3