上節講到配置wkhtmltopdf,這節講下如何批量操做php
首先講下wkhtmltopdf如何使用css
直接命令行輸入:html
wkhtmltopdf http://www.baidu.com/ baidu.pdfmysql
php使用sql
<?phpshell
shell_exec('wkhtmltopdf http://www.baidu.com/ baidu.pdf') //注:中間兩個空格隔開fetch
?>ui
當前路徑下會生成一個PDF文件:spa
批量操做:命令行
<?php
header("Content-type:text/html;charset=utf-8");
$host='127.0.0.1';
$user='root';
$password='***';
$dbName= "***";
$db=new MySQLi($host,$user,$password,$dbName);
mysqli_set_charset($db,'utf8');
if ($db->connect_error){
die("鏈接失敗:".$db->connect_error);
}
$sql = '***';
$result = $db->query($sql);//返回結果集對象
$n = $result->fetch_all();
echo '<pre>';
$s = 0;
foreach ($n as $v){
$s ++;
//判斷是否生成
$file = "test_pdf/".$v[0].".pdf";
if(file_exists($file)){
continue;
}
$path="test_html/".$v[0].".html"; //命名方式能夠id命名,惟一便可
$tem = 'cq/template.html'; //模板HTML文件
$fp=fopen($tem,"r");
//讀取模板中內容
$str=fread($fp,filesize($tem));
//替換內容
$str=str_replace("{indentity_code}",$v[0],$str);
$str=str_replace("{name}",$v[1],$str);
***
fclose($fp);
//寫入方式打開路徑
$handle=fopen($path,"w");
//把剛纔替換的內容寫進生成的HTML文件
fwrite($handle,$str);
fclose($handle);
//存PDF
shell_exec("wkhtmltopdf localhost/test_html/".$v[0].".html "."test_pdf/".$v[0].".pdf");
echo $v[0].'<br/>';
//檢測生成PDF
// if($s == 2 ){
// break;
// }
}
經過循環方式執行:
<!DOCTYPE HTML>
<meta http-equiv="content-type" content="text/html;charset=utf-8"> <!-- 注:這句加上防止HTML亂碼,致使導出PDF亂碼 -->
<html>
<body>
<link rel="stylesheet" type="text/css" href="../ks.css">
<div class="box">
<span style="width: 30%">姓名:{name}</span>
</div>
</body>
</html>
注: css文件要和生成html文件引入方式同樣,這樣確保生成後的html文件能在本地訪問
以上方式基本上能實現批量數據導出PDF,若有不懂,或者過程當中遇到別的問題,亂碼等問題加羣討論