Haru 和 PDFlib 这二个php扩展提供了完整的api来操作pdf文档。
另外还有很多开源的代码,可以操作pdf。
这篇文章主要讲解Zend Framework 中的 Zend_Pdf组件。
Zend_Pdf 是纯PHP实现的一套程序,不依赖于其它的任何外部库文件。
所以在虚拟主机上用起来是蛮合适的。
Zend_Pdf 可以对PDF进行绝大部分的操作,比如添加/删除页面,插入文件和图片,
绘图,更改PDF文档的元信息(update document meta-data)等等。
下面就以一个简单的例子开始吧:
<?php
// include auto-loader class
require_once 'Zend/Loader/Autoloader.php';
// register auto-loader
$loader = Zend_Loader_Autoloader::getInstance();
try {
// create PDF
$pdf = new Zend_Pdf();
// create A4 page
$page = new Zend_Pdf_Page(Zend_Pdf_Page::SIZE_A4);
// define font resource
$font = Zend_Pdf_Font::fontWithName(Zend_Pdf_Font::FONT_HELVETICA);
// set font for page
// write text to page
$page->setFont($font, 24)
->drawText('That which we call a rose,', 72, 720)
->drawText('By any other name would smell as sweet.', 72, 620);
// add page to document
$pdf->pages[] = $page;
// save as file
$pdf->save('example.pdf');
echo 'SUCCESS: Document saved!';
} catch (Zend_Pdf_Exception $e) {
die ('PDF error: ' . $e->getMessage());
} catch (Exception $e) {
die ('Application error: ' . $e->getMessage());
}
程序一开始就引入了Zend auto-loader,它会自动include所需的类文件。
程序其它部分的流程就不解释了,直接看注释就可以明白了。
drawText函数的后两个参数是初始写入位置的X轴坐标和Y轴坐标。
注意:Zend_Pdf系统使用 Postscript geometry。也就是说,字体的单位是pt。1pt=1/72 inch;(0,0)原点位于页面的左下脚。http://framework.zend.com/manual/zh/zend.pdf.html
相关文章: