在使用php開發(fā)一些項目時, 經(jīng)常會用到php直接生成pdf文件, 開源類 tcpdf是一個很不錯的選擇, 具體原因, 這里就不多說了
大之前的使用過程中都是沒有問題的, 但是在ThinkPHP5中引用直接輸出到瀏覽器, 會顯示亂碼, 搜便百度, 也沒有找到一個答案, 這里經(jīng)過測試找到了解決方案[不要問我為什么, 這里只是解決方法].
打開tcpdf.php文件, 第7643行, 增加 die() 或者 exit() 語句
即 function Output函數(shù)中當(dāng)?shù)诙€參數(shù)是I時, 為直接輸出到瀏覽器, 這里已經(jīng)不需要返回什么信息, 可以直接exit();

使用方法如下:
import('tcpdf.tcpdf', EXTEND_PATH); //extend/tcpdf/tcpdf.php
//實例化
$html='<h1 style="color:red">我們是共產(chǎn)主義接班人</h1>
<table border="1"><tr><td>莊子</td></tr></table>';
$pdf = new \Tcpdf(PDF_PAGE_ORIENTATION, PDF_UNIT,
PDF_PAGE_FORMAT, true, 'UTF-8', false);
// 設(shè)置打印模式
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor('zhuangzi');
$pdf->SetTitle('莊子測試tcpdf.php在thinkphp5下');
$pdf->SetSubject('莊子到此一游');
$pdf->SetKeywords('TCPDF, PDF, example, test, guide');
// 是否顯示頁眉
$pdf->setPrintHeader(true);
// 設(shè)置頁眉顯示的內(nèi)容
$pdf->SetHeaderData('', 60, 'www.ncyateng.com', '南昌雅騰',
array(0,64,255), array(0,64,128));
// 設(shè)置頁眉字體
$pdf->setHeaderFont(Array('stsongstdlight', '', '12'));
// 頁眉距離頂部的距離
$pdf->SetHeaderMargin('5');
// 是否顯示頁腳
$pdf->setPrintFooter(true);
// 設(shè)置頁腳顯示的內(nèi)容
$pdf->setFooterData(array(0,64,0), array(0,64,128));
// 設(shè)置頁腳的字體
$pdf->setFooterFont(Array('dejavusans', '', '10'));
// 設(shè)置頁腳距離底部的距離
$pdf->SetFooterMargin('10');
// 設(shè)置默認(rèn)等寬字體
$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
// 設(shè)置行高
$pdf->setCellHeightRatio(1);
// 設(shè)置左、上、右的間距
$pdf->SetMargins('10', '10', '10');
// 設(shè)置是否自動分頁 距離底部多少距離時分頁
$pdf->SetAutoPageBreak(TRUE, '15');
// 設(shè)置圖像比例因子
$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();
// 設(shè)置字體
$pdf->SetFont('stsongstdlight', '', 14, '', true);
$pdf->writeHTMLCell(0, 0, '', '', $html, 0, 1, 0, true, '', true);
$pdf->Output(config("filepath").DS.'AA.pdf', 'F'); //生成PDF文件到某地
$pdf->Output('AA.pdf', 'I'); //輸入AA.pdf到瀏覽器輸出
}
