php批量生成pdf 并且下载
首先通过循环批量生成PDF 这里用到的是mpdf 这个插件。
然后就是php自带的zip类 ZipArchive
以下下thinkphp代码实现批量生成pdf 然后压缩成zip 给浏览器下载。
public function download_many() { $ids = I("ids"); $orders = M("Order")->where([ 'id' => ['in',$ids], ])->select(); $category = M("Category")->getField("id,name,type",true); foreach($orders as $order){ $this->assign("order", $order); $cominfo = M("Users")->where("id={$order['company_id']}")->field("user_nicename,mobile,user_email,linkman,en_name")->find(); $this->assign("cominfo", $cominfo); $labname = M("Users")->where("id={$order['lab_id']}")->getField("user_nicename"); $this->assign("labname", $labname); $standard = $category[$order['cate_id']]; $this->assign("standard", $standard); $body = $this->fetch("pdf"); $head = $this->fetch("pdf_header"); $foot = $this->fetch("pdf_footer"); //$this->display(); Vendor('mpdf.mpdf'); //设置中文编码 //function mPDF($mode='',$format='A4',$default_font_size=0,$default_font='',$mgl=15,$mgr=15,$mgt=16,$mgb=16,$mgh=9,$mgf=9, $orientation='P') { $mpdf = new \mPDF('zh-CN/utf-8', 'A4', 0, '宋体', 10, 10, 25, 15, 5, 5); $mpdf->SetDisplayMode('fullpage'); //$mpdf->SetWatermarkText('中国水印',0.1); $strContent = $body; //$mpdf->showWatermarkText = true; if ($head) { $mpdf->SetHTMLHeader($head); } if ($foot) { $mpdf->SetHTMLFooter($foot); } $stylesheet = file_get_contents(APP_PATH . '/../public/css/pdf.css'); $mpdf->WriteHTML($stylesheet, 1); //$mpdf->AddPage('','','1','i','on'); $mpdf->WriteHTML($strContent); $outName = './data/upload/'.$order['order_num'] . ".pdf"; $mpdf->Output($outName, 'f'); $path_data[]=$outName; } //压缩包文件名称 $filename = "./data/upload/批量下载合同".date("YmdHis").".zip"; //$filename = "contracts.zip"; //压缩文件夹 $zip= new ZipArchive(); if($zip->open($filename, ZipArchive::CREATE)=== TRUE) { foreach ($path_data as $item){ $zip -> addFile($item,basename($item)); } $zip->close(); header("Cache-Control: max-age=0"); header("Content-Description: File Transfer"); header('Content-disposition: attachment; filename=' . basename($filename)); // 文件名 header("Content-Type: application/zip"); // zip格式的 header("Content-Transfer-Encoding: binary"); // 告诉浏览器,这是二进制文件 header('Content-Length: ' . filesize($filename)); // 告诉浏览器,文件大小 @readfile($filename);//输出文件; // 删除服务器上的压缩包 unlink($filename); foreach ($path_data as $item){ unlink('./data/upload/' .basename($item)); } }else{ $this->error('下载失败!'); } exit; }