dompdf in Laravel: Small file size with Japanese fonts

Marc C
2 min readNov 15, 2024

--

I want to convert this html with Japanese characters to a pdf:

<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<style>
/* Load Fonts */
@font-face {
font-family: 'Noto Sans JP';
font-style: normal;
font-weight: 400;
src: url('{{ public_path('fonts/NotoSansJP-Regular.ttf') }}') format('truetype');
}
@font-face {
font-family: 'Noto Sans JP';
font-style: normal;
font-weight: 700;
src: url('{{ public_path('fonts/NotoSansJP-Bold.ttf') }}') format('truetype');
}

body {
font-family: 'Noto Sans JP', sans-serif;
font-size: 12px;
line-height: 1;
padding: 10px;
box-sizing: border-box;
}

.content {
width: 100%;
max-width: 595px; /* A4 width in points */
margin: auto;
padding-bottom: 80px; /* Space for footer content */
}

.title {
font-size: 16px;
font-style: bold;
}
</style>
</head>
<body>
<div class="content">
<div class="title">こんにちは</div>
<p>Look at this kanji: 猫</p>
<p>My cat's name is {{ $cat_name }}.</p>
</div>
</body>

Note the css and everything needs to be inside this example.blade.pdf. I’m using Laravel here. Inline style doesn’t work here.

The controller might look like this:

    use Barryvdh\DomPDF\Facade\Pdf;

public function downloadCatCertificate(Request $request)
{
$cat_name = 'Storven';

$pdf = Pdf::loadView('cat_certificate', compact('cat_name'));

return $pdf->download("cat-{$cat_name}.pdf");
}

And most importantly, so that it uses only the characters you need in your pdf file (6KB here) as opposed to the entire font (which will make each pdf, like, 6MB larger), you need this in your config/dompdf.php:

'enable_font_subsetting' => true,
'default_font' => 'Noto Sans JP'

And, of course, I drop the necessary .tff font files in my public/fonts folder.

“cat-storven.pdf” — A beautiful pdf written in html

I don’t have a cat.

--

--

Marc C
Marc C

Written by Marc C

Both a creative and critical thinker, I am a programmer, bicycle rider, and woodworker, based in Japan.

No responses yet