Home > Backend Development > PHP Tutorial > How to Set and Enforce the Desired Font in Dompdf PDF Generation?

How to Set and Enforce the Desired Font in Dompdf PDF Generation?

Susan Sarandon
Release: 2024-11-16 01:08:02
Original
924 people have browsed it

How to Set and Enforce the Desired Font in Dompdf PDF Generation?

Overcoming Font-Family Discrepancies in Dompdf PDF Generation

Dompdf offers a convenient way to create PDFs, but users often encounter discrepancies where the specified font-family in CSS is overlooked, resulting in the default Times New Roman font in the PDF output. This commonly occurs when a custom font is employed, leading to the question: how can you set and enforce the desired font?

The solution lies in understanding how Dompdf manages fonts. PDF documents inherently support a limited set of fonts. To incorporate other fonts, Dompdf requires them to be pre-loaded or referenced in CSS using the @font-face rule. This pre-loading is essential for generating accurate font metrics during typesetting.

Dompdf supports Type 1 and TrueType fonts, provided their font metrics are available. The PHP-based php-font-lib library assists in loading and sub-setting these fonts.

Methods for Font Loading

There are several approaches to load fonts:

  • CSS @font-face Rules: Load a font dynamically via CSS if it's accessible online.
  • Command Line: Use dompdf/load_font.php to load a font from the command line. The required parameters are the font name and the path to the font files.
  • Dompdf Admin Site: Access dompdf/www/fonts.php to load fonts through the admin site. Remember to configure the admin credentials before use.

Example: CSS @font-face Rule

To load a font using a CSS @font-face rule, incorporate the following code:

@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');
}
Copy after login

Note: The load_font.php and admin site methods will be deprecated in dompdf 0.7.0 and later.

The above is the detailed content of How to Set and Enforce the Desired Font in Dompdf PDF Generation?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template