您的位置:首页 > 理论基础 > 计算机网络

php 利用gd库及tcpdf 自动多图片生成pdf

2016-11-15 14:37 801 查看
因为公司取证的原因,需要把很多的资质图片文件打包生成pdf,所以用php写了一个脚本来自动生成文件。

代码如下:

<?php  

//设置超时事件。防止超时异常

ini_set("max_execution_time",18000);

//设置内存使用,防止大数据量超内存

ini_set("memory_limit",'-1');

header("Content-type:text/html;charset=utf-8");

require_once('TCPDF/tcpdf.php');

require_once('TCPDF/config/tcpdf_config.php');

//tcpdf 创建一个pdf对象

$pdf = new TCPDF('P', 'mm', 'A4', true, 'UTF-8', false); 

$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);

// set margins

$pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);

$pdf->SetHeaderMargin(PDF_MARGIN_HEADER);

$pdf->SetFooterMargin(PDF_MARGIN_FOOTER);

// set auto page breaks

$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);

// set image scale factor

$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);

// set some language-dependent strings (optional)

if (@file_exists(dirname(__FILE__).'/lang/eng.php')) {
require_once(dirname(__FILE__).'/lang/eng.php');
$pdf->setLanguageArray($l);

}

$hostdir='1\3'; //要操作的目录名
$filesnames = scandir($hostdir);//获取全部文件名
sort($filesnames,SORT_NUMERIC);//文件名排序,根据数字从小到大排列

//遍历文件名
foreach ($filesnames as $name) {
if(strstr($name,'jpg')){//如果是图片则添加到pdf中
// Image($file, $x='', $y='', $w=0, $h=0, $type='', $link='', $align='', $resize=false, $dpi=300, $palign='', $ismask=false, $imgmask=false, $border=0, $fitbox=false, $hidden=false, $fitonpage=false)
$pdf->AddPage();//添加一个页面
$filename = $hostdir.'\\'.$name;//拼接文件路径

                        //gd库操作  读取图片
$source = imagecreatefromjpeg($filename);

                       //gd库操作  旋转90度
$rotate = imagerotate($source, 90, 0);

                      //gd库操作  生成旋转后的文件放入别的目录中
imagejpeg($rotate,$hostdir.'\\123\\'.$name.'_1.jpg');

                        //tcpdf操作  添加图片到pdf中
$pdf->Image($hostdir.'\\123\\'.$name.'_1.jpg', 15, 26, 210, 297, 'JPG', '', 'center', true, 300);

}
}

$pdf->Output('1.pdf', 'I'); //输出pdf文件

//删除生成的目录及文件

function delDirAndFile( $dirName )

{
if ( $handle = opendir( "$dirName" ) ) {
while ( false !== ( $item = readdir( $handle ) ) ) {
if ( $item != "." && $item != ".." ) {
if ( is_dir( "$dirName/$item" ) ) {
delDirAndFile( "$dirName/$item" );
} else {
if( unlink( "$dirName/$item" ) )echo "成功删除文件: $dirName/$item<br />n";
}
}
}
closedir( $handle );
if( rmdir( $dirName ) )echo "成功删除目录: $dirName<br />n";
}
}

delDirAndFile($hostdir.'\\123');
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  php pdf gd库