Problems embedding true type fonts with TCPDF
After spending many hours pulling my hair out trying to embed True Type fonts in a pdf document using TCPDF and php, I learnt an undocumented an invaluable lesson.
The problem font was Helvetica Neue (thin and roman versions). I had it as a True Type font (.ttf) and was using TCPDF’s addTTFfont method to embed the font and then setFont to use the font as per the documentation like so:
// embed the font $fontname = $pdf->addTTFfont(K_PATH_FONTS . 'helvetica55roman.ttf', 'TrueTypeUnicode', '', 32); // use the font $pdf->SetFont($fontname, '', 10);
The problem I was having was classic. It worked fine on mac, even my virtual XP box, however the client was seeing gibberish, the font was showing completely garbled text. I tried various methods for converting the font to the correct format to be used by TCPDF however none worked.
Then in my billionth google search, I found this article which has the line “….If you see the embedded fonts as anything other than True Type ansi, you’ve got a problem…“. I checked in Adobe Reader (Properties > Fonts), and sure enough my fonts were encoded as “CID Identity-H”. I then spent a long time trying to figure out how to change this, trying software, online encoders etc and reading and re-reading the TCPDF documentation.
If you have ever had the displeasure of using the TCPDF documentation then I feel for you. It’s appalling! However if you read the documentation for addTTFfont you will see there is a parameter for ‘$enc’, with no explanation of possible values. Simply changing this value to ‘ansi’ fixed my problems:
// embed the font // note the 3rd parameter $fontname = $pdf->addTTFfont(K_PATH_FONTS . 'helvetica55roman.ttf', 'TrueType', 'ansi', 32); // use the font $pdf->SetFont($fontname, '', 10);
I also changed the second parameter to ‘TrueType’ instead of ‘TrueTypeUnicode’ but not sure what bearing this has on anything. It was the encoding that fixed the issues for me.
I’ve had to use TCPDF for a few projects recently and although it does quite a lot and I’ve achieved everything I needed to, it is appalling written, the API is horrific and the documentation is even worse. Next time I am going to take a look at FPDF and see if I get on any better. However any other solutions would be welcomed!
- Using Swift Mailer plugins with Laravel 4
- Using Selenium Server 2 and PHPUnit to automate browser acceptance testing
- Laravel 4 First Thoughts
- UK Data.gov Property Price Mash Up
- Re-routing emails to a development email address with php and SwiftMailer
- php $_FILES array shorter than expected and max_file_uploads sillyness
- Find and replace html links with PHP