It seems like the issue you're encountering with the barryvdh/laravel-dompdf package not rendering linked CSS files is a common one. DOMPDF, the underlying library used by this package, has some limitations and specific requirements when it comes to handling external resources like CSS files.
Here are a few steps and tips to ensure your CSS is applied correctly when generating PDFs:
-
Use Absolute URLs for CSS Files: DOMPDF handles external stylesheets better when they are referenced with absolute URLs. You can use Laravel's
asset()helper to generate absolute URLs. -
Embed CSS Directly: As an alternative to linking external stylesheets, consider embedding the CSS directly within the
<style>tags in your HTML. This ensures that all styles are available to DOMPDF without relying on external file fetching. -
Check CSS Compatibility: Ensure that your CSS uses properties and values that are supported by DOMPDF. Some modern CSS features might not be supported.
-
Permissions and Path Issues: Ensure that the paths to your CSS files are correct and that the server has the necessary permissions to access those files.
Here's how you might adjust your code:
Adjusting the Blade Template
Instead of linking to external CSS files, embed the CSS directly within the HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{{ $reportTitle }}</title>
<style>
@import url('{{ public_path('css/app.bundle.css') }}');
@import url('{{ public_path('css/themes/cust-theme-15.css') }}');
@import url('{{ public_path('css/sirius.css') }}');
/* Additional embedded styles */
</style>
@yield('headerStyle')
</head>
<body>
{{-- Content here --}}
</body>
</html>
Controller Method
Ensure that the paths and permissions are correctly set, and consider logging or debugging to confirm that paths resolve as expected.
public function previewPDF(Event $event)
{
$featuredImage = $event->getMedia('Event Images')->first();
$featuredImagePath = $featuredImage->getPath(); // Ensure this path is correct
$pdf = PDF::loadView('events.pdf', compact('event', 'featuredImagePath'));
$pdf->setPaper('A4', 'portrait');
return new Response($pdf->output(), 200, [
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'inline; filename="report.pdf"',
]);
}
By embedding the CSS directly within your HTML document, you can avoid issues related to external file loading and ensure greater compatibility with DOMPDF's rendering engine.