Search code examples
csspdfbackground-imagedompdf

How to get background image showing on DOMPDF generator


So far, I've been trying to work with this code:

<style>
    body {
        background-image: url(http://example.com/wp-content/uploads/2016/04/myImage.jpg);
        background-size: 100%;
        background-repeat: no-repeat;
    }
</style>

Yet this doesn't render an image on the generated PDF.

A plain image tag in the body that's formatted this way, works and shows up fine:

<img src="/home/example/public_html/wp-content/uploads/2016/04/myImage.jpg">

Does anyone know why this is? What can I do to get the background image to actually show on the generated pdf?

UPDATE:

I've now tried to base64_encode() all possibilities of links.. meaning I've passed,

/home/example/public_html/wp-content/uploads/2016/04/myImage.jpg

http://example.com/wp-content/uploads/2016/04/myImage.jpg

/wp-content/uploads/2016/04/myImage.jpg

These ^ combinations through the base64_encode() function, and none of them have worked to display a background image yet.


Solution

  • A more flexible solution

    This way you do not have to know the relativeness of the directory generating the PDF.

    ..include setup.dompdf.php in your generator script

    <?php 
    
        $webRoot = '/var/www/html/';
    
        $dompdf = new Dompdf($this->dompdf_options);
        $dompdf->setBasePath($webRoot);
    
    ?>
    

    Then you can reference any file in css relative to the web root from any script you are generating the pdf.

    <style>
        body {
            background-image: url(wp-content/uploads/2016/04/myImage.jpg);
        }
    </style>