Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add CSS to DomPDF

I've got this code to export some data into a pdf. And I would like to add css from an external css file (which is not mentionned in the html used)

/*********************************** Export PDF ****************************************************/
if($request->query->get('exportPDF')!= null){
    // Configure Dompdf according to your needs
    $pdfOptions = new Options();
    $pdfOptions->set('defaultFont', 'Arial');
    // Instantiate Dompdf with our options
    $dompdf = new Dompdf($pdfOptions);
    // Retrieve the HTML generated in our twig file
    $html = $this->renderView('dashboard/user_table.html.twig', [
        'users' => $users
    ]);
    // Load HTML to Dompdf
    $dompdf->loadHtml($html);
    // (Optional) Setup the paper size and orientation 'portrait' or 'portrait'
    $dompdf->setPaper('A3', 'landscape');
    // Render the HTML as PDF
    $dompdf->render();
    // Output the generated PDF to Browser (force download)
    $dompdf->stream("exportUsers.pdf", [
        "Attachment" => true
    ]);
}

The user_table.html is only a file with a <table>

who has some class from a css file loaded in an other template. That means for DomPDF the file who contains the css is unkown and, as a result I have a table with no css in my pdf. I've tried to add the stylesheet in my html directly but the import isn't working like that neither. But I don't want to add it in the html anyway, the css is loaded is a more hight level template.

How to add external files (like bootstrap etc etc) from this structure ? I do not know if this is even possible. Thanks for the help ;)

like image 959
Minirock Avatar asked Oct 31 '25 14:10

Minirock


2 Answers

the css file must be referenced in the HTML you give to DomPDF.

If you don't want to change your twig template, you can use a workaround like this :

$dompdf = new Dompdf();
$html = $this->renderView('dashboard/user_table.html.twig', [
    'users' => $users
]);
$html .= '<link type="text/css" href="/absolute/path/to/pdf.css" rel="stylesheet" />';
$dompdf->loadHtml($html);

Note that adding a link tag to the body is not valid according to HTML specifications. With the current Dompdf version, it works but it may not work in future versions.

like image 75
ᴄʀᴏᴢᴇᴛ Avatar answered Nov 03 '25 07:11

ᴄʀᴏᴢᴇᴛ


You can always use solutions like this Including a non-twig file from twig read external file contents right into templates attribute, so css will be rendered inline and will be compatible with mpdf.

like image 36
Vytenis Ščiukas Avatar answered Nov 03 '25 06:11

Vytenis Ščiukas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!