利用wkhtmltopdf和PHP將HTML存成PDF

jopen 10年前發布 | 109K 次閱讀 PDF工具包 wkhtmltopdf

在PHP中生成PDF文件,可以使用 FPDFTCPDF 。但是它們只能用于創建簡單的表格,當涉及到需要將圖像添加到表中,就無法產生所需的布局。有一個強大的工具叫wkhtmltopdf就能夠實現。

Wkhtmltopdf 是一個shell工具,它使用了WebKit渲染引擎和QT,將HTML轉換為PDF格式。

安裝wkhtmltopdf

# apt-get install wkhtmltopdf

從HTML生成PDF文件的基本語法如下:

# wkhtmltopdf input-file output-file

我們可以從任何網頁生成PDF:

# wkhtmltopdf example.com example.pdf

或從本地html文件:

# wkhtmltopdf example.html example.pdf

以上命令只能在Linux box 圖形環境中使用。如果我們在一個VPS或專用服務器上生成PDF,如果我們執行該命令,我們將得到從下錯誤:

wkhtmltopdf: cannot connect to X server

為了解決這個問題,我們需要使用一個名為 xvfb 的工具。

Xvfb是一個 X 服務器,能夠運行在沒有顯示硬件和沒有物理輸入設備的機器上。它使用虛擬內存來模擬一個dumb framebuffer。

安裝 xvfb

# apt-get install xvfb

接下來,我們需要創建一個shell腳本:

xvfb-run --server-args="-screen 0, 1024x768x24" /usr/bin/wkhtmltopdf $*

然后將它保存在 /usr/bin/wkhtmltopdf.sh 下

下一步,我們將創建一個 symbolic 鏈接,這樣我們就可以執行腳本而不用編寫的完整路徑:

# ln -s /usr/bin/wkhtmltopdf.sh /usr/local/bin/wkhtmltopdf2

讓我們嘗試執行shell腳本,并看看會發生什么。

# wkhtmltopdf2 example.com example.pdf
Loading page (1/2)
Printing pages (2/2)                                               
Done

好,如果能夠正確運行。就可以用以下自定義PHP腳本來生成一個PDF文件。

//Turn on output buffering
ob_start();

echo "<html>";
echo "<head>";
echo "<link  rel='stylesheet' type='text/css'>";
echo "</head>";
echo "<body>";
echo "<p>custom HTML to PDF report</p>";
echo "</body>";
echo "</html>";

//return the contents of the output buffer
$html = ob_get_contents();
$filename = date('YmdHis');

//save the html page in tmp folder
file_put_contents("/tmp/{$filename}.html", $html);

//Clean the output buffer and turn off output buffering
ob_end_clean();

//convert HTML to PDF
shell_exec("wkhtmltopdf2 -q /tmp/{$filename}.html /tmp/{$filename}.pdf");
if(file_exists("/tmp/{$filename}.pdf")){
    header("Content-type:application/pdf");
    header("Content-Disposition:attachment;filename='{$filename}.pdf'");
    echo file_get_contents("/tmp/{$filename}.pdf");
}else{
    exit;
}

 

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!