Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 705
LatentDenis Avatar asked Feb 08 '23 06:02

LatentDenis


2 Answers

I know this question is old, but there is always room for other answers.

You can try to use base64. Here is the code:

Get image content.

$data = file_get_contents('absolute/path/to/background-image.jpg');

Convert it to base64.

$base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);

In CSS use it this way.

body { background-image: url(<?php echo $base64 ?>); }

But remember that background-size property doesn't work properly, at least as far as i tried.

like image 152
Drk_alien Avatar answered Feb 11 '23 23:02

Drk_alien


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>
like image 44
Artistan Avatar answered Feb 12 '23 00:02

Artistan