用PHP创建PDF中文文档

我使用的是FPDF(www.fpdf.org),下载了fpdf类库后,还要使用下面的中文类库才能支持中文,但只能使用一种中文字体(华文仿宋)。为此我烦恼了很长时间,现在终于搞定了,将TrueType字体转化为pt1字体使用:

下面是在FPDF上找的一个中文类库:
<?php
require('fpdf.php');

$Big5_widths=array(' '=>250,'!'=>250,'"'=>408,'#'=>668,'$'=>490,'%'=>875,'&'=>698,'''=>250,
'('=>240,')'=>240,'*'=>417,'+'=>667,','=>250,'-'=>313,'.'=>250,'/'=>520,'0'=>500,'1'=>500,
'2'=>500,'3'=>500,'4'=>500,'5'=>500,'6'=>500,'7'=>500,'8'=>500,'9'=>500,':'=>250,';'=>250,
'<'=>667,'='=>667,'>'=>667,'?'=>396,'@'=>921,'A'=>677,'B'=>615,'C'=>719,'D'=>760,'E'=>625,
'F'=>552,'G'=>771,'H'=>802,'I'=>354,'J'=>354,'K'=>781,'L'=>604,'M'=>927,'N'=>750,'O'=>823,
'P'=>563,'Q'=>823,'R'=>729,'S'=>542,'T'=>698,'U'=>771,'V'=>729,'W'=>948,'X'=>771,'Y'=>677,
'Z'=>635,'['=>344,''=>520,']'=>344,'^'=>469,'_'=>500,'`'=>250,'a'=>469,'b'=>521,'c'=>427,
'd'=>521,'e'=>438,'f'=>271,'g'=>469,'h'=>531,'i'=>250,'j'=>250,'k'=>458,'l'=>240,'m'=>802,
'n'=>531,'o'=>500,'p'=>521,'q'=>521,'r'=>365,'s'=>333,'t'=>292,'u'=>521,'v'=>458,'w'=>677,
'x'=>479,'y'=>458,'z'=>427,'{'=>480,'|'=>496,'}'=>480,'~'=>667);

$GB_widths=array(' '=>207,'!'=>270,'"'=>342,'#'=>467,'$'=>462,'%'=>797,'&'=>710,'''=>239,
'('=>374,')'=>374,'*'=>423,'+'=>605,','=>238,'-'=>375,'.'=>238,'/'=>334,'0'=>462,'1'=>462,
'2'=>462,'3'=>462,'4'=>462,'5'=>462,'6'=>462,'7'=>462,'8'=>462,'9'=>462,':'=>238,';'=>238,
'<'=>605,'='=>605,'>'=>605,'?'=>344,'@'=>748,'A'=>684,'B'=>560,'C'=>695,'D'=>739,'E'=>563,
'F'=>511,'G'=>729,'H'=>793,'I'=>318,'J'=>312,'K'=>666,'L'=>526,'M'=>896,'N'=>758,'O'=>772,
'P'=>544,'Q'=>772,'R'=>628,'S'=>465,'T'=>607,'U'=>753,'V'=>711,'W'=>972,'X'=>647,'Y'=>620,
'Z'=>607,'['=>374,''=>333,']'=>374,'^'=>606,'_'=>500,'`'=>239,'a'=>417,'b'=>503,'c'=>427,
'd'=>529,'e'=>415,'f'=>264,'g'=>444,'h'=>518,'i'=>241,'j'=>230,'k'=>495,'l'=>228,'m'=>793,
'n'=>527,'o'=>524,'p'=>524,'q'=>504,'r'=>338,'s'=>336,'t'=>277,'u'=>517,'v'=>450,'w'=>652,
'x'=>466,'y'=>452,'z'=>407,'{'=>370,'|'=>258,'}'=>370,'~'=>605);

class PDF_Chinese extends FPDF
{
function AddCIDFont($family,$style,$name,$cw,$CMap,$registry)
{
$i=count($this->fonts)+1;
$fontkey=strtolower($family).strtoupper($style);
$this->fonts[$fontkey]=array('i'=>$i,'type'=>'Type0','name'=>$name,'up'=>-120,'ut'=>40,'cw'=>$cw,'CMap'=>$CMap,'registry'=>$registry);
}

function AddBig5Font($family='Big5')
{
$cw=$GLOBALS['Big5_widths'];
$name='MSungStd-Light-Acro';
$CMap='ETenms-B5-H';
$registry=array('ordering'=>'CNS1','supplement'=>0);
$this->AddCIDFont($family,'',$name,$cw,$CMap,$registry);
$this->AddCIDFont($family,'B',$name.',Bold',$cw,$CMap,$registry);
$this->AddCIDFont($family,'I',$name.',Italic',$cw,$CMap,$registry);
$this->AddCIDFont($family,'BI',$name.',BoldItalic',$cw,$CMap,$registry);
}

function AddGBFont($family='GB')
{
$cw=$GLOBALS['GB_widths'];
$name='STSongStd-Light-Acro';
$CMap='GBKp-EUC-H';
$registry=array('ordering'=>'GB1','supplement'=>2);
$this->AddCIDFont($family,'',$name,$cw,$CMap,$registry);
$this->AddCIDFont($family,'B',$name.',Bold',$cw,$CMap,$registry);
$this->AddCIDFont($family,'I',$name.',Italic',$cw,$CMap,$registry);
$this->AddCIDFont($family,'BI',$name.',BoldItalic',$cw,$CMap,$registry);
}

function GetStringWidth($s)
{
if($this->CurrentFont['type']=='Type0')
return $this->GetMBStringWidth($s);
else
return parent::GetStringWidth($s);
}

function GetMBStringWidth($s)
{
//Multi-byte version of GetStringWidth()
$l=0;
$cw=&$this->CurrentFont['cw'];
$nb=strlen($s);
$i=0;
while($i<$nb)
{
$c=$s[$i];
if(ord($c)<128)
{
$l+=$cw[$c];
$i++;
}
else
{
$l+=1000;
$i+=2;
}
}
return $l*$this->FontSize/1000;
}

function MultiCell($w,$h,$txt,$border=0,$align='L',$fill=0)
{
if($this->CurrentFont['type']=='Type0')
$this->MBMultiCell($w,$h,$txt,$border,$align,$fill);
else
parent::MultiCell($w,$h,$txt,$border,$align,$fill);
}

function MBMultiCell($w,$h,$txt,$border=0,$align='L',$fill=0)
{
//Multi-byte version of MultiCell()
$cw=&$this->CurrentFont['cw'];
if($w==0)
$w=$this->w-$this->rMargin-$this->x;
$wmax=($w-2*$this->cMargin)*1000/$this->FontSize;
$s=str_replace("\r",'',$txt);
$nb=strlen($s);
if($nb>0 and $s[$nb-1]=="\n"
$nb--;
$b=0;
if($border)
{
if($border==1)
{
$border='LTRB';
$b='LRT';
$b2='LR';
}
else
{
$b2='';
if(is_int(strpos($border,'L')))
$b2.='L';
if(is_int(strpos($border,'R')))
$b2.='R';
$b=is_int(strpos($border,'T')) ? $b2.'T' : $b2;
}
}
$sep=-1;
$i=0;
$j=0;
$l=0;
$ns=0;
$nl=1;
while($i<$nb)
{
//Get next character
$c=$s[$i];
//Check if ASCII or MB
$ascii=(ord($c)<128);
if($c=="\n"
{
//Explicit line break
if($this->ws>0)
{
$this->ws=0;
$this->_out('0 Tw');
}
$this->Cell($w,$h,substr($s,$j,$i-$j),$b,2,$align,$fill);
$i++;
$sep=-1;
$j=$i;
$l=0;
$ns=0;
$nl++;
if($border and $nl==2)
$b=$b2;
continue;
}
if(!$ascii)
{
$sep=$i;
$ls=$l;
}
elseif($c==' ')
{
$sep=$i;
$ls=$l;
$ns++;
}
$l+=$ascii ? $cw[$c] : 1000;
if($l>$wmax)
{
//Automatic line break
if($sep==-1 or $i==$j)
{
if($i==$j)
$i+=$ascii ? 1 : 2;
if($this->ws>0)
{
$this->ws=0;
$this->_out('0 Tw');
}
$this->Cell($w,$h,substr($s,$j,$i-$j),$b,2,$align,$fill);
}
else
{
if($align=='J')
{
if($s[$sep]==' ')
$ns--;
if($s[$i-1]==' ')
{
$ns--;
$ls-=$cw[' '];
}
$this->ws=($ns>0) ? ($wmax-$ls)/1000*$this->FontSize/$ns : 0;
$this->_out(sprintf('%.3f Tw',$this->ws*$this->k));
}
$this->Cell($w,$h,substr($s,$j,$sep-$j),$b,2,$align,$fill);
$i=($s[$sep]==' ') ? $sep+1 : $sep;
}
$sep=-1;
$j=$i;
$l=0;
$ns=0;
$nl++;
if($border and $nl==2)
$b=$b2;
}
else
$i+=$ascii ? 1 : 2;
}
//Last chunk
if($this->ws>0)
{
$this->ws=0;
$this->_out('0 Tw');
}
if($border and is_int(strpos($border,'B')))
$b.='B';
$this->Cell($w,$h,substr($s,$j,$i-$j),$b,2,$align,$fill);
$this->x=$this->lMargin;
}

function Write($h,$txt,$link='')
{
if($this->CurrentFont['type']=='Type0')
$this->MBWrite($h,$txt,$link);
else
parent::Write($h,$txt,$link);
}

function MBWrite($h,$txt,$link)
{
//Multi-byte version of Write()
$cw=&$this->CurrentFont['cw'];
$w=$this->w-$this->rMargin-$this->x;
$wmax=($w-2*$this->cMargin)*1000/$this->FontSize;
$s=str_replace("\r",'',$txt);
$nb=strlen($s);
$sep=-1;
$i=0;
$j=0;
$l=0;
$nl=1;
while($i<$nb)
{
//Get next character
$c=$s[$i];
//Check if ASCII or MB
$ascii=(ord($c)<128);
if($c=="\n"
{
//Explicit line break
$this->Cell($w,$h,substr($s,$j,$i-$j),0,2,'',0,$link);
$i++;
$sep=-1;
$j=$i;
$l=0;
if($nl==1)
{
$this->x=$this->lMargin;
$w=$this->w-$this->rMargin-$this->x;
$wmax=($w-2*$this->cMargin)*1000/$this->FontSize;
}
$nl++;
continue;
}
if(!$ascii or $c==' ')
$sep=$i;
$l+=$ascii ? $cw[$c] : 1000;
if($l>$wmax)
{
//Automatic line break
if($sep==-1 or $i==$j)
{
if($this->x>$this->lMargin)
{
//Move to next line
$this->x=$this->lMargin;
$this->y+=$h;
$w=$this->w-$this->rMargin-$this->x;
$wmax=($w-2*$this->cMargin)*1000/$this->FontSize;
$i++;
$nl++;
continue;
}
if($i==$j)
$i+=$ascii ? 1 : 2;
$this->Cell($w,$h,substr($s,$j,$i-$j),0,2,'',0,$link);
}
else
{
$this->Cell($w,$h,substr($s,$j,$sep-$j),0,2,'',0,$link);
$i=($s[$sep]==' ') ? $sep+1 : $sep;
}
$sep=-1;
$j=$i;
$l=0;
if($nl==1)
{
$this->x=$this->lMargin;
$w=$this->w-$this->rMargin-$this->x;
$wmax=($w-2*$this->cMargin)*1000/$this->FontSize;
}
$nl++;
}
else
$i+=$ascii ? 1 : 2;
}
//Last chunk
if($i!=$j)
$this->Cell($l/1000*$this->FontSize,$h,substr($s,$j,$i-$j),0,0,'',0,$link);
}

function _putfonts()
{
$nf=$this->n;
foreach($this->diffs as $diff)
{
//Encodings
$this->_newobj();
$this->_out('<</Type /Encoding /BaseEncoding /WinAnsiEncoding /Differences ['.$diff.']>>');
$this->_out('endobj');
}
$mqr=get_magic_quotes_runtime();
set_magic_quotes_runtime(0);
foreach($this->FontFiles as $file=>$info)
{
//Font file embedding
$this->_newobj();
$this->FontFiles[$file]['n']=$this->n;
if(defined('FPDF_FONTPATH'))
$file=FPDF_FONTPATH.$file;
$size=filesize($file);
if(!$size)
$this->Error('Font file not found');
$this->_out('<</Length '.$size);
if(substr($file,-2)=='.z')
$this->_out('/Filter /FlateDecode');
$this->_out('/Length1 '.$info['length1']);
if(isset($info['length2']))
$this->_out('/Length2 '.$info['length2'].' /Length3 0');
$this->_out('>>');
$f=fopen($file,'rb');
$this->_putstream(fread($f,$size));
fclose($f);
$this->_out('endobj');
}
set_magic_quotes_runtime($mqr);
foreach($this->fonts as $k=>$font)
{
//Font objects
$this->_newobj();
$this->fonts[$k]['n']=$this->n;
$this->_out('<</Type /Font');
if($font['type']=='Type0')
$this->_putType0($font);
else
{
$name=$font['name'];
$this->_out('/BaseFont /'.$name);
if($font['type']=='core')
{
//Standard font
$this->_out('/Subtype /Type1');
if($name!='Symbol' and $name!='ZapfDingbats')
$this->_out('/Encoding /WinAnsiEncoding');
}
else
{
//Additional font
$this->_out('/Subtype /'.$font['type']);
$this->_out('/FirstChar 32');
$this->_out('/LastChar 255');
$this->_out('/Widths '.($this->n+1).' 0 R');
$this->_out('/FontDescriptor '.($this->n+2).' 0 R');
if($font['enc'])
{
if(isset($font['diff']))
$this->_out('/Encoding '.($nf+$font['diff']).' 0 R');
else
$this->_out('/Encoding /WinAnsiEncoding');
}
}
$this->_out('>>');
$this->_out('endobj');
if($font['type']!='core')
{
//Widths
$this->_newobj();
$cw=&$font['cw'];
$s='[';
for($i=32;$i<=255;$i++)
$s.=$cw[chr($i)].' ';
$this->_out($s.']');
$this->_out('endobj');
//Descriptor
$this->_newobj();
$s='<</Type /FontDescriptor /FontName /'.$name;
foreach($font['desc'] as $k=>$v)
$s.=' /'.$k.' '.$v;
$file=$font['file'];
if($file)
$s.=' /FontFile'.($font['type']=='Type1' ? '' : '2').' '.$this->FontFiles[$file]['n'].' 0 R';
$this->_out($s.'>>');
$this->_out('endobj');
}
}
}
}

function _putType0($font)
{
//Type0
$this->_out('/Subtype /Type0');
$this->_out('/BaseFont /'.$font['name'].'-'.$font['CMap']);
$this->_out('/Encoding /'.$font['CMap']);
$this->_out('/DescendantFonts ['.($this->n+1).' 0 R]');
$this->_out('>>');
$this->_out('endobj');
//CIDFont
$this->_newobj();
$this->_out('<</Type /Font');
$this->_out('/Subtype /CIDFontType0');
$this->_out('/BaseFont /'.$font['name']);
$this->_out('/CIDSystemInfo <</Registry (Adobe) /Ordering ('.$font['registry']['ordering'].') /Supplement '.$font['registry']['supplement'].'>>');
$this->_out('/FontDescriptor '.($this->n+1).' 0 R');
$W='/W [1 [';
foreach($font['cw'] as $w)
$W.=$w.' ';
$this->_out($W.']]');
$this->_out('>>');
$this->_out('endobj');
//Font descriptor
$this->_newobj();
$this->_out('<</Type /FontDescriptor');
$this->_out('/FontName /'.$font['name']);
$this->_out('/Flags 6');
$this->_out('/FontBBox [0 0 1000 1000]');
$this->_out('/ItalicAngle 0');
$this->_out('/Ascent 1000');
$this->_out('/Descent 0');
$this->_out('/CapHeight 1000');
$this->_out('/StemV 10');
$this->_out('>>');
$this->_out('endobj');
}
}
?>

将以上代码存为chinese.php即可引用。但用它只能得到一种字体。为了支持所有中文字体,可用ttf2pt1程序将TrueType字体转化pt1字体,一个一个地转(具体方法在FPDF的教程中有详细说明)。为了支持其他中文字体,养分要修改上面的chinese.php,如下:

1: Replace the following line in the AddGBFont() method:

function AddGBFont($family='GB',$name='STSongStd-Light-Acro')
{
$cw=$GLOBALS['GB_widths'];
// $name='STSongStd-Light-Acro';
$CMap='GBKp-EUC-H';
........

2: This is a Sample.

<?php
require('chinese.php');

$pdf=new PDF_Chinese();
$pdf->AddGBFont('simsun','宋体');
$pdf->AddGBFont('simhei','黑体');
$pdf->AddGBFont('simkai','楷体_GB2312');
$pdf->AddGBFont('sinfang','仿宋_GB2312'');
$pdf->Open();
$pdf->AddPage();
$pdf->SetFont('simsun','',20);
$pdf->Write(10,'简体中文汉字‘);
$pdf->SetFont('simhei','',20);
$pdf->Write(10,'简体中文汉字');
$pdf->SetFont('simkai','',20);
$pdf->Write(10,'简体中文汉字‘);
$pdf->SetFont('sinfang','',20);
$pdf->Write(10,'简体中文汉字');
$pdf->Output();
?>

(0)

相关推荐

  • C# 中使用iTextSharp组件创建PDF的简单方法

    将iTextSharp.dll文件拷贝到项目的bin目录,然后在项目中添加引用: 然后在后台代码添加引用: 复制代码 代码如下: using iTextSharp.text;using iTextSharp.text.pdf;using System.IO;using System.Diagnostics; //创建PDF private void CreatePdf() {     //定义一个Document,并设置页面大小为A4,竖向      iTextSharp.text.Docume

  • 如何创建一个PDF文件?

    <%Option ExplicitSub CheckXlDriver()      On Error Resume Next Dim vConnString      Dim oConn, oErr vConnString = "DRIVER={Microsoft Excel Driver (*.xls)};DBQ=NUL:"      ' 连接NUL. Set oConn = CreateObject("ADODB.Connection")      oCo

  • C#中创建PDF网格并插入图片的方法

    这篇文章我将向大家演示如何以编程的方式在PDF文档中创建一个网格,并将图片插入特定的网格中. 网上有一些类似的解决方法,在这里我选择了一个免费版的PDF组件.安装控件后,创建新项目,添加安装目录下的dll文件作为项目的引用以及命名空间,如下: using Spire.Pdf; using Spire.Pdf.Graphics; using Spire.Pdf.Grid; 接下来是详细步骤及代码片段: 步骤1: 首先创建一个PDF文档,并添加一个新页面. PdfDocument doc = new

  • C# 在PDF中创建和填充域

    众所周知,PDF文档通常是不能编辑和修改的.如果用户需要在PDF文档中签名或者填写其他内容时,就需要PDF文档中有可编辑的域.开发者也经常会遇到将数据以编程的方式填充到PDF模板域的需求.这时候就需要解决以下两个问题: 如何在PDF中创建可编辑的域? 如何将内容准确地填写到这些域中? 这里我将介绍怎样使用C#和Free Spire.PDF组件来实现这一功能. Free Spire.PDF组件概述 Free Spire.PDF是一个免费专业的PDF组件,用于在.NET应用程序中创建,编辑,处理和阅

  • 用PHP创建PDF中文文档

    我使用的是FPDF(www.fpdf.org),下载了fpdf类库后,还要使用下面的中文类库才能支持中文,但只能使用一种中文字体(华文仿宋).为此我烦恼了很长时间,现在终于搞定了,将TrueType字体转化为pt1字体使用: 下面是在FPDF上找的一个中文类库:<?phprequire('fpdf.php'); $Big5_widths=array(' '=>250,'!'=>250,'"'=>408,'#'=>668,'$'=>490,'%'=>875

  • 详解vue axios中文文档

    axios中文文档 在用Vue做开发的时候,官方推荐的前后端通信插件是axios,Github上axios的文档虽然详细,但是却是英文版.现在发现有个axios的中文文档,于是就转载过来了! 原文地址 : https://github.com/mzabriskie/axios 简介 版本:v0.16.1 基于http客户端的promise,面向浏览器和nodejs 特色 浏览器端发起XMLHttpRequests请求 node端发起http请求 支持Promise API 拦截请求和返回 转化请

  • three.js中文文档学习之如何本地运行详解

    前言 本文属于系列问题,需要的朋友们开始之前可以参考以下的两篇文章: 1.three.js中文文档学习之创建场景 2.three.js中文文档学习之通过模块导入 如果你只是使用程序化的几何体,不需要加载任何材质,网页应该直接从文件系统加载,只需要双击文件管理器中 HTML 文件,应该在你的浏览器能够运行(地址栏长这样子:file:///yourFile.html) 从外部文件加载内容 如果你从外部文件下载模块和材质,由于浏览器的 同源政策 的安全限制,会引发安全异常而加载失败. 有两种解决办法:

  • 详解Chai.js断言库API中文文档

    Chai.js断言库API中文文档 基于chai.js官方API文档翻译.仅列出BDD风格的expect/should API.TDD风格的Assert API由于不打算使用,暂时不放,后续可能会更新. BDD expect和should是BDD风格的,二者使用相同的链式语言来组织断言,但不同在于他们初始化断言的方式:expect使用构造函数来创建断言对象实例,而should通过为Object.prototype新增方法来实现断言(所以should不支持IE):expect直接指向chai.ex

  • 基于python-pptx库中文文档及使用详解

    个人使用样例及部分翻译自官方文档,并详细介绍chart的使用 一:基础应用 1.创建pptx文档类并插入一页幻灯片 from pptx import Presentation prs = Presentation() slide = prs.slides.add_slide(prs.slide_layouts[1]) # 对ppt的修改 prs.save('python-pptx.pptx') prs.slide_layouts中一共预存有1-48种,采用第六种为空白幻灯片 例slide_lay

  • 使用Python3内置文档高效学习以及官方中文文档

    概述 从前面的对Python基础知识方法介绍中,我们几乎是围绕Python内置方法进行探索实践,比如字符串.列表.字典等数据结构的内置方法,和大量内置的标准库,诸如functools.time.threading等等,而我们怎么快速学习掌握并学会使用这个Python的工具集呢? 我们可以利用Python的内置文档大量资源既可以掌握许多关于Python工具集的基本使用. dir函数 Python中内置的dir函数用于提取某对象内所有属性的方法,,诸如对象的方法及属性 L = [1, 2, 3, 4

  • Keras官方中文文档:性能评估Metrices详解

    能评估 使用方法 性能评估模块提供了一系列用于模型性能评估的函数,这些函数在模型编译时由metrics关键字设置 性能评估函数类似与目标函数, 只不过该性能的评估结果讲不会用于训练. 可以通过字符串来使用域定义的性能评估函数 model.compile(loss='mean_squared_error', optimizer='sgd', metrics=['mae', 'acc']) 也可以自定义一个Theano/TensorFlow函数并使用之 from keras import metri

  • three.js中文文档学习之创建场景

    什么是Three.js? 如果你正在读这篇文章,你可能对Three.js有一定的了解,那我们来简单地介绍下Three.js是什么. Three.js是一个库,使得WebGL的3D效果在浏览器中运用很容易.而在原始的WebGL中一个简单的立方体会变成数百Javascript和着色器代码的行,而一个Three.js只需要一点点代码. 本节目标是为 three.js 做简介.我们从使用旋转立方体来搭建场景开始.如果遇到困难需要帮助,页面底部有可参考的源码. 一个场景至少需要的三种类型组件 相机/决定哪

  • nodejs npm package.json中文文档

    简介 本文档有所有package.json中必要的配置.它必须是真正的json,而不是js对象. 本文档中描述的很多行为都受npm-config(7)的影响. 默认值 npm会根据包内容设置一些默认值. 复制代码 代码如下: "scripts": {"start": "node server.js"} 如果包的根目录有server.js文件,npm会默认将start命令设置为node server.js. "scripts":

  • imgAreaSelect 中文文档帮助说明

    一.技术文档 1.介绍 ImgAreaSelect是一jQuery插件,它支持用户通过鼠标拖曳选择图片的一部分,非常的fashion.另外,可以在这个选择图像区域的基础上应用网站的其他一些技术,比如图片拖曳.图片编辑等. 2.基本用法 这个插件基于jQuery上通过imgAreaSelect()方法来调用,它操作的对象是HTML中<img>元素内的图像. 复制代码 代码如下: <script type="text/javascript"> $(document)

随机推荐