Does anybody know how to set the encoding in FPDF package to UTF-8? Or at least to ISO-8859-7 (Greek) that supports Greek characters?
Basically I want to create a PDF file containing Greek characters.
Any suggestions would help. George
UTF-8 Encoding in Notepad (Windows)Click File in the top-left corner of your screen. In the dialog which appears, select the following options: In the "Save as type" drop-down, select All Files. In the "Encoding" drop-down, select UTF-8.
Click Tools, then select Web options. Go to the Encoding tab. In the dropdown for Save this document as: choose Unicode (UTF-8). Click Ok.
Within IBM, UTF-8 has been registered as CCSID 1208 with growing character set (sometimes also referred to as code page 1208).
UTF-8 is an 8-bit variable width encoding. The first 128 characters in the Unicode, when represented with UTF-8 encoding have the representation as the characters in ASCII.
Don't use UTF-8 encoding. Standard FPDF fonts use ISO-8859-1 or Windows-1252. It is possible to perform a conversion to ISO-8859-1 with utf8_decode()
: $str = utf8_decode($str);
But some characters such as Euro won't be translated correctly. If the iconv extension is available, the right way to do it is the following: $str = iconv('UTF-8', 'windows-1252', $str);
There also is a official UTF-8 Version of FPDF called tFPDF http://www.fpdf.org/en/script/script92.php
You can easyly switch from the original FPDF, just make sure you also use a unicode Font as shown in the example in the above link or my code:
<?php //this is a UTF-8 file, we won't need any encode/decode/iconv workarounds //define the path to the .ttf files you want to use define('FPDF_FONTPATH',"../fonts/"); require('tfpdf.php'); $pdf = new tFPDF(); $pdf->AddPage(); // Add Unicode fonts (.ttf files) $fontName = 'Helvetica'; $pdf->AddFont($fontName,'','HelveticaNeue LightCond.ttf',true); $pdf->AddFont($fontName,'B','HelveticaNeue MediumCond.ttf',true); //now use the Unicode font in bold $pdf->SetFont($fontName,'B',12); //anything else is identical to the old FPDF, just use Write(),Cell(),MultiCell()... //without any encoding trouble $pdf->Cell(100,20, "Some UTF-8 String"); //... ?>
I think its much more elegant to use this instead of spaming utf8_decode() everywhere and the ability to use .ttf files directly in AddFont() is an upside too.
Any other answer here is just a way to avoid or work around the problem, and avoiding UTF-8 is no real option for an up to date project.
There are also alternatives like mPDF or TCPDF (and others) wich base on FPDF but offer advanced functions, have UTF-8 Support and can interpret HTML Code (limited of course as there is no direct way to convert HTML to PDF). Most of the FPDF code can be used directly in those librarys, so its pretty easy to migrate the code.
https://github.com/mpdf/mpdf http://www.tcpdf.org/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With