php html转为pdf文件,php使用wkhtmltopdf实现html转pdf
項目中有需求將html頁面實時轉(zhuǎn)為pdf并提供下載。經(jīng)過各種查找比對,最終使用了wkhtmltopdf工具來實現(xiàn)。
wkhtmltopdf,可以很方便的將輸入的url渲染并打印成pdf文件。當(dāng)然也有一些坑需要踩。特別提出,wkhtmltopdf渲染不支持ES6語法,意味著使用ES6語法編寫的頁面可能會報錯而無法打印或出現(xiàn)排版問題。
先貼一個我的使用代碼段,具體的再講
$filename = "xxx.pdf";
$url = "http://www.xxx.com/"
$save_url = "/tmp/".$filename;
$shell = "xvfb-run --auto-servernum wkhtmltopdf --no-stop-slow-scripts --window-status ready '$url' $save_url";
$process = shell_exec($shell);
if(file_exists($save_url)){
//pdf文件存在,轉(zhuǎn)換成功。
}else{
//pdf文件不存在,轉(zhuǎn)換錯誤。
}
要使用wkhtmltopdf,首先自然是要安裝它。我使用的是ubuntu server-16.04,所以就直接使用apt安裝了。因為是server版的ubuntu,沒有桌面環(huán)境,同時也需要安裝xvfb,為wkhtmltopdf提供一個虛擬屏幕。否則會無法渲染而報錯。
sudo apt-get update
sudo apt-get install xvfb
sudo apt-get install wkhtmltopdf
wkhtmltopdf的使用就是在bash中使用(注意引號)
wkhtmltopdf ‘網(wǎng)址’ ‘保存地址’
即可。
在前面加上xvfb-run –auto-servernum,可以在無桌面環(huán)境的linux中使用
xvfb-run --auto-servernum wkhtmltopdf --no-stop-slow-scripts --window-status ready '$url' $save_url
參數(shù):
–no-stop-slow-scripts 表示不停止計算緩慢的js腳本
–window-status ready 表示wkhtmltopdf將會等到渲染的網(wǎng)頁window-status變?yōu)閞eady后再進行打印(可在頁面中通過運行js代碼window.status=”ready”進行狀態(tài)匹配)
–debug-javascript 可以輸出js的控制臺信息,進行debug
總結(jié)
以上是生活随笔為你收集整理的php html转为pdf文件,php使用wkhtmltopdf实现html转pdf的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: freetds php mssql 中文
- 下一篇: 行车记录仪设置php,【必看】如何正确的