Search code examples
phpconvertersfatal-errordompdf

Throwing Fatal Error after using dompdf


Im trying to write a script that convert HTML file to PDF using dompdf.I have a php file named converter.php with the following lines of code:

<?php
use Dompdf\Dompdf;

$dompdf = new Dompdf();
$dompdf->loadHtml('Hello, its my first HTML to PDF Converter');
$dompdf->setPaper('A4', 'landscape');
$dompdf->render();
$dompdf->stream();

After compiling the program it throws 2 exeptions:

First:

Fatal error: Uncaught Error: Class 'Dompdf\Dompdf' not found in C:\xampp\htdocs\PHP-PDFConverter\converter.php on line 4

Second:

Error: Class 'Dompdf\Dompdf' not found in C:\xampp\htdocs\PHP-PDFConverter\converter.php on line 4

Im sure the problem isn't with the path of some directory.

Edit: Here's my Dompdf class:

/**
 * @package dompdf
 * @link    http://dompdf.github.com/
 * @author  Benj Carson <benjcarson@digitaljunkies.ca>
 * @author  Fabien Ménager <fabien.menager@gmail.com>
 * @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
 */
namespace Dompdf;

use DOMDocument;
use DOMNode;
use Dompdf\Adapter\CPDF;
use DOMXPath;
use Dompdf\Frame\Factory;
use Dompdf\Frame\FrameTree;
use HTML5_Tokenizer;
use HTML5_TreeBuilder;
use Dompdf\Image\Cache;
use Dompdf\Renderer\ListBullet;
use Dompdf\Css\Stylesheet;

And the autoload file:

<?php
/**
 * @package dompdf
 * @link    http://dompdf.github.com/
 * @author  Benj Carson <benjcarson@digitaljunkies.ca>
 * @author  Fabien Ménager <fabien.menager@gmail.com>
 * @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
 */

/**
 * Dompdf autoload function
 *
 * If you have an existing autoload function, add a call to this function
 * from your existing __autoload() implementation.
 *
 * @param string $class
 */

require_once __DIR__ . '/lib/html5lib/Parser.php';
require_once __DIR__ . '/lib/php-font-lib/src/FontLib/Autoloader.php';
require_once __DIR__ . '/lib/php-svg-lib/src/autoload.php';

/*
 * New PHP 5.3.0 namespaced autoloader
 */
require_once __DIR__ . '/src/Autoloader.php';

Dompdf\Autoloader::register();

Solution

  • The first exception thrown means "Hey, there is a exception that you haven't yet handled using try ... catch", you can ignore that unless you want to do something with it, but seeing that you are here, the only thing you'd want to do with it is solve it.
    The second exception means that the class is not know to PHP, meaning that it is not included/required anywhere before calling the class. Which in your case probably means that a autoloader does not work as expected or the file is in the wrong place for the autoloader.

    Make sure you are doing the following:

    • including the autoloader file as early as possible
    • including the autoloader of composer(if using composer)
    • have the autoloaders registered (read how to here)
    • have the DomPDF class in a location that gets autoloaded