前言
某协会之前的项目,需要进行升级,其中有一个功能是需要将奖状导出成pdf后发给印刷厂生产。查询后决定使用tcpdf来实现,TP5 有多个pdf插件可选,其他没试,这个代码比较简单,坑也不大,就决定用这个了。
安装
composer安装
根目录使用命令:
composer require tecnickcom/tcpdf
直接拷贝
由于对方服务器composer比较老,懒得升级了,直接使用拷贝的方式,将Tcpdf文件夹拷贝到vendor文件夹下。有些文字写的是直接拷贝tecnickcom文件夹,测试无效。
使用
使用很方便
1
use TCPDF;
2
public function pdf($html="WWW",$fileName="dc"){
vendor('Tcpdf.tcpdf');
$pdf = new \Tcpdf(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
// 设置打印模式
$pdf->SetCreator(PDF_CREATOR);
// $pdf->SetAuthor('Nicola Asuni');
// $pdf->SetTitle('TCPDF Example 001');
// $pdf->SetSubject('TCPDF Tutorial');
// $pdf->SetKeywords('TCPDF, PDF, example, test, guide');
// 是否显示页眉
$pdf->setPrintHeader(false);
// 设置页眉显示的内容
// $pdf->SetHeaderData('logo.png', 60, 'baijunyao.com', '白俊遥博客', array(0,64,255), array(0,64,128));
// 设置页眉字体
$pdf->setHeaderFont(Array('dejavusans', '', '12'));
// 页眉距离顶部的距离
$pdf->SetHeaderMargin('0');
// 是否显示页脚
$pdf->setPrintFooter(false);
// 设置页脚显示的内容
// $pdf->setFooterData(array(0,64,0), array(0,64,128));
// 设置页脚的字体
$pdf->setFooterFont(Array('dejavusans', '', '0'));
// 设置页脚距离底部的距离
$pdf->SetFooterMargin('0');
// 设置默认等宽字体
$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
// 设置行高
$pdf->setCellHeightRatio(1);
// 设置左、上、右的间距
// $pdf->SetMargins('10', '10', '10');
$pdf->SetMargins('5', '0', '5');
// 设置是否自动分页 距离底部多少距离时分页
$pdf->SetAutoPageBreak(TRUE, '0');
// 设置图像比例因子
$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
if (@file_exists(dirname(__FILE__).'/lang/eng.php')) {
require_once(dirname(__FILE__).'/lang/eng.php');
$pdf->setLanguageArray($l);
}
$pdf->setFontSubsetting(true);
$pdf->AddPage();
// 设置字体
$pdf->SetFont('stsongstdlight', '', 14, '', true);
$pdf->writeHTMLCell(0, 0, '', '', $html, 0, 1, 0, true, '', true);
$pdf->Output($fileName.'.pdf', 'I');
}
各项设置看需求。
坑
调试模式问题
调试模式下汇出现乱码,所有调试的时候可能会问题,部署到生成环境或者直接关闭调试就可以了。
背景图片问题
tcpdf对html代码的解析并不完全,我遇到的主要问题是背景图片不解析问题,导致我中间浪费了不少前端调试时间。这个问题来自库本身,其他小伙伴有空可以试试其他库。