以下为封装的tp5的操作类方法,转图片需要安装imagemagick的扩展
<?php
namespace crepdf;
class Pdf
{
//xhtml转pdf
public static function pdf($file_name, $flag = 'd', $html = '<h1 style="color:red">这里可以随便写一句话~</h1>')
{
require_once('../extend/TCPDF/tcpdf.php');
$pdf = new \TCPDF(PDF_PAGE_ORIENTATION, "px", PDF_PAGE_FORMAT, true, 'UTF-8', false);
// 设置打印模式
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor('DaZe');
$pdf->SetTitle($file_name);
// $pdf->SetSubject('TCPDF Tutorial');
// $pdf->SetKeywords('TCPDF, PDF, example, test, guide');
// 是否显示页眉
$pdf->setPrintHeader(false);
// 设置页眉显示的内容
// $pdf->SetHeaderData('http://www.baidu.com', 60, 'cainiao.cn', '', 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('5', '5', '5');
// 设置是否自动分页 距离底部多少距离时分页
$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');
$pdf->setLanguageArray($l);
}
$pdf->setFontSubsetting(true);
$pdf->AddPage();
// 设置字体
$pdf->SetFont('stsongstdlight', '', 10, '', true);
// $pdf->writeHTMLCell(0, 0, '', '', $html, 0, 1, 0, true, '', true);
$pdf->writeHTML($html);
// dump($file_name);
// die;
if ($flag == "s") {
$res = $pdf->Output($file_name, 'S'); //保存
$Path = './pdf/';
if (!is_dir($Path)) {
@mkdir($Path, 0777, true);
}
$file = $Path . date('YmdHis', time()) . mt_rand('99', '999') . '.pdf';
// dump($file);die;
file_put_contents($file, $res);
$file = substr($file, 1);
return $file;
} else {
$file = date('YmdHis', time()) . mt_rand('99', '999') . '.pdf';
$res = $pdf->Output($file, 'D'); //直接下载
}
}
//pdf转图片
public static function pdf2png($PDF = './pdf/TestFile.pdf', $file_name = '', $floder = "")
{
if (!extension_loaded('imagick')) {
return false;
}
if (!file_exists($PDF)) {
return 1;
return false;
}
$IM = new \imagick();
$IM->setResolution(150, 150);
$IM->setCompressionQuality(100);
// dump($PDF);die;
$IM->readImage($PDF);
$Path = '';
if ($floder) $Path .= "$floder";
if (!is_dir($Path)) {
@mkdir($Path, 0777, true);
}
foreach ($IM as $Key => $Var) {
$Var->setImageFormat('png');
$Filename = $Path . '/' . $file_name . '.png';
// $Filename = $Path.'/aa.png';
if ($Var->writeImage($Filename) == true) {
$Return[] = $Filename;
}
}
unlink($PDF);
return $Return;
}
}
还要安装ghostscript的扩展 以下为linux服务器centOS的安装方法sudo yum install ghostscript