How to Use DOMPDF Library to Convert Html to Pdf in Php

Creating a PDF is a frequent requirement. I have seen such requests in virtually every product. Having a solid basic approach well in the early stages of a project can save countless development hours later.

I have tried both vanilla JavaScript based solutions for quick PDF generation on the client and this for PDF creation on the server. IMHO, both are equally good (stable). You can refer the one that suits your project requirements.

Download the library from their Github here and copy it in your setup. The code snippets below are mostly taken from here.

Be careful about the path in your declarations. Look for error_log for any path related misconfigurations.

The following declarations go on the top:

//	Download and unzip the folder in the assets directory inside application directory

// include autoloader
require_once $_SERVER['DOCUMENT_ROOT'].'/tgapp/assets/dompdf/autoload.inc.php';

// reference the Dompdf namespace
use Dompdf\Dompdf;

//  The actual code abstracted to a function
generatePDF('Jack');

Now the actual function

//	Define a function
function generatePDF($name) {
    
    // instantiate and use the dompdf class
    $dompdf = new Dompdf();
    
    $data = file_get_contents('assets/img/flower-bg.jpeg');
    
    //	convert the image to base64 string
    $base64 = 'data:image/jpeg;base64,' . base64_encode($data);
    
    //	use the image as page background
    $html =
        '<html>'.
            '<body><div>
	            <img src="'.$base64.'" height="auto" width="100%">'.
	            '<div style="position: absolute; top: 36%; left: 20%; text-align:left; font-family:Arial; font-size:40px; font-weight:bold; text-transform: uppercase; color:#fff; line-height: 10px;" id="body">Hello '.$name.'</div>'.
            '</div></body>'.
        '</html>';
   
    $dompdf->loadHtml($html);
    
    // (Optional) Setup the paper size and orientation
    $dompdf->setPaper('A4', 'landscape');
    
    // Render the HTML as PDF
    $dompdf->render();
    
    //	stream the content to be written to a file
    $output = $dompdf->output();

		//	write to a file in the downloads directory
    file_put_contents('downloads/'.$name.'.pdf', $output);
    
    // Output the generated PDF to Browser
    //  $dompdf->stream();
}

Note: Using files could be a little tricky. You can try the instructions given in Dompdf wiki here.

Also, you can find examples of how to configure options here.

// pass an array of options
$dompdf->getOptions()->set([
    'defaultFont' => 'helvetica',
    'chroot' => '/var/www/myproject/public',
]);

$dompdf->getOptions()->set('defaultFont', 'helvetica');
$dompdf->getOptions()->set('chroot', '/var/www/myproject/public');

// or use the setters directly
$dompdf->getOptions()->setDefaultFont('helvetica');
$dompdf->getOptions()->setChroot('/var/www/myproject/public');

In my case, as the requirement was to use an image as a backgound, I used a workaround as suggested here. It was to convert the image into base64 string and use it instead. Similar snippet is provided by Dompdf wiki:-

'<img src="data:image/svg+xml;base64,' . base64_encode($svg) . '" ...>';

Using the base64 string in the inline CSS did not work for me.

comments powered by Disqus