Keywords: Dompdf | Custom Fonts | PDF Generation
Abstract: This article provides an in-depth exploration of custom font configuration mechanisms in the Dompdf library, detailing multiple implementation approaches. It begins by analyzing the limitations of Dompdf's default font support, then systematically introduces three primary font loading methods: dynamic loading via CSS @font-face rules, preloading using the command-line tool load_font.php, and configuration through the built-in admin interface fonts.php. For different Dompdf versions (particularly 0.7.0 and above), the article offers adapted solutions, including how to obtain and configure standalone font loading utilities. Through complete code examples and configuration steps, this guide provides developers with comprehensive coverage from fundamental concepts to advanced practices, ensuring accurate custom font application in PDF generation processes and resolving common font rendering issues.
Overview of Dompdf Font Support Mechanism
Dompdf, as a PHP-based HTML to PDF conversion library, builds its font handling mechanism on the underlying R&OS PDF class. By default, Dompdf only supports a limited set of core fonts: Helvetica, Times-Roman, Courier, Zapf-Dingbats, and Symbol, which use Windows ANSI encoding. When developers specify other fonts in CSS, such as font-family: NeutraText-Book mentioned in the question, Dompdf falls back to the default Times New Roman, resulting in font rendering that does not meet expectations.
Font Formats and Loading Principles
Dompdf supports two font formats: Type 1 (.pfb) and TrueType (.ttf), provided that the corresponding font metric files (.afm/.ufm) are available. The core purpose of font loading is to generate font metric data, which is used for precise typesetting calculations. Dompdf utilizes the integrated php-font-lib library for font loading and subsetting, ensuring optimized PDF file sizes.
Method 1: Dynamic Loading via CSS @font-face
For scenarios requiring online font loading, CSS @font-face rules can be employed. This method does not require command-line access and is suitable when font files are accessible via HTTP. Below is a complete example:
<style>
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: normal;
src: url(http://themes.googleusercontent.com/static/fonts/opensans/v8/cJZKeOuBrn4kERxqtaUH3aCWcynf_cDxXwCLxiixG1c.ttf) format('truetype');
}
.sub-header {
font-size: 1.4rem;
text-transform: uppercase;
font-family: 'Open Sans', sans-serif;
padding-bottom: 1.5rem;
}
</style>
In PHP code, simply load the HTML containing these styles normally:
$pdf = PDF::loadHTML($view);
return $pdf->stream();
Method 2: Preloading Fonts via Command-Line Tool
For scenarios requiring local font files, the load_font.php utility can be used for preloading. This tool was originally distributed with Dompdf but is no longer included by default starting from version 0.7.0. The complete workflow for acquisition and usage is as follows:
- Download the standalone
load_font.phpfile:curl -o load_font.php https://raw.githubusercontent.com/dompdf/utils/master/load_font.php - Modify the autoload path in the file to point to the project's
autoload.inc.phporvendor/autoload.php:require_once 'vendor/autoload.php'; - Execute the font loading command, with parameters依次为 font name, normal font file path, bold font file path (optional), italic font file path (optional), bold-italic font file path (optional):
php load_font.php "NeutraText-Book" /path/to/neutratext.ttf
Upon successful loading, font files will be copied to the vendor/dompdf/dompdf/lib/fonts/ directory, with corresponding metric files generated.
Method 3: Programmatic Font Registration
For scenarios requiring finer control, fonts can be registered directly via Dompdf's API. This method is particularly suitable for dynamic font loading or environments with specific permission management requirements:
$options = new Dompdf\Options();
$options->setChroot('/var/www/html/fonts');
$dompdf = new Dompdf\Dompdf($options);
$dompdf->getFontMetrics()->registerFont(
['family' => 'Muli', 'style' => 'normal', 'weight' => 'normal'],
'/var/www/html/fonts/muli-v20-latin-regular.ttf'
);
$html = '<style>div{font-family: "Muli";}</style><div>Content</div>';
$dompdf->loadHtml($html);
$dompdf->render();
This method requires ensuring that the web server has write permissions to the font directory, typically achieved through chmod 775 and appropriate user group configuration.
Version Compatibility and Best Practices
As Dompdf versions evolve, font loading approaches have changed. For version 0.7.0 and above:
load_font.phpand thefonts.phpadmin interface are no longer included by default- Using standalone font loading tools or programmatic registration is recommended
- Ensure correct font file paths and avoid permission issues
In practical projects, it is advisable to:
- Prioritize CSS
@font-facefor online font loading to simplify deployment - Use command-line tools for preloading fonts in offline environments
- Adopt programmatic registration in shared hosting or restricted environments
- Always test font rendering effects to ensure cross-platform consistency
Common Issues and Solutions
1. Fonts not taking effect: Verify font file paths are correct and ensure Dompdf has read permissions. Confirm that font names in CSS exactly match registered names.
2. Character encoding issues: Ensure HTML documents specify correct character encoding, such as <meta http-equiv="Content-Type" content="charset=utf-8" />.
3. Large font file sizes: Enable font subsetting option: $dompdf->set_option('isFontSubsettingEnabled', true);, embedding only actually used characters.
4. Multiple font weight support: Register different variants (e.g., bold, italic) of the same font separately, and correctly specify font-weight and font-style in CSS.
Conclusion
While custom font configuration in Dompdf involves multiple steps, by understanding its underlying mechanisms and selecting appropriate methods, various font requirements can be reliably implemented. Whether for simple online font loading or complex enterprise-level font management, the methods introduced in this article provide complete solutions. Developers should flexibly choose and combine these techniques based on specific environments, version requirements, and project needs in practical applications, ensuring quality and consistency in PDF generation.