php使用wkhtmltopdf將html轉爲pdf

首先需要安裝wkhtmltopdf插件。安裝參考鏈接:https://mp.csdn.net/postedit/103162085

生成pdf選擇wkhtmltopdf的原因是,wkhtmltopdf對樣式能夠很好的體現。mpdf對樣式的呈現不足。

php後臺代碼調用wkhtmltopdf,將靜態html轉爲pdf。

//生成pdf的函數,$html爲需要寫入到pdf文件裏的字符串
function generatePdf($html){
//將字符串$html裏的內容寫入到$filename_path文件裏,該文件爲html
file_put_contents("{$filename_path}.html", $html);
//wkhtmltopdf將生成的html文件轉爲相應的pdf
shell_exec("wkhtmltopdf -q {$filename_path}.html {$filename_path}.pdf");
//判定指定的路徑下是否存在相應的pdf
if(file_exists("{$filename_path}.pdf")){
       //設置header信息
       header("Content-type:application/pdf");
       //設置下載的文件名稱
       header("Content-Disposition:attachment;filename={$filename}.pdf");
        //火狐瀏覽器下文件名設定
       if (stripos($_SERVER["HTTP_USER_AGENT"], 'Firefox')) {
           header("Content-Disposition: attachment;filename*={$filename}.pdf");
       }
        //safari瀏覽器默認不支持漢字名,所以safari下文件名設爲拼音
       if (stripos($_SERVER["HTTP_USER_AGENT"], 'Macintosh')) {
            //通過一個漢字轉爲拼音的共同函數,獲取漢字相應的拼音,參考鏈接:https://mp.csdn.net/postedit
            $pinyin = new Pinyin();
            $name_py = $pinyin->getpy($name,true,true) . '\'s ';
            $filename = '2-' . $name_py;
             header("Content-Disposition: attachment; filename={$filename}.pdf");
            }
            //下載文件到本地
            echo file_get_contents("{$filename_path}.pdf");
            //刪除下載Pdf產生在服務器上的臨時文件
            unlink("{$filename_path}.pdf");
            unlink("{$filename_path}.html");
        }
        exit;
}

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章