当前位置: 首页 > 工具软件 > FPDF > 使用案例 >

fpdf.php教程,fpdf使用教程 - ican2089的个人空间 - OSCHINA - 中文开源技术交流社区

华涵意
2023-12-01

表 本教程显示了制作表的不同方法。

php

require('fpdf.php');

类PDF扩展FPDF { //加载数据 function LoadData($ file) { //读取文件行 $ lines = file($ file); $ data = array(); foreach($ lines as $ line) $ data [] = explode(';',trim($ line)); return $ data; }}

//简单表 function BasicTable($ header,$ data) { // Header foreach($ header as $ col) $ this-> Cell(40,7,$ col,1); $ this-> Ln(); //数据 foreach($ data as $ row) { foreach($ row as $ col) $ this-> Cell(40,6,$ col,1); $ this-> Ln(); }} }}

//更好的表 function ImprovedTable($ header,$ data) { //列宽 $ w = array(40,35,40,45); // Header for($ i = 0; $ i Cell($ w [$ i],7,$ header [$ i],1,0,'C'); $ this-> Ln(); //数据 foreach($ data as $ row) { $ this-> Cell($ w [0],6,$ row [0],'LR'); $ this-> Cell($ w [1],6,$ row [1],'LR'); $ this-> Cell($ w [2],6,number_format($ row [2]),'LR',0,'R'); $ this-> Cell($ w [3],6,number_format($ row [3]),'LR',0,'R'); $ this-> Ln(); }} //关闭行 $ this-> Cell(array_sum($ w),0,'','T'); }}

//彩色表 function FancyTable($ header,$ data) { //颜色,线宽和粗体字体 $ this-> SetFillColor(255,0,0); $ this-> SetTextColor(255); $ this-> SetDrawColor(128,0,0); $ this-> SetLineWidth(.3); $ this-> SetFont('','B'); // Header $ w = array(40,35,40,45); for($ i = 0; $ i Cell($ w [$ i],7,$ header [$ i],1,0,'C',true); $ this-> Ln(); //颜色和字体恢复 $ this-> SetFillColor(224,235,255); $ this-> SetTextColor(0); $ this-> SetFont(''); //数据 $ fill = false; foreach($ data as $ row) { $ this-> Cell($ w [0],6,$ row [0],'LR',0,'L',$ fill); $ this-> Cell($ w [1],6,$ row [1],'LR',0,'L',$ fill); $ this-> Cell($ w [2],6,number_format($ row [2]),'LR',0,'R',$ fill); $ this-> Cell($ w [3],6,number_format($ row [3]),'LR',0,'R',$ fill); $ this-> Ln(); $ fill =!$ fill; }} //关闭行 $ this-> Cell(array_sum($ w),0,'','T'); }} }}

$ pdf = new PDF(); //列标题 $ header = array('Country','Capital','Area(sq km)','Pop。(thousands)'); //数据加载 $ data = $ pdf-> LoadData('countries.txt'); $ pdf-> SetFont('Arial','',14); $ pdf-> AddPage(); $ pdf-> BasicTable($ header,$ data); $ pdf-> AddPage(); $ pdf-> ImprovedTable($ header,$ data); $ pdf-> AddPage(); $ pdf-> FancyTable($ header,$ data); $ pdf-> Output(); ?>

[演示] 一个表只是一个单元格的集合,它是自然地从他们构建一个。第一个例子是以最基本的方式实现的:简单的框架单元格,所有相同的大小和左对齐。结果是初步的,但很快获得。

第二个表格带来了一些改进:每个列都有自己的宽度,标题居中,数字对齐。此外,水平线已被去除。这是通过Cell()方法的border参数来完成的,该方法指定必须绘制单元格的哪些边。这里我们想要左(L)和右(R)。它仍然是水平线完成表的问题。有两种可能性:检查循环中的最后一行,在这种情况下,我们使用LRB作为边界参数;或者,如这里所做的,一旦循环结束就添加行。

第三个表类似于第二个表,但使用颜色。只需指定填充,文本和线条颜色。通过使用交替透明和填充的单元获得行的交替着色。

 类似资料: