How to Add CSS Files in mPDF
Integrating external stylesheets into PDF generation workflows often trips up developers because they expect the behavior of a standard browser. When using mPDF, you cannot simply rely on <link rel="stylesheet" href="..."> tags or assume that file_get_contents will automatically inject the rules for styling. The engine requires a specific sequence of operations to parse and apply external CSS before rendering the HTML content.
The core issue in your current implementation lies in how mPDF handles the WriteHTML method. In your code, you are loading the stylesheet file directly into the HTML buffer using $mpdf->WriteHTML($stylesheet, 1);. The second argument tells mPDF to treat the content as a stylesheet definition rather than raw HTML tags. While this approach technically loads the CSS, there are critical nuances regarding how mPDF processes external styles versus inline or embedded styles that often lead to missing styles in the final output.
To ensure your pdf.css is applied correctly, you must understand that mPDF has specific limitations on which selectors and properties it supports. Unlike a web browser, mPDF does not execute JavaScript or fully interpret every CSS3 feature. If your pdf.css contains unsupported pseudo-classes (like :hover) or complex layout modules, they will be ignored silently. The most reliable method to ensure styles are picked up is to embed the stylesheet content directly into the HTML string or use the @import rule within your main HTML file if you prefer keeping them separate.
However, sticking to your current file-loading approach requires a slight adjustment in execution order and context. When you call $mpdf->WriteHTML($stylesheet, 1), you are injecting the CSS rules into the document's internal style block. This works, but it assumes that the HTML content loaded subsequently ($divPrint) does not override these styles with conflicting inline definitions or scoped styles that mPDF might mishandle.
A more robust pattern often involves creating a dedicated PHP function to handle the PDF generation. This isolates the logic and ensures the stylesheet is available regardless of where the HTML comes from (AJAX, database, or static file). Here is an adjusted structure that explicitly sets the font paths before attempting to write any content:
function generatePDF($htmlContent, $cssPath) {
$mpdf = new \mpdf\Mpdf();
// Optional: Set font paths if using custom fonts defined in CSS
// $mpdf->SetFontPath('path/to/fonts');
// Load the external stylesheet
if (file_exists($cssPath)) {
$stylesheet = file_get_contents($cssPath);
// Write the stylesheet to the document
$mpdf->WriteHTML($stylesheet, 1);
} else {
throw new Exception("Stylesheet not found at: " . $cssPath);
}
// Write the actual HTML content
// Parameter '2' indicates this is raw HTML to be rendered after styles are loaded
$mpdf->WriteHTML($htmlContent, 2);
return $mpdf->Output('document.pdf', 'S');
}
Using file_exists checks prevents runtime errors if the CSS path changes or is missing. It is also crucial to note that mPDF expects the HTML content to be a complete document structure if you are not generating from an existing DOM node. If $divPrint contains only a fragment (like a <div> without a parent body), the rendering engine might struggle with positioning relative to page margins unless the CSS explicitly accounts for absolute positioning within the generated PDF context.
Another common pitfall involves the font configuration. mPDF requires that all fonts used in your CSS or HTML are registered in the fontconfig directory before generation. If your stylesheet references a font like 'Arial', it must be installed on the server where the script runs, otherwise, mPDF will revert to a fallback font like Helvetica, breaking your layout.
If you are working within a Laravel application, consider leveraging service providers or middleware to register these fonts globally, ensuring consistent behavior across all PDF generation requests. For complex styling needs, embedding the CSS directly via @import url('path/to/pdf.css'); inside a <style> block in your HTML string is often safer than relying on external file inclusion, as it guarantees the content travels with the HTML fragment regardless of server-side caching or path resolution issues.