用PHP编写PDF文档生成器
从上面的例子可以看出,要画一条直线,只需要三个函数即可:PDF_moveto(), PDF_lineto() 和 PDF_stroke()。上面的例子是先用PDF_moveto($pdf, 20, 780)函数把光标移动到坐标(20,780),然后用PDF_lineto($pdf, 575, 780)函数定义直线的另外一个点的坐标(575,780),最后用PDF_stroke($pdf)画出线。设定颜色的函数PDF_setcolor($pdf, "stroke", "rgb", 0, 0, 0)有好几个参数,其中的颜色填充模式有stroke、fill、both三种选项,颜色可以是RGB或CMYK配色方案的颜色值。值得注意的是:PDF_setcolor()函数中使用的值是颜色的百分比,也就是说是该颜色的亮度,比如:如果想设为红色(RGB:255,0,0),你可以这样写:PDF_setcolor($pdf, "stroke", "rgb", 1, 0, 0),如果想设为黄色,可以这样:PDF_setcolor($pdf, "stroke", "rgb", 1, 1, 0)。
PDF_setcolor($pdf, "fill", "rgb", 1, 1, 0);
PDF_setcolor($pdf, "stroke", "rgb", 0, 0, 0);
PDF_rect($pdf, 50, 500, 200, 300); PDF_fill_stroke($pdf); PDF_setcolor($pdf, "fill", "rgb", 0, 1, 0); PDF_setcolor($pdf, "stroke", "rgb", 0, 0, 1);
PDF_set_info_creator($pdf, "Meng Xianhui"); PDF_set_info_title($pdf, "PHP Exam"); PDF_set_info_subject($pdf, "PHP"); PDF_set_info_keywords($pdf, "PHP PDF PDFLib");
说到这里,相信大家对如何使用PDFLib创建PDF文档有了基本的了解了吧。下面,我们就以一个实际的例子来看看如何为我们的工作服务。这个例子就是根据提供的数据来生成饼图,首先,建立一个数据输入表单,输入饼图中每一块的大小。文件如下:
<head> <title>利用PHP创建PDF文档(饼图)</title> </head> <body> <h3>饼图生成器</h3> <table cellspacing="5" cellpadding="5"> <form action="pie.php" method=POST> <tr> <td>请输入饼图中每一块的数据值,以(,)分割开:</td></tr> <tr><td><input type=text name=data></td></tr> <tr><td><input type=submit value="产生PDF饼图"></td></tr> </form> </table> </body> </html>
// 接受书库 $data = $_POST['data']; $slices = explode(",", $data);
$sum = 0; $degrees = Array(); $diameter = 200; $radius = $diameter/2;
$colours = array(array(0,0,0),array(0,0,1),array(0,1,0), array(1,0,0),array(0,1,1),array(1,1,0), array(1,0,1));
$sum = array_sum($slices);
for ($y=0; $y<sizeof($slices); $y++) { $degrees[$y] = ($slices[$y]/$sum) * 360; }
$pdf = PDF_new(); PDF_open_file($pdf, "chart.pdf"); PDF_begin_page($pdf, 500, 500); PDF_setcolor($pdf, "stroke", "rgb", 1, 1, 0); PDF_moveto($pdf, 250, 250); PDF_lineto($pdf, 350, 250); PDF_stroke($pdf);
{ // 设定填充颜色 PDF_setcolor($pdf, "fill", "rgb", $colours[$z][0], $colours[$z][1], $colours[$z][2]);
$end_x = round(250 + ($radius * cos($last_angle*pi()/180))); $end_y = round(250 + ($radius * sin($last_angle*pi()/180)));
PDF_moveto($pdf, 250, 250); PDF_lineto($pdf, $end_x, $end_y);
PDF_arc($pdf, 250, 250, $radius, $last_angle,($last_angle+$degrees[$z]));
$last_angle = $last_angle+$degrees[$z];
PDF_fill_stroke($pdf); }
PDF_circle($pdf, 250, 250, 100); PDF_stroke($pdf);
PDF_close($pdf);
$buf = PDF_get_buffer($p); $len = strlen($buf); header("Content-type: application/pdf"); header("Content-Length: $len"); header("Content-Disposition: inline; filename=Pie_php.pdf"); print $buf; PDF_delete($p); ?> 运行上面的程序,并输入不同数值,你将会得到不同的饼图。 PDFLib是一个兼容性很好的模块,你不但可以用PHP编写,还可以用Java,C#,VB.NET,VB5/6(ActiveX/COM),ASP(VBScript/Jscript),Borland Delphi, Windows Script Host,ColdFusion4.5+,C/C++,Python,Perl,RPG;支持的平台不仅仅有Windows,还有Unix/Linux,Mac OS,IBM eServer iSeries 400 和 zSeries S/390等,具体的运行环境请随时访问他们的网站得到最新的资料。 (编辑:焦作站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |