How to add Google font to mPDF
Home » BLOG » Web development » How to add Google font to mPDF

How to add Google font to mPDF

category:  Web development

A few days ago, I added the Open Sans font which is a Google font into the mPDF library. My client uses mPDF 6.1. It is super easy. Here the steps you can follow.

  • Download the custom fonts you want. For example, we want to add the Open Sans font. You can download the font files from here.
  • Once the downloading file is complete. You will extract that download zip file. Then you will see the OpenSans-Bold.ttf, OpenSans-BoldItalic.ttf and so on.
  • Copy these font files into “/ttfonts” in the mPDF library
  • Next, you have to declare the font-family, in this case, OpenSans into the config_fonts.php in the mPDF library as it shows below.
$this->fontdata = array(
...
"open-sans" => array(
		'R' => "OpenSans-Regular.ttf",
		'B' => "OpenSans-Bold.ttf",
		'I' => "OpenSans-Italic.ttf",
		'BI' => "OpenSans-BoldItalic.ttf",
	),
);
  • Now you are set. In your stylesheet, you can add the font-family style with your custom font. Just remember, you have to refer to the property name of your custom font that you declare in the config_fonts.php in your stylesheet. In my case, I declare the OpenSans as open-sans. So in my stylesheet, I will use open-sans for the font-family like so.
body {
    font-family: open-sans,sans-serif;
    background-color: #EEEEEE;
    color:#333;
}

And that’s it. Simply and easy.