How to embed fonts into a PDF with TCPDF?

2019-09-21 12:35发布

问题:

I have tried to use TCPDF whose code is given below:

require_once($_SERVER['DOCUMENT_ROOT'].'/tcpdf/tcpdf.php'); 
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor('Nicola Asuni');
$pdf->SetTitle('TCPDF Example 061');
$pdf->SetSubject('TCPDF Tutorial');
$pdf->SetKeywords('TCPDF, PDF, example, test, guide');
$pdf->setPrintHeader(false);
$pdf->setPrintFooter(false);
$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
$pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
$pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
$pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
if (@file_exists($_SERVER['DOCUMENT_ROOT'].'/tcpdf/config/lang/eng.php')) {
    require_once($_SERVER['DOCUMENT_ROOT'].'/tcpdf/config/lang/eng.php');
    $pdf->setLanguageArray($l);
}
$pdf->SetFont('helvetica', '', 10); 
$html ="";
$pdf->AddPage();
$html .='<style>'. file_get_contents('http://localhost/Projects/PDF/css/style_4.css').'</style>';
$html .= file_get_contents("http://localhost/Projects/PDF/mycon.php"); 
$pdf->writeHTML($html, true, false, true, false, '');
$pdf->lastPage();
$pdf->Output('example_061.pdf', 'I');

The above code generates a PDF successfully but is not taking my CSS and fonts that I have defined into "style_4.css" and included externally.

I have also tried to include CSS on the page itself "mycon.php" but its not taking from there as well. What am I doing wrong?

Note: I have different fonts which will be dynamically attached with layout based on certain conditions.

回答1:

See TCPDF's documentation:

Using the addTTFfont() method you can directly create a TCPDF font starting from a TrueType, OpenType or Type1 font. NOTE: The 'fonts' folder must be writeable by the webserver.

For example:

$fontname = $pdf->addTTFfont('/path-to-font/DejaVuSans.ttf', 
                                'TrueTypeUnicode', '', 32);


标签: php html pdf tcpdf