I am new to PHP and trying to build a little project for my assignment.
I am trying to convert some HTML to a PDF using PHP (DOMPDF package). The HTML does contain some tags to output some images that are locally stored within the this project's folder.
I am currently getting "Image not found or type unknown" error, which I have seen is quite common when trying to do this.
I have done some research and experimented with quite a few different things, however I do not seem to be getting anywhere unfortunately.
Does anyone know what I might be doing wrong?
Just a little snippet from my project:
index.php
<?php
require_once 'packages/dompdf/autoload.inc.php';
use Dompdf\Dompdf;
$dompdf = new Dompdf();
$dompdf->loadHtml("<img src='photo.jpeg'>");
$dompdf->setPaper('A4', 'portrait');
$dompdf->render();
$dompdf->stream("test-pdf", array("Attachment" => 0));
?>
The image is stored in the same directory as the index.php file. I am using XAMPP as a development environment.
Hope this is described correctly. Thanks everyone and appreciate the support!
As @KIKOSoftware mentioned in the comments, the src
attribute of an img
tag can either contain an absolute URI or base64-encoded image data. You can use the following helper function to generate the latter on the fly.
function ImageToDataUrl(String $filename) : String {
if(!file_exists($filename))
throw new Exception('File not found.');
$mime = mime_content_type($filename);
if($mime === false)
throw new Exception('Illegal MIME type.');
$raw_data = file_get_contents($filename);
if(empty($raw_data))
throw new Exception('File not readable or empty.');
return "data:{$mime};base64," . base64_encode($raw_data);
}
Which will then be used like this:
$dompdf->loadHtml("<img src='" . ImageToDataUrl('photo.jpeg') . "'>");