You are here: |Blog|Computers|How To Add A Webfont To Dompd

How to add a webfont to DOMPDF


Computers

DOMPDF is a reliable class to convert HTML documents to PDF.

If you haven't already downloaded DOMPDF, you can get it from here:

https://github.com/dompdf/dompdf/releases

These fonts are embedded within the release:

  • Courier (Normal, Bold, Oblique, and BoldOblique variants)
  • Helvetica (Normal, Bold, Oblique, and BoldOblique variants)
  • Times (Normal, Bold, Oblique, and BoldOblique variants)
  • Symbol
  • ZapfDingbats

and, as of release 0.6.0, DejaVu TrueType fonts are also included.

And now the fun begins!

Lets say that we want to embed the "Roboto" webfont (regular and bold).

Download load_font.php to the same lib directory as dompdf

    curl -o load_font.php https://raw.githubusercontent.com/dompdf/utils/master/load_font.php

Open load_font.php with your favorite text editor.

Replace

    require_once "autoload.inc.php";

To:

    require_once 'dompdf/autoload.inc.php'; 

Download Roboto font (regular and bold variations) from your favorite source, and place both .ttf under the same lib folder and in subfolder fonts.

    lib/fonts/

This is the generic way to run the load_font.php script

    php load_font.php new_font_family ./path/to/new_font.ttf

...or in our case:

    php load_font.php Roboto ./fonts/Roboto-Regular.ttf ./fonts/Roboto-Bold.ttt

The new webfont is now embedded in DOMPDF!

 

To use it, specify it in the head tag of your html code:

    $page='<html>
<head>
<style>
body{font-family: 'Roboto', sans-serif;}
... rest of css rules here ...
</style>
... your other 'head' tags here ...
</head>
<body>
... HTML CONTENT HERE ...
</body>
</html>
';

/* then use DOMPDF to make the conversion: */

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

use Dompdf\Dompdf;

$dompdf = new Dompdf();

$dompdf->loadHtml($page, "UTF-8");

$dompdf->setPaper("A4", "portrait");

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

$dompdf->render();

$dompdf->stream(); // stream the pdf in browser

The above commands for DOMPDF are pretty much self explainatory. 
For any further clarifications, refer to the author's page:

https://github.com/dompdf/dompdf

 


We will be delighted to hear from you

Our Mission Top

gdb

Innovations and new technologies are the priority of the company and it does not stop constantly updating.

To have impeccable, immediate and efficient customer service throughout the range of electronic devices

Products certified and quality for all coverage of electronic devices-needs of the consumer

chart