Home >Backend Development >PHP Tutorial >PHP generate PDF file
本文介绍PHP生成PDF。我们使用TCPDF开源插件,实现PHP生成PDF文档。可以插入图片、HTML、链接、表格、柱状图折线图等PHP动态生成PDF的功能。
PHP的PECL扩展有一个叫做pdflib,并且维护到了2014年1月,PDFLib库对于个人是免费的,对于商业产品需要购买许可。并且使用相对复杂。因此排除。
本文介绍一款插件,TCPDF!官网http://www.tcpdf.org。下载后在代码中引入即可使用。无需编译/安装其他的扩展。TCPDF的下载包和官网都会提供大量的示例和几十个字体(只是除个别外中文都不能用...)。采用LGPL license开源协议。
下面直奔主题。在官网下载后。假设放在了/var/www/目录下。
//第一步肯定是引入TCPDF的入口文件
require_once '/var/www/tcpdf/tcpdf.php';
//实例化
$pdf = new TCPDF('P', 'mm', 'A4', true, 'UTF-8', false);
// 设置文档信息
$pdf->SetCreator('Lane');
$pdf->SetAuthor('Lane');
$pdf->SetTitle('PHP生成PDF');
$pdf->SetSubject('PHP动态生成PDF文件');
$pdf->SetKeywords('PHP PDF TCPDF');
//设置页眉信息 参数分别是LOGO地址,LOGO大小,两行标题,标题颜色,分割线颜色。。颜色是RGB
$pdf->SetHeaderData('/var/www/tcpdf/examples/images/tcpdf_logo.jpg', 30, 'PHP生成PDF', 'PHP如何生成PDF文件', array(0,0,0), array(0,0,0));
//设置页脚信息
$pdf->setFooterData(array(0,0,0), array(0,0,0));
// 设置页眉和页脚字体
$pdf->setHeaderFont(Array('stsongstdlight', '', '12'));
$pdf->setFooterFont(Array('helvetica', '', '8'));
//设置默认等宽字体
$pdf->SetDefaultMonospacedFont('courier');
//设置间距
$pdf->SetMargins(15, 27, 15);
$pdf->SetHeaderMargin(5);
$pdf->SetFooterMargin(10);
//设置分页
$pdf->SetAutoPageBreak(TRUE, 15);
//设置图片比例
$pdf->setImageScale(1.25);
//将页眉页脚的信息输出出来。
$pdf->AddPage();
//设置字体 - 正文标题的哦。B是加粗,15是大小
$pdf->SetFont('stsongstdlight', 'B', 15);
$pdf->Write(20, 'PHP如何动态生成PDF', '', 0, 'C', true, 0, false, false, 0);
//设置字体 - 正文内容的哦。B是加粗,15是大小
$pdf->SetFont('stsongstdlight', '', 10);
//L是左对齐,R是右对齐,C是居中对齐。
$pdf->Write(0, $content,'', 0, 'L', true, 0, false, false, 0);
//输出PDF。第二个参数默认是I,是浏览器预览。D是下载
$pdf->Output('PHP_TO_PDF.pdf', 'I');
Copy and execute the above code, you will find that the browser opens the PDF file preview (if your browser is not IE). Replace the second parameter of Output with D and you can download it.
At this point, it’s basically done. But there is a problem. You will find that the font is awkward and extremely ugly. We can change the font to "droidsansfallback". This font does not come with it. You can find the download location through Google Baidu, or at http://sourceforge.net/projects/hawebs/files/Assistance/PHP/Droid%20Sans%20Fallback%20-%20PHP.zip/download. After downloading and decompressing, copy the three files droidsansfallback.php, droidsansfallback.z and droidsansfallback.ctg.z to the tcpdf/fonts/ directory. Then replace stsongstdlight in the code with droidsansfallback. After executing it, you will find that the font looks much better. . Of course, you can use tcpdf_addfont.php that comes with TCPDF to convert other fonts into fonts recognized by TCPDF, and then move them into the tcpdf/fonts/ directory. For example, Microsoft Yahei or something.
The above introduces how to generate PDF files with PHP, including some aspects. I hope it will be helpful to friends who are interested in PHP tutorials.