PHP之 将html源代码生成pdf并下载

代码

SetDefaultMonospacedFont('courier');
        $number="HIECO-MBR-";
        // 设置间距
        $pdf->SetMargins(15, 15, 15);//页面间隔
        $pdf->SetFooterMargin(10);//页脚bottom间隔

    $pdf->setPrintHeader(false);
    $pdf->setPrintFooter(false);

    //设置字体 stsongstdlight支持中文
    $pdf->SetFont('stsongstdlight', '', 14);

    //第一页
    $pdf->AddPage();
    //输出PDF
    if($html!=''){
        $html="
\n \n \n \n \n \n
\n

采购合同

\n
\n \n
"; } $pdf->writeHTMLCell(150, 0, 40, 65, $html, 0, 1, 0, true, '', true); ob_clean(); $dir = "/uploads/organization/" . date('Ymd'); if (!file_exists($dir)) { mkdir($dir, 0777, true); // 如果保存目录不存在就创建新目录 } $filename = $dir .'/'. date('YmdHis') . '.pdf'; $pdf->Output($_SERVER['DOCUMENT_ROOT'].'/'.$filename, 'F'); if($is_dowon){ $this->download_new('/'.$filename,'合同.pdf'); }else{ return $filename; } } public function download_new($url="",$filename='') { if($url ==''){ $url= request()->get('url'); } if($filename==''){ $filename= request()->get('filename'); } $info = pathinfo($url); if($filename){ $info['filename']=$filename.'_'.$info['filename']; } $isurl=0; if(!empty($_GET['isurl'])){ $info['filename']=$filename; $isurl=1; } $this-> download_file( ROOT_PATH.$url,$info['filename'],$isurl); } /** * 下载文件 * @param string $file * 被下载文件的路径 * @param string $name * 用户看到的文件名 */ private function download_file($file,$name='',$isurl=0){ $fileName = $name ? $name : pathinfo($file,PATHINFO_FILENAME); $filePath = realpath($file); $fp = fopen($filePath,'rb'); if(!$filePath || !$fp){ header('HTTP/1.1 404 Not Found'); echo "Error: 404 Not Found.(server file path error)"; exit; } if($isurl==0){ $fileName = $fileName .'.'. pathinfo($filePath,PATHINFO_EXTENSION); }else{ // $fileName = $fileName.'.xlsx' ; $fileName = $fileName .'.'. pathinfo($filePath,PATHINFO_EXTENSION); } $encoded_filename = urlencode($fileName); $encoded_filename = str_replace("+", "%20", $encoded_filename); header('HTTP/1.1 200 OK'); header( "Pragma: public" ); header( "Expires: 0" ); header("Content-type: application/octet-stream"); header("Content-Length: ".filesize($filePath)); header("Accept-Ranges: bytes"); header("Accept-Length: ".filesize($filePath)); $ua = $_SERVER["HTTP_USER_AGENT"]; if (preg_match("/MSIE/", $ua)) { header('Content-Disposition: attachment; filename="' . $encoded_filename . '"'); } else if (preg_match("/Firefox/", $ua)) { header('Content-Disposition: attachment; filename*="utf8\'\'' . $fileName . '"'); } else { header('Content-Disposition: attachment; filename="' . $fileName . '"'); } // ob_end_clean(); <--有些情况可能需要调用此函数 // 输出文件内容 fpassthru($fp); exit; } }

你可能感兴趣的:(php,html,pdf)