1:安装
由于本项目使用的是laravel5.5.*版本,所以直接:
composer require tecnickcom/tcpdf
安装执行完之后,会在vendor出现tecnickcom文件夹。
2:控制器中引入:
不需要注册服务提供器,直接在控制器中使用
use TCPDF;
use TCPDF_FONTS;(如果不需要使用addTTFfont() 则不需要加载)
3:代码中就可以
//$pdf = new TCPDF();
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
$fontname = TCPDF_FONTS::addTTFfont('font/Droid_Sans_Fallback.ttf', 'TrueTypeUnicode', '', 32);
//$pdf->SetCreator('网站');
//$pdf->SetAuthor('网站');
//$pdf->SetTitle('TCPDF示例');
//$pdf->SetSubject('TCPDF示');
//$pdf->SetKeywords('TCPDF, PDF, PHP');
//设置间距
//$pdf->SetHeaderData('/img/download_logo.png', 300, 'www.znnwine.com', PDF_HEADER_STRING,array(0,64,255), array(0,64,128));
//$pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN)); //设置页头字体
//去掉默认的页头页脚。比如那个横线
$pdf->setPrintHeader(false);
$pdf->setPrintFooter(false);
// 设置页眉和页脚字体
//$pdf->setHeaderFont(['stsongstdlight', '', '10']);
//$pdf->setFooterFont(['helvetica', '', '8']);
// 设置默认等宽字体
//$pdf->SetDefaultMonospacedFont('courier');
//$pdf->Image('/img/download_logo.png', 15, 140, 75, 113, 'PNG', 'http://www.tcpdf.org', '', true, 150, '', false, false, 1, false, false, false);
$pdf->SetMargins(15, 15, 15);//页面间隔
$pdf->SetHeaderMargin(5);//页眉top间隔
$pdf->SetFooterMargin(10);//页脚bottom间隔
//设置分页
$pdf->SetAutoPageBreak(true, 25);
//设置字体 stsongstdlight支持中文
//$pdf->SetFont('dejavusans', '', 12);
//$pdf->SetFont('stsongstdlight', '', 14);
//$pdf->SetFont('cid0cs', '', 12);
$pdf->SetFont($fontname, '', 12);
//添加一页
$pdf->AddPage();
$pdf->Ln(10);//换行符
$html = '
<div>
<img src="'.'/img/download_logo.png'.'" width="160" height="45"/>
</div>
<div style="height:30px;width:100%;"></div>
<table width="500" align="center" border="1" cellpadding="10">
<tr>
<th align="left">WINRY NAME/酒庄名称</th>
<th align="center" colspan="2">'.$order_info["winery"]["name_en"].'</th>
</tr>
<tr>
<td align="left">PO NO/采购单号</td>
<td align="center" colspan="2">'.$order_info["purchase_no"].'</td>
</tr>
<tbody>
<tr>
<th>ITEM/品名</th>
<th>Specification/规格</th>
<th>QUANTITY(Cases) /数量(箱)</th>
</tr>';
if(!empty($order_info['subs'])){
foreach ($order_info['subs'] as $k => $v){
$html.='<tr>
<td align="center">'.$v['wine_name_en'].'</td>
<td align="center">'.$v['bottles_per_box'].' x '.$v['capacity'].'ml'.'</td>
<td align="center">'.$v['num'].'</td>
</tr>';
}
}
$html.='</tbody>
<tr>
<td align="center">托盘数</td>
<td align="center" colspan="2">TOTAL</td>
</tr>
</table>
';
$pdf->writeHTML($html, true, false, true, false, '');
//输出PDF
$pdf->Output($order_info["winery"]["name_en"].'.pdf', 'D');//I输出、D下载
注释:由于tcpdf虽然对中文也支持,但是当中英文同时出现的时候,对中文兼容性比较好,但是英文状态下,会出现一些字体问题,所以,引入的字体库:
font/Droid_Sans_Fallback.ttf
//只需要放在项目根目录中public/font目录中即可,代码中引入路径,这样就实现了中英文都可以正常显示。这个字体库直接网上下载一份就可以。
效果展示:
在使用搜索的过程中,发现不止这一种pdf扩展包,包括laravel框架自带的pdf扩展包就有两种,当然也可以使用其他的扩展包进行开发。