20 June 2013

TCPDF How to show/display Chinese Character?

Thanks to this article (in Simplified Chinese), there is a way to embed a TTF that can display Chinese (Traditional and Simplify, and possibly Japanese).

Environment: 

  • TCPDF 6.0.020
  • PHP 5.3.8
  • Windows 7

The problem:

If you follow this post that said: using cid0cs or cid0ct to display Chinese, it can display the character correctly, only to the extend that user installed a correct font package.  However, chances are other users who didn't install that package cannot view that PDF since there are several packages and versions of PDF viewer (mainly Adobe).  And even worse: even if user installed certain CJK font package, the PDF still not displayed correctly (show empty page).

And according to the official TCPDF documentation about font:
The fonts that could be not embedded are only the standard core fonts and CID-0 fonts.

The solution:

Again, thanks to the post above (in simplified Chinese), now developer can use a font that:
  • Can display Chinese
  • Can be embedded to PDF
The font is called: Droid Sans Fallback, which is free.  You can download it from MediaFire below:


All you need to do are:
  1. To rename it from Droid Sans Fallback.ttf to DroidSansFallback.ttf (Remove the space only)
  2. Put the file under tcpdf/fonts/ (in this case the final destination will be tcpdf/fonts/DroidSansFallback.ttf). 
  3. In your PDF generation code, enter:
    1. $pdf->addTTFfont('fonts/DroidSansFallback.ttf');  Updated: Mind the path here, please make sure you have correct path to the ttf file.
    2. $pdf->SetFont('DroidSansFallback', '', 12, '', false);
It works!

To test, you use the examples file (better use examples/example_038.php) and edit the file to test.

Points to note:
  • Make your tcpdf/fonts/ directory writable, as you call the addTTFfont() function, 3 files will be created inside that directory.  If the system cannot get access from the outside, it won't work.
  • The 3 files are: 
    • droidsansfallback.ctg.z
    • droidsansfallback.php
    • droidsansfallback.z
Hope it helps someone.

3 comments:

林晓 said...

Thanks for your solution but when I did this in my test, it returned an error:"TCPDF ERROR: Could not include font definition file: droidsansfallback"
I tested in example_038.php as you had suggested. And the platform is win8.1/php5.4/apache2.2/tcpdf6_0_053.
And I think I've opened the fonts dir for everyone to write.

林晓 said...

oh it should be $pdf->addTTFfont('./tcpdf/fonts/DroidSansFallback.ttf'); instead of $pdf->addTTFfont('./fonts/DroidSansFallback.ttf'); (missed "tcpdf" as you've pointed it out, just my fault). Again, thanks so much for your help.
BTW, are you Chinese?

Ellery Leung said...

Yes I am from Hong Kong. Glad to know that your problem is solved.

About the path problem, I don't put tcpdf in the path because my tcpdf folder structure seems not same as you.

But thank you again for pointing that out.