fpdfcjkbin(FPDF与中文支持的解决方案——fpdfcjkbin)

双枪

FPDF与中文支持的解决方案——fpdfcjk.bin

FPDF的基本介绍

FPDF是一个轻量级的PDF生成库,提供了一些基本的绘制图形、文字等元素的方法。由于其轻量级特性,难以直接支持中文输出,本文将介绍一种解决方案——fpdfcjk.bin。

什么是fpdfcjk.bin

fpdfcjk.bin是fpdf库的一个扩展,能够实现对中文的支持。该扩展提供了两种方案,一种是使用TrueType字体文件,另一种是使用嵌入字形。两者各有优劣,具体应根据需求选择。

如何使用fpdfcjk.bin

使用fpdfcjk.bin需要进行如下步骤:

  • 下载fpdfcjk.bin扩展
  • 将扩展文件复制到fpdf库的font文件夹中
  • 修改fpdf.php文件,加入中文字体的支持,具体代码如下:
``` require('fpdf.php'); require('font/cjk.php'); class PDF extends FPDF { protected $_cjkFont = 'FangSong'; function SetCjkFont($font){ $this->_cjkFont = $font; } function WriteCjk($h, $txt, $link='', $indent=false,$border=0,$align='L') { // Output as justified text if($align=='J') $this->Cell(0,$h,$txt,$border,1,'J',$link,$indent); else { // Extract words $words = preg_split('/ +/', $txt); $space = $this->GetStringWidth(' '); $indent = ($indent) ? str_repeat(' ', $indent).$this->_cjkFont : ''; $this->Cell($this->GetStringWidth($indent), $h, $indent, $border, 0, 'R', false, $link); $w = 0; foreach($words as $word){ $wordWidth = $this->GetStringWidth($word); if($w + $wordWidth < $this->lMargin + $this->w - $this->rMargin) { $this->Cell($wordWidth+$space, $h, $word, $border, 0, $align, false, $link); $w += $wordWidth + $space; } else { $this->Cell(0, $h, '', $border, 1); $this->Cell($this->GetStringWidth($indent), $h, $indent, $border, 0, 'R', false, $link); $w = $wordWidth; $this->Cell($wordWidth+$space, $h, $word, $border, 0, $align, false, $link); } } } } } ```

fpdfcjk.bin的优缺点

使用TrueType字体文件的方式,可以很好地保留正常的文字样式,支持各种字体以及字体风格,但相应地,会耗费较多的内存。另一种方式是使用嵌入字形,该方式可以最大程度地减小文件体积,但字形的精度会受到一定程度的影响。

总结

fpdfcjk.bin是一种解决FPDF无法直接支持中文输出的方案。具体实现过程较为简单,只需下载并安装该扩展,稍作修改即可完成中文文本的输出。不过在选择使用TrueType字体文件还是使用嵌入字形时,需要根据实际需求进行抉择。