$fontDir = __DIR__ . '/fonts';
$customFont = $fontDir . '/COOPBL.ttf';
$fontMetrics = $dompdf->getFontMetrics();
$customFontFamily = $fontMetrics->getFont('Cooper Black', 'bold', $customFont);
$html = "
<!DOCTYPE html>
<style>
@font-face {
font-family: 'Cooper Black';
src: url('$customFont') format('truetype');
font-weight: 900%;
font-style: normal;
}
.coop {
font-family: 'Cooper Black';
}
I am using dompdf to generate pdf, but my custom font is not picking up. I want the fonts to pick up. Why is my custom font not picking up? Please help me. Please provide me a example, that works.
Not sure if the API methods you're using are still working with your current version of DOMPdf.
Here's script working in DOMPDF version 3.0.0 (running on php 8.2) as described here:
"About Fonts and Character Encoding"
<?php
require_once 'dompdf/autoload.inc.php';
// reference the Dompdf namespace
use Dompdf\Dompdf;
// define fontDir/tmp directory
$fontDir = __DIR__ . '/fonts';
// instantiate and use the dompdf class
$dompdf = new Dompdf([
'fontDir' => $fontDir,
'fontCache' => $fontDir,
'tempDir' => $fontDir,
'chroot' => $fontDir,
]);
$fontRegular = 'fonts/Poppins-Regular.ttf';
$fontBlack = 'fonts/Poppins-Black.ttf';
//create html
$html = "
<!DOCTYPE html>
<head>
<meta http-equiv='Content-Type' content='text/html; charset=utf-8' />
<style>
@font-face {
font-family: 'Cooper';
src: url('$fontRegular') format('truetype');
font-weight: 400;
font-style: normal;
}
@font-face {
font-family: 'Cooper';
src: url('$fontBlack') format('truetype');
font-weight: 900;
font-style: normal;
}
body{
font-family: 'Cooper';
font-weight: 400;
color:red;
}
h1{
font-family: 'Cooper';
font-weight: 900;
color:#000;
}
</style>
</head>
<body>
<h1>Hamburglefontiv <br>123456</h1>
<p>Hamburglefontiv <br>123456</p>
</body>
</html>";
echo($html);
// process HTML
$dompdf->loadHtml($html);
// (Optional) Setup the paper size and orientation
$dompdf->setPaper('A4', 'landscape');
// Render the HTML as PDF
$dompdf->render();
$output = $dompdf->output();
file_put_contents('test.pdf', $output);
?>
It is important to specify a temporary directory when initializing DOMPDF:
$fontDir = __DIR__ . '/fonts';
// instantiate and use the dompdf class
$dompdf = new Dompdf([
'fontDir' => $fontDir,
'fontCache' => $fontDir,
'tempDir' => $fontDir,
'chroot' => $fontDir,
]);
In the above example I created/defined a "fonts" directory in the root directory of the page.
You may also need to delete previous files in this directory like installed-fonts.json
to prevent caching not working files.
Another problem in your CSS font rule you're using %
units - these values need to be unitless like so: font-weight: 900
.