When generating PDFs in Laravel using dompdf, custom fonts sometimes do not render correctly. This can be resolved by configuring dompdf to recognize and use these fonts. In this guide, we’ll walk through the steps to add a custom font to Laravel-dompdf.
Step 1: Download the Custom Font
First, download the custom font you want to use. For this example, we’ll use the Poppins font.
- Visit Google Fonts.
- Search for “Poppins”.
- Download the font by clicking on the download icon.
Step 2: Add the Font to Your Laravel Project
- Create a fonts directory in your public folder:
mkdir public/fonts
- Extract the downloaded font files and move them to the public/fonts directory.
Step 3: Register the Font in Dompdf Configuration
Laravel-dompdf needs to know about the custom font. This can be achieved by setting font directories and font cache in the dompdf configuration.
- Open the
config/dompdf.php
file. If the file doesn’t exist, publish the configuration file using:
php artisan vendor:publish --provider="Barryvdh\DomPDF\ServiceProvider"
- Update the font_dir and font_cache to point to the public/fonts directory. Your
config/dompdf.php
should look like this:
return [ // Other configurations... 'font_dir' => public_path('fonts/'), 'font_cache' => public_path('fonts/'), // More configurations...
];
– OR –
Generate the PDF with Custom Font
Use it in the PDF generation logic to set the custom font as the default font.
In your controller or wherever you’re generating the PDF, add the custom font options:
use Barryvdh\DomPDF\Facade\Pdf; class PdfController extends Controller
{ public function generatePdf() { $data = [ 'param1' => 'value1', // other data ]; $pdf = Pdf::loadView('pdf-view', $data) ->setOption([ 'fontDir' => public_path('/fonts'), 'fontCache' => public_path('/fonts'), 'defaultFont' => 'Poppins' ]); return $pdf->download('document.pdf'); }
}
Step 4: Load the Font in Your View
Next, we need to inform dompdf about the custom font in the view file where the PDF is being generated.
- Open the view file where the PDF content is being generated, e.g.,
resources/views/pdf-view.blade.php
. - Add the following CSS to load the custom font:
<style> @font-face { font-family: 'Poppins'; font-style: normal; font-weight: 400; src: url('{{ public_path('fonts/Poppins-Regular.ttf') }}') format('truetype'); } body { font-family: 'Poppins', sans-serif; }
</style>
By following these steps, you can ensure that your custom fonts are correctly rendered when generating PDFs using Laravel-dompdf. This solution involves downloading the font, placing it in the correct directory, registering it in dompdf, and setting it as the default font in the PDF generation logic.
Discover more from Coursity
Subscribe to get the latest posts sent to your email.