DOMPDF with laravel - cannot load images in html file

12,181

Solution 1

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.

Solution 2

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
Share:
12,181
Alexxosipov
Author by

Alexxosipov

Fullstack (php+js) разработчик из солнечного (не очень) Санкт-Петербурга. Telegram: alexxosipov

Updated on June 05, 2022

Comments

  • Alexxosipov
    Alexxosipov almost 2 years

    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?

  • Simon R
    Simon R about 6 years
    If you dd(asset('img/logo.png')); what does that show?
  • Alexxosipov
    Alexxosipov about 6 years
    This URL works fine from browser, but from dompdf it does not work
  • Simon R
    Simon R about 6 years
    perhaps instead try <img src="{{ public_path('img/logo.png')}}" alt="BTS">
  • Simon R
    Simon R about 6 years
    Does it work if you use an external image - something like cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/…
  • Alexxosipov
    Alexxosipov about 6 years
    oh, no, it works fine, my bad! Thanks :) Update your answer, then I will mark it as correct :)
  • AbingPj
    AbingPj almost 4 years
    thanks its work,.. last version (0.8.5) i uses asset() function its work but in version 0.8.6 it not work. @Angelwise why the asset() function is not work anymore?
  • Toby Okeke
    Toby Okeke over 3 years
    In my case, it wasn't working because I tried to access a remote URL and in the config, it defaults to not allow remote accessing anything.