使用Laravel dompdf时日文字符无法正常显示的解决方法求助
I’ve run into this exact issue before—dompdf doesn’t include support for non-Latin scripts like Japanese out of the box, so we need to add a compatible font and configure things correctly. Here’s how to fix it:
Step 1: Add a Japanese-Supporting Font
First, you need a font that includes Japanese characters. Noto Sans JP is a free, reliable choice (it covers all Japanese kanji, hiragana, and katakana).
- Download the font files (pick weights like Regular) from Google Fonts.
- Create a
fontsdirectory in your Laravelpublicfolder, then place the font files (e.g.,NotoSansJP-Regular.otf) inside it.
Step 2: Update Your Blade View to Use the Font
Add a <style> section to your invoice.blade.php to define the font and apply it to your content:
<!DOCTYPE html> <html lang="ja"> <head> <title>Invoice</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <style> @font-face { font-family: 'Noto Sans JP'; font-weight: normal; src: url('{{ public_path('fonts/NotoSansJP-Regular.otf') }}') format('opentype'); } body { font-family: 'Noto Sans JP', sans-serif; margin: 0; padding: 20px; } </style> </head> <body> <div>日本語のテキスト</div> </body> </html>
Notes:
- The
lang="ja"attribute on the<html>tag helps dompdf recognize the language context. - Using
public_path()ensures dompdf can find the font file (it uses the absolute filesystem path instead of a URL).
Step 3: Verify Dompdf Configuration
Double-check your dompdf settings to ensure fonts are embedded correctly:
- Publish the dompdf config file if you haven’t already:
php artisan vendor:publish --provider="Barryvdh\DomPDF\ServiceProvider" - Open
config/dompdf.phpand confirm these settings are enabled:
These ensure the font is embedded in the PDF and that dompdf parses your HTML correctly.'embed_fonts' => true, 'isHtml5ParserEnabled' => true,
Step 4: Test the PDF Generation
Update your controller code (the default should work if you followed the above steps, but adding these options can help):
$pdf = PDF::loadView('invoice') ->setOptions([ 'isHtml5ParserEnabled' => true, 'isRemoteEnabled' => true // Only needed if loading external fonts via URL ]); return $pdf->download('invoice.pdf');
That should do it! The Japanese text should now render correctly in your PDF. If you still see garbled characters, double-check that the font file path is correct and that the font file isn’t corrupted.
内容的提问来源于stack exchange,提问作者Vinod VT

