John
John

Reputation: 3050

Dompdf and set different font-family

When generating a PDF it totally ignores my font-family attribute applied to my CSS. Instead of say Verdana, it uses Times New Roman. So my CSS look like:

.sub-header {
    font-size: 1.4rem;
    text-transform: uppercase;
    font-family: NeutraText-Book !important;
    padding-bottom: 1.5rem;
}

The PDF is generated like this:

$pdf = PDF::loadHTML($view);
return $pdf->stream();

How can I set a font I want?

Upvotes: 52

Views: 180727

Answers (11)

Marcin Wesel
Marcin Wesel

Reputation: 104

Probably the easiest way to use custom fonts in DOMPDF is just to link it's source like in standard HTML document. The below example works perfectly - supports latin-ext characters and properly interprets UTF-8.

See the example:

<head>
  <meta http-equiv="Content-Type" content="charset=utf-8" />
  <link href='https://fonts.googleapis.com/css?family=Barlow&subset=latin-ext' rel='stylesheet'>
  <style>
    body {
        font-family: 'Barlow';
        font-size: 14px;
    }
  </style>
</head>

Upvotes: 1

hansrouge
hansrouge

Reputation: 203

I struggled a lot implementing custom fonts.

I found an easy and working solution. All Credits go to https://peterdev.pl/how-to-set-a-font-in-pdf/

So this is how you do it, if you installed dompdf with composer:

$html = '<style type="text/Css">
      @font-face {
         font-family: "Muli";
         font-style: normal;
         font-weight: normal;
      }

      div{ 
         font-family: "Muli";
      }
   </style>

    <div>My PDF File in Muli</div>';

$fontDirectory = '/var/www/html/fonts'; //change to the diretory where you fonts is located on your server
$options = new Dompdf\Options();
$options->setChroot($fontDirectory);

$dompdf = new Dompdf\Dompdf($options);
$dompdf->getFontMetrics()->registerFont(
        ['family' => 'Muli', 'style' => 'normal', 'weight' => 'normal'],
        $fontDirectory . '/muli-v20-latin-regular.ttf'
); // you have to set the style (e.g. italic) and weight (e.g. bold)
$dompdf->loadHtml($html);
$dompdf->render();

Dompdf will save the fonts to this directory:

vendor/dompdf/dompdf/lib/fonts

Your script needs write access (chmod 775 and chown www-data:www-data should work) to this directory.

Thats it. Hope it works for you as well :)

Upvotes: 11

8ctopus
8ctopus

Reputation: 3237

Here's the 2022 way to do it:

composer require dompdf/dompdf:^1.2


use Dompdf\Dompdf;

require '../vendor/autoload.php';

$html = <<<HTML
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link href="https://fonts.googleapis.com/css2?family=Montserrat&display=swap" rel="stylesheet" />
<link href="https://fonts.googleapis.com/css2?family=Tangerine&display=swap" rel="stylesheet" />
<style>

.m {
    font-family: 'Montserrat';
}

.t {
    font-family: 'Tangerine';
}

</style>
</head>
<body>
    <p class="m">
        Montserrat
    </p>
    <p class="t">
        Tangerine
    </p>
</body>
</html>
HTML
;

//$_dompdf_show_warnings = true;
//$_dompdf_debug = true;

$tmp = sys_get_temp_dir();

$dompdf = new Dompdf([
    'logOutputFile' => '',
    // authorize DomPdf to download fonts and other Internet assets
    'isRemoteEnabled' => true,
    // all directories must exist and not end with /
    'fontDir' => $tmp,
    'fontCache' => $tmp,
    'tempDir' => $tmp,
    'chroot' => $tmp,
]);

$dompdf->loadHtml($html);

$dompdf->render();

$dompdf->stream('hello.pdf', [
    'compress' => true,
    'Attachment' => false,
]);

Upvotes: 8

msayubi76
msayubi76

Reputation: 1658

DOMPDF advise to load your fonts from storage/fonts/ directory. You can see it inside config/dompdf.php in defines array at key font_dir. My problem solved by copy and paste my fonts files inside storage/fonts directory.

Upvotes: 0

Woody Hayday
Woody Hayday

Reputation: 127

Lots of answers here, struggled to get any to provide cross-language support reliably. I believe that for those of us making distributed software, there is also server-setting blocks which stop some functionality such as @import and src:url() in pdfdom automatically working to embed a font.

The following solution has worked across many servers & locally hosted sites, and requires no command line access:

  1. Retrieve font you want to use as a .ttf (for language support including Cyrillic, Greek, Devanagari, Latin, and Vietnamese, we used Noto Sans with all optional languages checked)
  2. Run/build-in the following script and fire PDFBuilder_install_font_family() ONCE only (singular install)

Gist for PDFBuilder_install_font_family()

Upvotes: 0

Ramesh
Ramesh

Reputation: 1555

You need to use dompdf library for generate pdf with specific font family.

$html ='<!doctype html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>';

$html.='</head><body>';
$html.="<style> 
@font-face { font-family: 'Roboto Regular'; font-weight: normal; src: url(\'fonts/Roboto-Regular.ttf\') format(\'truetype\'); } 
@font-face { font-family: 'Roboto Bold'; font-weight: bold; src: url(\'fonts/Roboto-Bold.ttf\') format(\'truetype\'); } 
body{ font-family: 'Roboto Regular', sans-serif; font-weight: normal; line-height:1.6em; font-size:17pt; }
h1,h2{ font-family: 'Roboto Bold', sans-serif; font-weight: bold; line-height:1.2em; }
</style>";

$html.='test <br>
<span style="font-family:\'Open Sans\'"> test </span> <br>          ';
$html.= '</body></html>';

$dompdf = new Dompdf\Dompdf();
$dompdf->load_html($html,'UTF-8');
$dompdf->set_paper('A4', 'portrait');
$dompdf->render();
$dompdf->stream();

Upvotes: 1

Mayra M
Mayra M

Reputation: 744

I have a similar problem and i have been looking a solution for 2 days...With the new version, the accepted answer does not work any more.

@jay-bienvenu answer is correct. The new version of DomPDF does not include everything and also there is a very poor documentation.

So you will have to:

  1. download load_font.php and place it to the root directory of your project: curl -o load_font.php https://raw.githubusercontent.com/dompdf/utils/master/load_font.php

  2. then open load_font.php with your editor and place the correct path to your autoload.inc.php, eg require_once 'lib/dompdf/autoload.inc.php';

  3. Open the command line, go to the root folder of your project, and run the utility with the name of the font you are registering and the path to the TFF file eg php load_font.php SourceSansPro ./pathToYourFolder/lib/dompdf/SourceSansPro-Regular.ttf ./pathToYourFolder/lib/dompdf/SourceSansPro-Bold.ttf

Now the font is installed. You may use it as you would normally would as a webfont in html:

<html>
<head>
    <meta http-equiv="Content-Type" content="charset=utf-8" />
    <style type="text/css">
        @page {
            margin: 0;
        }
        * { padding: 0; margin: 0; }
        @font-face {
            font-family: "source_sans_proregular";           
            src: local("Source Sans Pro"), url("fonts/sourcesans/sourcesanspro-regular-webfont.ttf") format("truetype");
            font-weight: normal;
            font-style: normal;

        }        
        body{
            font-family: "source_sans_proregular", Calibri,Candara,Segoe,Segoe UI,Optima,Arial,sans-serif;            
        }
    </style>
</head>
<body>
Your code here ....
</body>
</html>

and to make the pdf in php:

require_once 'lib/dompdf/autoload.inc.php';

use Dompdf\Dompdf;

// instantiate and use the dompdf class
$dompdf = new Dompdf();
$dompdf->loadHtml($html, 'UTF-8');

// (Optional) Setup the paper size and orientation
$dompdf->setPaper('A4');

$dompdf->set_option('defaultMediaType', 'all');
$dompdf->set_option('isFontSubsettingEnabled', true);

// Render the HTML as PDF
$dompdf->render();

EDIT: i made a blog post about how to use dompdf and apply custom fonts so that things can be more detailed: https://www.blog.lab21.gr/using-domdpf-create-pdf-php

Upvotes: 35

Jay Bienvenu
Jay Bienvenu

Reputation: 3293

Dompdf's About Fonts and Character Encoding says the font utility is included but doesn't tell you how to get it and run it. Here's how:

  1. Download load_font.php to the root directory of your project. curl -o load_font.php https://raw.githubusercontent.com/dompdf/utils/master/load_font.php

  2. Open load_font.php with a text editor (e.g. vim). Change require_once "autoload.inc.php"; to require_once "vendor/autoload.php";

  3. Run the utility with the name of the font you are registering and the path to the TFF file. For example: php load_font.php 'Brush Script MT' https/fonts/brush-script-mt.ttf

Read the code for load_font.php for more information about how to use this command.

Upvotes: 10

BrianS
BrianS

Reputation: 13914

PDF documents internally support the following fonts: Helvetica, Times-Roman, Courier, Zapf-Dingbats, & Symbol (all using Windows ANSI encoding). dompdf will embed any referenced font in the PDF so long as it has been pre-loaded or is accessible to dompdf and referenced in a CSS @font-face rule. The loading process is necessary in order to produce the font metrics used for type setting.

dompdf supports the same fonts as the underlying R&OS PDF class: Type 1 (.pfb) and TrueType (.ttf) so long as the font metrics (.afm/.ufm) are available. The bundled, PHP-based php-font-lib provides support for loading and sub-setting fonts.

The process for loading a font varies depending on your needs and server access. There are three ways you can load a font:

  1. Use CSS @font-face rules to load a font at run-time.
  2. From the command line use dompdf/load_font.php.
  3. Browse to dompdf/www/fonts.php in the included admin site.

Use CSS @font-face rules to load a font at run-time

No command line access required. So long as the font you want to load is available online you can load it easily via CSS.

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

From the command line use dompdf/load_font.php

If you have access to the command line then loading a font is as simple as:

[php] load_font.php "NeutraText-Book" /path/to/neutratext.ttf

Run the command without any parameters to see help text. Quickly, though, the parameters are: name of the font, normal font file, bold font file, italic font file, bold-italic font file

Browse to dompdf/www/fonts.php in the included admin site

Self-explanatory (sample). The only thing you need to do is make sure you've modified the admin username/password combo


Note: load_font.php and the admin site will not be included by default starting with dompdf 0.7.0

Adapted from the dompdf wiki (Unicode How-To, About Fonts and Character Encoding) and other sources.

Upvotes: 51

Developer
Developer

Reputation: 3998

Thanks for the answer by Brians above, but in my case only one option worked which is by installing font using "dompdf/www/fonts.php"

it installed the font by Browsing to dompdf/www/fonts.php in the included admin site. (it will be something like http://yoursite.com/sites/all/modules/print/lib/dompdf/www/fonts.php)

Go to bottom of the page, and click on a link

[Authenticate to access this section][1]

it comes up with alert saying "password must be changed in dompdf_config.custom.inc.php".

  1. Go to dompdf_config.custom.inc.php file and add the user name and password in the bottom of the file. you can find "DOMPDF_ADMIN_USERNAME" and "DOMPDF_ADMIN_PASSWORD". uncomment these 2 lines and add user name and password for installing the font.
  2. Now, again click on [Authenticate to access this section][2], it asks for user name and password. enter user user name and password which u have given in step one.

  3. if you browse the same fonts.php path again in your browser you can find install new fonts section in the bottom of the page( you can see in image)install new fonts,(however, i moved my rockwell.ttf and rockwell.afm files to fonts folder first and then i installed here)

  4. choose your desired font ttf file and then install it. it installed and showing in installed fonts but it did not work for me. so I had to create to .afm file for my new font.(here i wanted to use rockwell font)

steps I did to create my rockwell.afm file. 1

I did this like dompdf other 14 native fonts, I'm not sure how acceptable is this. but it worked for me. I just wanted to get it done.

  • I've added my rockwell font where ever i found the dompdf native font names in php files

  • Added "rockwell" to public static $native_fonts array in dompdf/include/dompdf.cls.php file

  • Added "rockwell" array to
    dompdf/lib/fonts/dompdf_font_family_cache.dist.php file like belowadding rockwell array

thats it. it generated rockwell.afm file for me like this rockwell afm file

  • just use whatever font family you want to use like

     body {  
                    font-family: 'rockwell';
                    font-size:10;
                    }   
    

Upvotes: 2

cOle2
cOle2

Reputation: 4784

You need to have the font loaded in DomPDF. Check this page for details.

Upvotes: 1

Related Questions