I've been working with TCPDF for a few months now; off and on. It's worked fairly well for most of my HTML templates, but I've always had problems placing images into the PDF's. The images are usually placed into the body, not the header. My placement is either a fixed position from the top-left corner or it is relative to the bottom of the document. In either case, I've had issues. When the text changes in the HTML, I have to reposition the image. Multiple column tables can make things even more difficult. Note: "class pdf extends TCPDF".
$this->pdf->AddPage();
$this->pdf->writeHTML($pdf_html);
$cur_page = $this->pdf->getPage();
$x_pos = $this->pdf->GetX();
$y_pos = $this->pdf->GetY();
// Place image relative to end of HTML
$this->pdf->SetXY($x_pos, $y_pos - 54);
$this->pdf->Image('myimage.png');
Does anyone know a fool-proof way of placing an Image into a PDF that is generated from HTML. I thought about splitting the HTML into two parts, but I'm not sure if it would work well either.
I am using html img tag and its working well.
$toolcopy = ' my content <br>';
$toolcopy .= '<img src="/images/logo.jpg" width="50" height="50">';
$toolcopy .= '<br> other content';
$pdf->writeHTML($toolcopy, true, 0, true, 0);
Sorry, I know you've got an accepted answer. However, it does not appear to actually answer your question, with regards to an image that is NOT at the web level.
Have you considered using file_get_contents(); and the simple rendering the base_64 string. This way you can use an image from any level, without worrying about it being publicly accessible.
$imageLocation = '/var/www/html/image.png';
$ext = end(explode(".", $imageLocation);
$image = base64_encode(file_get_contents($imageLocation));
$pdf->writeHTML("<img src='data:image/$ext;base64,$image'>");
Or, without relying on the HTML parser. Which from experience slows rendering of the resulting PDF by far to much you could use:
$image = file_get_contents('/var/www/html/image.png');
$pdf->Image('@'.$image);
For the sake of completeness, and in response to Roland. You could certainly use SplFileObject.
$image = new SplFileObject('/var/www/html/image.png', 'r');
$imageContents = $image->fread($image->getSize());
$imageExtension = $image->getExtension();
$pdf->writeHTML("<img src='data:image/$imageExtension;base64,$imageContents'>");
Answer is here
Please make sure the HTML attributes have double quotes.
$html = "<img src='...' />"; // This will not work
$html = '<img src="..." />'; // This will work
$pdf->writeHTML($html, true, false, true, false, '');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With