使用TP5将数据生成为PDF文件
2016-08-03 14:34:28
一:引入tcpdf
/ThinkPHP/Library/Vendor/Tcpdf
把tcpdf文件整个目录拷到自己的项目中;
二:函数
创建 /Application/Common/Common/function.php
/**
- 生成pdf
- @param string
h
t
m
l
需
要
生
成
的
内
容
∗
/
f
u
n
c
t
i
o
n
p
d
f
(
html 需要生成的内容 */ function pdf(
html需要生成的内容∗/functionpdf(html=‘
hello word
’){
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(‘5’);
// 是否显示页脚
$pdf->setPrintFooter(true);
// 设置页脚显示的内容
$pdf->setFooterData(array(0,64,0), array(0,64,128));
// 设置页脚的字体
$pdf->setFooterFont(Array(‘dejavusans’, ‘’, ‘10’));
// 设置页脚距离底部的距离
$pdf->SetFooterMargin(‘10’);
// 设置默认等宽字体
$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
// 设置行高
$pdf->setCellHeightRatio(1);
// 设置左、上、右的间距
$pdf->SetMargins(‘10’, ‘10’, ‘10’);
// 设置是否自动分页 距离底部多少距离时分页
$pdf->SetAutoPageBreak(TRUE, ‘15’);
// 设置图像比例因子
$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
if (@file_exists(dirname(FILE).’/lang/eng.php’)) {
require_once(dirname(FILE).’/lang/eng.php’);
p d f − > s e t L a n g u a g e A r r a y ( pdf->setLanguageArray( 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(‘example_001.pdf’, ‘I’);
}
三 控制器代码
namespace app\index\controller;
use app\model\Admin;
use think\Controller;
class Index extends Controller
{
public function pdfTest()
{
$res = db(‘admin’)->select();
$pdfHtml = ‘’;
foreach ($res as $k=>$v){
$pdfHtml.=implode(’.’,$v);
}
pdf($pdfHtml);die();
return $this->fetch();
}
}