fpdf使用教程


    本教程显示了制做表的不一样方法。

<?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 <count($ header); $ i ++)
        $ this-> 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 <count($ header); $ i ++)
        $ this-> 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做为边界参数;或者,如这里所作的,一旦循环结束就添加行。

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

相关文章
相关标签/搜索