Skip to content

How to display images in DOM PDF using Php

As you all know DOM PDF is a great library by which you can create PDF’s directly from Php code by using writing minimum lines of code.

Though there are lot of answers in stackoverflow which suggest you to use remote urls most of them wrong.The best solution I found for displaying images is to convert the image into Base64 and display them as base64 when the PDF is generated. The below code will explain about how to do it..

<?php
require_once 'dompdf/autoload.inc.php';
use Dompdf\Dompdf';
use Dompdf\Options';

//Getting image
$image=file_get_contents("image.png");
$imagedata=base64_encode($image);
$imgpath='<img src="data:image/png;base64, '.$dataBase64.'">';

$HTML='<body><div>'.$imgpath.'</div></body>';

//Setting options
$options=new Options();
$options->set('defaultFont', 'Helvetica');
$options->set('dpi','120');
$options->set('enable_html5_parser',true);
$options->set('tempDir','C:\xxx\htdocs\'); //Any directory)

$dompdf=new Dompdf($options);
$dompdf->loadHTML($HTML);
$dompdf->setPaper('A4','landscape');

$dompdf->render();
$dompdf->stream();



?>

In the above code the 2 important steps are

  • Converting the image into Base64 data
  • Then setting up temporary directory

Even if one of them is not followed then you may not see the desired output