How to Add CSS File in Mpdf

how to add css file in mpdf

 <?php

$html = $divPrint;

include('mpdf.php'); // including mpdf.php
$mpdf=new mPDF();
$stylesheet = file_get_contents('pdf.css'); // external css
$mpdf->WriteHTML($stylesheet,1);
$mpdf->WriteHTML($html,2);
$mpdf->Output();
exit;

?>

1st assign your html in $html then include mpdf.php file.

Including CSS file to mpdf

OP found out the solution from the comments, so I'll add it here just for the sake of closure:

It seems mPDF doesn't support CSS in style tags (see here: https://mpdf.github.io/css-stylesheets/introduction.html). In this case, you could replace this:

$cssFile = __DIR__.DIRECTORY_SEPARATOR.'styles.css';

if (file_exists($cssFile)) {
$pdf_output .= '<style type="text/css">'.file_get_contents($cssFile).'</style>';
}

By this:

$cssFile = __DIR__.DIRECTORY_SEPARATOR.'styles.css';

if (file_exists($cssFile)) {
$pdf_output .= '<link rel="stylesheet" href='.$cssFile.'></link>';
}

Or else use the alternative approach that's calling mPDF's WriteHTML() twice, once for the stylesheet and another for the body, as on the example on the documentation above.

mpdf not rendering styles from linked stylesheet

mPDF does not support id on body element. Remove body#the_pdf and body#the_pdf from your css selectors and your styles will be applied.

Other Bootstrap styles (specifically font-family) from your stylesheet are being applied correctly when I add eg. a heading and a paragraph to your example code.

See a page on supported HTML attributes in the mPDF online manual.



Related Topics



Leave a reply



Submit