laravel-dompdf: Image not found or type unknown

After updating the version to 0.7.0. The images (.png) are broken (“Image not found or type unknown”).

imgnotfoumd

About this issue

  • Original URL
  • State: closed
  • Created 7 years ago
  • Reactions: 5
  • Comments: 78

Commits related to this issue

Most upvoted comments

You need to add ‘isRemoteEnabled’ => true

Sample return PDF::setOptions(['isHtml5ParserEnabled' => true, 'isRemoteEnabled' => true])->loadView('reports.invoiceSell')->stream();

I solved it after changed to this: <img src="{{ base_path() }}/location/to/image/image.png" />

Enabling remote by setting options helped me fix this. … $html = ‘’; $options = new Options(); $options->setIsRemoteEnabled(true); $dompdf = new Dompdf($options); $dompdf->loadHtml($html); $dompdf->output(); …

What solved it for me was using public_path('path/to/image.png').

this worked for me: <img src="http://www.domain.com/path/to/image/image.png" />

If you still have problem with it. It might be due to something with ssl certificate, I just install one and the images stop showing. To fix it: $contxt = stream_context_create([ 'ssl' => [ 'verify_peer' => FALSE, 'verify_peer_name' => FALSE, 'allow_self_signed'=> TRUE ] ]); $pdf = PDF::setOptions(['isHtml5ParserEnabled' => true, 'isRemoteEnabled' => true]); $pdf->getDomPDF()->setHttpContext($contxt);

@aodzylp It doesn’t help, form me 😞

Solution: Convert the image to base64

<img src="“data:image/png;base64, iVBORw0…” />

@noriega9807 is right. I used <img src="{{ url('/images/image.png') }}"> and it worked fine.

This work for me.

<img src="data:image/png;base64,{{ base64_encode(file_get_contents(public_path('img/example.png'))) }}">

Reference link: https://github.com/barryvdh/laravel-dompdf/issues/761

Seems that it does not work in the local domain. it worked fine in the public domain.

I used @josesotomayor suggest. I created a custom class with the method that gets the base64.

`<?php namespace App\Custom;

class Archivos { public static function imagenABase64($ruta_relativa_al_public) { $path = $ruta_relativa_al_public; $type = pathinfo($path, PATHINFO_EXTENSION); $data = \File::get($path);

	$base64 = "";
	if ($type == "svg") {
		$base64 = "data:image/svg+xml;base64,".base64_encode($data);
	} else {
		$base64 = "data:image/". $type .";base64,".base64_encode($data);
	}
	return $base64;
}

}`

Then in the view i did this.

@php use App\Custom\Archivos; @endphp <img src="{{Archivos::imagenABase64('assets/img/logo_empresa_contrato.jpg')}}" width="200px" >

Out of the blue I got this error as well. public_path('path/to/image.png') works before that I used asset('path/to/image.png')

Base 64 conversion is not a good solution for when images are dynamic. In that case you’d have to store them encoded somewhere or encode on the fly… 😞

After Internet shutdown it happened. It worked for me:

 //Obtener compra
        $purchase = Purchase::findOrFail($id);
        //crear objeto pdf para mostrar número de página. Se habilito php para dompdf. "enable_php" => true en config/dompdf.php
        $pdf = app('dompdf.wrapper');
      
        $contxt = stream_context_create([
            'ssl' => [
                'verify_peer' => FALSE,
                'verify_peer_name' => FALSE,
                'allow_self_signed' => TRUE,
            ]
        ]);

        $pdf = \PDF::setOptions(['isHTML5ParserEnabled' => true, 'isRemoteEnabled' => true]);


        $pdf->getDomPDF()->setHttpContext($contxt);

        //Cargar vista/tabla html y enviar varibles con la data
        $pdf->loadView('purchase.pdfReportsViews.invoice', compact('purchase', 'pdf'));
        //Establecer orientación horizontal al pdf
        $pdf->setPaper('A4', 'landscape');

        //descargar la vista en formato pdf 
        $fecha = date('Y-m-d');
        return $pdf->download("MyPdf.pdf");

‘isRemoteEnabled’ => true

Worked for me…thanks aodzylp

run it on htdocs. don’t run using composer php artisan serve and give currect path url(“/public/foldername/image.png”).

I think it doesn’t work when you customize options in any way.

laravel-dompdf defines a set of default options in config/dompdf.php. Whenever you customize these options either through setOptions method or a custom dompdf.php config file, all the defaults are ignored. Most likely some of the defaults are responsible for proper handling of images.

If this is true, then the issue can be solved by changing the behavior of the library to append-merge new options to the defaults.

Just Replace ( dompdf\src\Image\Cache.php ) From dompdf 0.8.5 To All New Version Dompdf !

dompdf 0.8.5 : https://github.com/dompdf/dompdf/releases/tag/v0.8.5

you can see here : https://youtu.be/bM3y5TY-7_k

Hello guys. for me this code works:

IN CONTROLLER:

public function report2()
    {
        $html = view('your_view');
        $options = new Options();
        $options->set('isRemoteEnabled', true);
        $options->set('chroot', realpath(base_path()));
        $options->set('enable_font_subsetting', false);
        $options->set('pdf_backend', 'CPDF');
        $options->set('default_media_type', 'screen');
        $dompdf = new Dompdf($options);
        $dompdf->loadHtml($html);
        $dompdf->render();
        $this->setEncryption($dompdf);
        $dompdf->stream('name_file');
    }

    public function setEncryption($dompdf)
    {
        $dompdf->get_canvas()->get_cpdf()->setEncryption('userpass', 'ownerpass', array('print'));
    }

IN VIEW TEMPLATE: ... <img src="{{ public_path('images/logo.png') }}"> ...

I had the same issue and applied the solutions above. Still no luck until I figured out that the problem might be due to the use of htaccess. My site is protected by user password auth, which might have prohibited dompdf to access the image files. The base64 encoding might be a workaround for that, but increases workload.

Finally I could solve the issue by adding the line: Require local to my .htaccess file and now it works like a charm.

My .htacces file looks like this:

AuthType      Basic
AuthName      "Alpha-Access"
AuthUserFile  [...]
Require user demo, admin
Require local
Require valid-user

Solution: Convert to base 64 the image:

Example:

<‘img’ src=“data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAAAUA AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO 9TXL0Y4OHwAAAABJRU5ErkJggg==” alt=“Example” />

You have to ask yourself, is the PDF package (that runs on the backend) able to access the image on the URL when calling from the backend. (I know it sounds stupid obvious).

I was running this from inside a docker container. The image I was trying to fetch was using the URL specified in the APP_URL configuration, that worked from the outside world, as that domain was mapped in my /etc/hosts file on my development machine.

The hostname was not mapped inside the container though.

Temporarily hardcoding the domain in the image URL to “localhost” confirmed, that it indeed was the case.

In my case updating the /etc/hosts inside the docker container solved it.

Are you using custom port numbers for your docker containers, you have another problem.

I have set the options like

    'tempDir' => public_path(),
    'chroot'  => public_path('/path/where/images/are'),
    ]);

and have acess the image like

<img src="{{ public_path('/path/where/images/are/'.$foo->field) }}">

And it worked for me.

If your environment is using dompdf/dompdf version 0.8.6, this version is strict checking local path more than previous version.

This version checks “open_basedir” in php.ini via realpath method. So, you need to set “chroot” option.

For example,

document root is “/var/www/html”

php.ini

open_basedir = /var/www/:/var/lib/php/session/:/var/lib/php/wsdlcache/:/tmp/

example.blade.php

<img src="{{ public_path('images/example.png') }}">

caller as PdfController

use Barryvdh\DomPDF\Facade as PDF;

class PdfController
    public function pdf()
    {
        return PDF::loadView('example')
                  ->setPaper('a4')
                  ->setOptions([
                      'tempDir' => public_path(),
                      'chroot'  => '/var/www',
                  ]);
    }

If public_path() is “/var/www/html”, you can also write the following

use Barryvdh\DomPDF\Facade as PDF;

class PdfController
    public function pdf()
    {
        return PDF::loadView('example')
                  ->setPaper('a4')
                  ->setOptions([
                      'tempDir' => public_path(),
                      'chroot'  => public_path(),
                  ]);
    }

Just did a clean installation on my laravel project… Have tried all the solutions above and nothing worked so far 😦

Solved it by setting the options PDF::setOptions(['isHtml5ParserEnabled' => true, 'isRemoteEnabled' => true])->loadView('models.receipt', ['receipt' => $receipt] )->setPaper('a5', 'portrait');

It can be done though base_path() also:

{{ base_path() . '/storage/app/public/images/logo.png' }}

@ACvijic Thanks, it’s very simple way…

`I’ve been having this problem for 3 days now, cant show image on pdf(used dompdf),i just wanna fetch the image locally using XAMPP on MAC, the image (goku.jpg) is located inside htdocs/images folder, already set the options, i guess the problem is with the path on src, tried everypath but still doesnt show, tried everything online but nothing seems to work.please help

2018-10-04 11 00 15

`<?php

require(“config.inc.php”); // Include autoloader require_once ‘dompdf/autoload.inc.php’; // $_dompdf_show_warnings = true; // $_dompdf_warnings = [];

use Dompdf\Dompdf; use Dompdf\Options; //if posted data is not empty $options = new Options(); $options->set(‘defaultFont’, ‘Courier’); $options->set(‘isRemoteEnabled’, TRUE); $options->set(‘debugKeepTemp’, TRUE); $options->set(‘isHtml5ParserEnabled’, TRUE); $options->set(‘chroot’, ‘/’); $options->setIsRemoteEnabled(true);

$dompdf = new Dompdf($options); $dompdf->set_option(‘isRemoteEnabled’, TRUE);

$auth = base64_encode(“username:password”);

$context = stream_context_create(array( ‘ssl’ => array( ‘verify_peer’ => FALSE, ‘verify_peer_name’ => FALSE, ‘allow_self_signed’=> TRUE ), ‘http’ => array( ‘header’ => “Authorization: Basic $auth” ) ));

$dompdf->setHttpContext($context);

$agent = “Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)”; ini_set(‘user_agent’, $agent);

if (isset($_GET[‘firstName’])){

$fileName = “https://i.ytimg.com/vi/1z3MA54hRW4/maxresdefault.jpg”;

$root ='file:///kabushikikaishahaimessodo'. $_SERVER["DOCUMENT_ROOT"];
//$root = realpath(__DIR__);
$tempDir = $root.'/images/'; 

$fileName = ‘goku.jpg’; $pngAbsoluteFilePath = $tempDir.$fileName;

$output = "

";

$fnme = $_GET[‘firstName’];

$query = " SELECT primarykey, firstName, lastName, address, contactNumber FROM booking WHERE firstName = :firstName ORDER BY primarykey DESC LIMIT 1 ";

$query_params = array( ‘:firstName’ => $_GET[‘firstName’] );

//execute query try { $stmt = $db->prepare($query); $result = $stmt->execute($query_params); } catch (PDOException $ex) { $response[“success”] = 0; $response[“message”] = “Database Error!”; die(json_encode($response)); }

// Finally, we can retrieve all of the found rows into an array using fetchAll $rows = $stmt->fetchAll();

if ($rows) { $response[“success”] = 1; $response[“message”] = “User exist!”; $response[“users”] = array();

foreach ($rows as $row) {
    $users             = array();
    $output .='<tr>
                     <th>'.$row['firstName'].' '.$row['lastName'].'  </th>
                     <th>'.$row['address'].'</th>
                     <th>'.$row['contactNumber'].'</th>
                     <th>'.$row['primarykey'].'</th>
                </tr>';

}
 $output .='</table><br/><br/>';

$output .= “<center></center>”;

$dompdf->loadHtml($output); $dompdf->setPaper(‘A4’,‘portrait’); $dompdf->render(); $dompdf->stream(“spl”,array(“Attachment” => 0));

} else { $response[“success”] = 0; $response[“message”] = “No Users!”; die(json_encode($response)); }

}

?>`

Name Address Contact number Primary Key