skip to Main Content

I am using dompdf version 1.0.2 but I never got it to apply any stylesheet to a pdf output. But I get no warnings or errors. The pdf has just no css applied.
This is code that I use (I use it in wordpress but the wordpress code is a bit different structured than the code here because of callback functions):

use DompdfDompdf;
use DompdfOptions;
$dirDompdf = ABSPATH . 'wp-content/plugins/dompdf';
require_once $dirDompdf . '/autoload.inc.php';
$invoiceHtmlFile = $pluginDir . '/invoice.html';
$invoiceHtmlDom = new DOMDocument();
$invoiceHtmlDom->loadHTMLFile($invoiceHtmlFile);
$stringHtml = $invoiceHtmlDom->saveHTML();
$dompdf = new Dompdf();
$dompdf->set_base_path(__DIR__ . '/style.css');
$dompdf->load_html($stringHtml);
$dompdf->render();
file_put_contents(__DIR__ . '/testing.pdf', $dompdf->output());

the html file

 <html>
    <head>
        <link rel="stylesheet" type="text/css" media="screen" href="style.css" />
    </head>
    <body>
    <h1>Invoice</h1>
    </body>
</html> 

The css file

h1 {
    text-align: center;
    font-size: 18pt;
}

Even this simple css doesn’t work. I tried also different set_base_paths (all files are in the same folder).

Are there any workarounds maybe? I read something that you can save the html as a .php and then include the css in a different way?

I tried getting some debug informations what dompdf is doing when its generating the pdf to see what is the problem (e.g. maybe some error concerning the filepath) but didn’t get any useful information.

Are there maybe any additional libraries or dependencies that are needed?

Unfortunately I cannot use composer to install another pdf library. So I guess I am stuck with dompdf.

2

Answers


  1. Chosen as BEST ANSWER

    The fixing solution I got from the dompdf developers:

    Base path in Dompdf defines the path portion of URLs, not the path to a specific file, so DIR would be what you want to provide. You haven't allowed Dompdf to access the base path by specifying it in the chroot setting. There are a few ways to do that, but this is the easiest: $dompdf = new Dompdf(['chroot' => DIR]);


  2. Link tag that you provided will result in search for a that file in generated PDF, so when you will have style.css in the same folder it will be applied.

    When you want to apply CSS in generated document, you can use <style> tag in your source html.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search