Search code examples
phpdompdf

dompdf 0.8.2 generates PHP errors: "Uncaught Error: Class 'Dompdf' not found"


The legacy application I'm working on uses dompdf to generate PDFs from html content. We are working to updating php 5x to php 7x, so we needed to update dompdf from 0.6.1 to 0.8.2.

I first tested 0.8.2 in a standalone file, and it works fine.

In the application, pdf creation occurs within a function, like this (but more complicated IRL):

function createPDF($html,$filename,$paper,$orientation)
{
    require_once("static/dompdf_0.8.2/autoload.inc.php");
    use Dompdf\Dompdf;
    $dompdf = new Dompdf();
    $dompdf->loadHtml($html);
    $dompdf->setPaper($paper, $orientation);
    $dompdf->render();
    $dompdf->stream($filename);
    return true;
}

This generated PHP Parse error: syntax error, unexpected 'use' (T_USE) against the use Dompdf\Dompdf line in the function above.

I tried moving the require and use lines outside of the function (again simplified)

require_once("static/dompdf_0.8.2/autoload.inc.php");
use Dompdf\Dompdf;

function createPDF($html,$filename,$paper,$orientation)
{
    $dompdf = new Dompdf();
    $dompdf->loadHtml($html);
    $dompdf->setPaper($paper, $orientation);
    $dompdf->render();
    $dompdf->stream($filename);
    return true;
}

This now generates PHP Fatal error: Uncaught Error: Class 'Dompdf' not found on the $dompdf = new Dompdf(); line.

Is there a relatively painless way to get dompdf 0.8.2 working within a function?


Solution

  • Your code should work:

    require_once 'static/dompdf_0.8.2/src/autoload.inc.php';
    use Dompdf\Dompdf;
    
    function createPDF($html,$filename,$paper,$orientation)
    {
        $dompdf = new Dompdf();
        $dompdf->loadHtml($html);
        $dompdf->setPaper($paper, $orientation);
        $dompdf->render();
        $dompdf->stream($filename);
        return true;
    }
    

    Make sure the require_once is executed (successfully) to load the autoload.inc.php.