Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add TTF font to html2pdf PHP program

I'm 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 die with this:

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

How can I add TTF font to my PDF file?

like image 874
netdjw Avatar asked Jan 25 '15 16:01

netdjw


2 Answers

I have managed to add 1 custom font to my setup 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 are generated by this system into the fonts 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");

This was fairly simple to get working, I am having issues using 2 seperate fonts though via this method. I'll figure it out though

like image 154
o11y_75 Avatar answered Sep 21 '22 12:09

o11y_75


To expand on the selected answer (by o11y_75) when you convert your fonts, you need to use a specific name to include also the bold and italic variants. That way, you only add one font definition like this

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

When you convert the fonts, name them, for example, like these:

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

notice that behind the original name, you add b, i and bi on each case. I have found no documentation on this issue, but I followed the nomenclature found on the fonts that already came with TCPDF and it worked.

like image 33
Ignacio Avatar answered Sep 19 '22 12:09

Ignacio