Alexxosipov
Alexxosipov

Reputation: 1234

DOMPDF with laravel - cannot load images in html file

I'm trying to generate pdf file with laravel and dompdf lib. Here is my code from controller:

public function create(Request $request) {
    $pdf = new Dompdf();
    $html = Storage::disk('local')->get('public/pdf/template.html');
    $pdf->loadHtml($html, 'UTF-8');
    $pdf->setPaper('A4', 'portrait');
    $pdf->render();
    $filename = "Hi!";
    return $pdf->stream($filename, ["Attachment" => false]);
}

And in template.html I got some html, somewhere there I got images like this:

<img src="img/logo.png" alt="BTS">

But dompdf cant write this image: Image not found or type unknown. My file system is:

.pdf ...img ......here is images ...template.html ...*some_fonts_files*

But at the same time, fonts are loading fine. What should I do to render images in template.html?

Upvotes: 3

Views: 19263

Answers (5)

Caelchro
Caelchro

Reputation: 11

I tried all tips!! The only one solution that works for me is:

header {
            background-image: url("https://example.org/logo.jpg");
        }

and

$pdf->setOptions(['isRemoteEnabled' => true]);
$pdf->getDomPDF()->setProtocol($_SERVER['DOCUMENT_ROOT'])

Upvotes: 0

Ivan Sushchyk
Ivan Sushchyk

Reputation: 1

There seems to be a need to set the protocol and add an additional option:

    $pdf->setOptions(['isRemoteEnabled' => true]);
    $pdf->getDomPDF()->setProtocol($_SERVER['DOCUMENT_ROOT'])

Or:

$pdf->setProtocol($_SERVER['DOCUMENT_ROOT']);

After this src="/storage/myimage.png" will work.

Upvotes: 0

Jesus Garcia
Jesus Garcia

Reputation: 1

You can just print the image path as the src attribute of the <img> tag.

Suppose you have the path to the location of your image in a variable: $img = asset($imgen);

Yust echo it out like this: <img src="@php echo $img @endphp">

Upvotes: 0

Angelwise
Angelwise

Reputation: 111

Me too i struggled for the same error for 3 days. Also when i tried tricks mentioned above, none of them worked too. But when i changed the image file to .jpg file(extension) everything worked well.

<img src="{{ public_path('img/logo.jpg') }}" >
  • Laravel version: 5.8.38
  • PHP version: 7.3
  • barryvdh/laravel-dompdf version: 0.8.6

Upvotes: 3

Simon R
Simon R

Reputation: 3772

I believe that for dompdf you need to pass a properly accessable url rather than relative paths.

Try <img src="{{ asset('img/logo.png')}}" alt="BTS">

Alternatively if asset doesn't work please try <img src="{{ public_path('img/logo.png')}}" alt="BTS">

Also please note that asset uses the public directory as the base_url to calculate the 'asset' from.

Upvotes: 6

Related Questions