108 字
1 分钟
利用PHP将HTML页面生成PDF文档
标签(空格分隔): php特殊处理
使用TCPDF第三方类库进行生成
githup下载地址:https://github.com/tecnickcom/tcpdf
官方下载地址:http://sourceforge.net/projects/tcpdf/
核心代码:
public static function writePdf($content) { $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false); $pdf->SetCreator(PDF_CREATOR);
$pdf->SetHeaderData("logo.jpg", 70, 'wanglibao Agreement' . '', ''); $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED); $pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT); $pdf->SetHeaderMargin(PDF_MARGIN_HEADER); $pdf->SetFooterMargin(PDF_MARGIN_FOOTER); $pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM); $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO); $pdf->AddPage(); $pdf->setPageMark(); $pdf->SetFont('stsongstdlight', '', 13); $title = <<<EOD<h2>标题</h2>EOD;
$pdf->writeHTML($content, true, false, false, false, '');// $pdf->writeHTML($content, true, 0, true, true);// $pdf->writeHTMLCell(0, 0, '', '', $content, 0, 1, 0, true, 'C', true); $pdf->lastPage(); $pdf->Output(date('Y-m-d') . '.pdf', 'I');}汉子出现乱码解决办法:
-
设置
$pdf->setHeaderFont(array(PDF_FONT_NAME_MAIN,'',PDF_FONT_SIZE_MAIN);其中PDF_FONT_NAME_MAIN就是设置头部的字体编码。 将PDF_FONT_NAME_MAIN设置为msungstdlight。页面中的字体:在$pdf->writeHtml();或者$pdf->Cell();等之前设置$pdf->SetFont(msungstdlight,'', 字体大小)。 -
汉字不出现乱码的代码如下:
<?php//引入tcpdf文件 require_once('./TCPDF-master/tcpdf.php');//实例化$pdf = new TCPDF('P', 'mm', 'A4', true, 'UTF-8', false);// 设置文档信息$pdf->SetCreator('哈喽');$pdf->SetAuthor('作者');$pdf->SetTitle('哈哈哈哈哈哈');$pdf->SetSubject('TCPDF Tutorial');$pdf->SetKeywords('TCPDF, PDF, PHP');// 设置页眉和页脚信息$pdf->SetHeaderData('logo.png', 10, 'kkkkkk', '就是做个PDF', array(0,64,255), array(0,64,128));$pdf->setFooterData(array(0,64,0), array(0,64,128));// 设置页眉和页脚字体$pdf->setHeaderFont(Array('stsongstdlight', '', '10'));$pdf->setFooterFont(Array('helvetica', '', '8'));// 设置默认等宽字体$pdf->SetDefaultMonospacedFont('courier');// 设置间距$pdf->SetMargins(15, 27, 15);$pdf->SetHeaderMargin(5);$pdf->SetFooterMargin(10);// 设置分页$pdf->SetAutoPageBreak(TRUE, 25);// set image scale factor$pdf->setImageScale(1.25);// set default font subsetting mode$pdf->setFontSubsetting(true);//设置字体$pdf->SetFont('stsongstdlight', '', 14);$pdf->AddPage();$str1 = " <table border=\"1\"> <tr> <td>哈哈</td> <td>123</td> <td>123</td> </tr> </table>";$pdf->WriteHTML($str1,'', 0, 'L', true, 0, false, false, 0);//输出PDF$pdf->Output('t.pdf', 'I');部分信息可能已经过时
