日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > php >内容正文

php

php html转为pdf文件,php使用wkhtmltopdf实现html转pdf

發布時間:2024/4/19 php 48 豆豆
生活随笔 收集整理的這篇文章主要介紹了 php html转为pdf文件,php使用wkhtmltopdf实现html转pdf 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

項目中有需求將html頁面實時轉為pdf并提供下載。經過各種查找比對,最終使用了wkhtmltopdf工具來實現。

wkhtmltopdf,可以很方便的將輸入的url渲染并打印成pdf文件。當然也有一些坑需要踩。特別提出,wkhtmltopdf渲染不支持ES6語法,意味著使用ES6語法編寫的頁面可能會報錯而無法打印或出現排版問題。

先貼一個我的使用代碼段,具體的再講

$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文件存在,轉換成功。

}else{

//pdf文件不存在,轉換錯誤。

}

要使用wkhtmltopdf,首先自然是要安裝它。我使用的是ubuntu server-16.04,所以就直接使用apt安裝了。因為是server版的ubuntu,沒有桌面環境,同時也需要安裝xvfb,為wkhtmltopdf提供一個虛擬屏幕。否則會無法渲染而報錯。

sudo apt-get update

sudo apt-get install xvfb

sudo apt-get install wkhtmltopdf

wkhtmltopdf的使用就是在bash中使用(注意引號)

wkhtmltopdf ‘網址’ ‘保存地址’

即可。

在前面加上xvfb-run –auto-servernum,可以在無桌面環境的linux中使用

xvfb-run --auto-servernum wkhtmltopdf --no-stop-slow-scripts --window-status ready '$url' $save_url

參數:

–no-stop-slow-scripts 表示不停止計算緩慢的js腳本

–window-status ready 表示wkhtmltopdf將會等到渲染的網頁window-status變為ready后再進行打印(可在頁面中通過運行js代碼window.status=”ready”進行狀態匹配)

–debug-javascript 可以輸出js的控制臺信息,進行debug

總結

以上是生活随笔為你收集整理的php html转为pdf文件,php使用wkhtmltopdf实现html转pdf的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。