How to add TTF font to html2pdf PHP program

I am trying to use HTML2PDF 4.03 with this code:

<?php $content = "..."; # my HTML code require_once(dirname(__FILE__).'/html2pdf_v4.03/html2pdf.class.php'); $html2pdf = new HTML2PDF('P','A4','en', true, 'utf-8', array(15,20,15,20) ); # here I'm trying to add my arial.ttf $html2pdf->pdf->AddTTFFont('arial.ttf'); $html2pdf->WriteHTML($content); $html2pdf->Output('exemple.pdf'); ?> 

Now the program dies with this:

 PHP Fatal error: Call to undefined method HTML2PDF_myPdf::AddTTFFont() 

How to add a TTF font to a PDF file?

+6
source share
3 answers

I was able to add 1 custom font to my installation using the following method.

First, convert the .ttf file to 3 separate files (.php.z and .ufm) using the following font converter. Place the 3 files that this system generates into the font folder in TCPDF.

Now you can set the default font for your PDF using the following command

 $html2pdf->setDefaultFont("the_name_you_called_your_font"); 

It was pretty simple to work, I have problems using two separate fonts, but using this method. I will find out though

+7
source

If you want to add multiple fonts just use:

 $html2pdf->addFont('opensansregular', '', 'opensansregular'); $html2pdf->addFont('opensansbold', '', 'opensansbold'); 

I would suggest that you do not use special characters with the above font converter.

Then in your CSS just type:

 <style type="text/css"> <!-- .uppercase { text-transform: uppercase; } * { font-family: opensansregular; } h1, h2, h3, strong { font-family: opensansbold; } --> </style> 
+1
source

To expand the selected answer (o11y_75) when converting your fonts, you need to use a specific name to include bold and italic options as well. This way you add only one font definition like this

 $html2pdf->AddFont('opensans', 'normal', 'opensans.php'); $html2pdf->setDefaultFont('opensans'); 

When you convert fonts, name them, for example, as follows:

 default: opensans bold: opensansb italic: opensansi bold italic: opensansbi 

note that for the original name you add b, i and bi for each case. I did not find documentation on this issue, but I followed the nomenclature found on fonts that were already with TCPDF, and it worked.

+1
source

Source: https://habr.com/ru/post/981519/


All Articles