wkhtmltopdf 是一個開源、簡單而有效的指令行 shell 程式,它可以将任何 html (網頁)轉換為 pdf 文檔或圖像(jpg、png 等)。
wkhtmltopdf 是用 c++ 編寫的,并在 gnu/gpl (通用公共許可證)下釋出。它使用 webkit 渲染引擎将 html 頁面轉換為 pdf 文檔且不會丢失頁面的品質。這是一個用于實時建立和存儲網頁快照的非常有用且可信賴的解決方案。
wkhtmltopdf 的功能
開源并且跨平台。
使用 webkit 引擎将任意 html 網頁轉換為 pdf 檔案。
添加頁眉和頁腳的選項
目錄生成 (toc) 選項。
提供批量模式轉換。
通過綁定 libwkhtmltox 來支援 php 或 python。
在本文中,我們将介紹如何在 linux 系統下使用 tar 包來安裝 wkhtmltopdf。
安裝 evince (pdf 浏覽器)
讓我們在 linux 系統中安裝 evince (一個 pdf 閱讀器)來浏覽 pdf 檔案。
$ sudo yum install evince [rhel/centos and fedora]
$ sudo dnf install evince [on fedora 22+ versions]
$ sudo apt-get install evince [on debian/ubuntu systems]
下載下傳 wkhtmltopdf 源碼檔案
使用 wget 指令根據你的 linux 架構來下載下傳 wkhtmltopdf 源碼檔案,或者你也可以在 wkhtmltopdf 下載下傳頁下載下傳最新的版本(目前最新的穩定版是 0.12.4)
在 64 位 linux 系統中:
$ wget http://download.gna.org/wkhtmltopdf/0.12/0.12.4/wkhtmltox-0.12.4_linux-generic-amd64.tar.xz
在 32 位 linux 系統中:
$ wget http://download.gna.org/wkhtmltopdf/0.12/0.12.4/wkhtmltox-0.12.4_linux-generic-i386.tar.xz
在 linux 中安裝 wkhtmltopdf
使用 tar 指令解壓檔案到目前目錄中。
------ on 64-bit linux os ------
$ sudo tar -xvf wkhtmltox-0.12.4_linux-generic-amd64.tar.xz
------ on 32-bit linux os ------
$ sudo tar -xvzf wkhtmltox-0.12.4_linux-generic-i386.tar.xz
為了能從任意路徑執行程式,将 wkhtmltopdf 安裝到 /usr/bin 目錄下。
$ sudo cp wkhtmltox/bin/wkhtmltopdf /usr/bin/
如何使用 wkhtmltopdf?
我們會看到如何将遠端的 html 頁面轉換成 pdf 檔案、驗證資訊、使用 evince 在 gnome 桌面中浏覽建立的檔案。
将 html 網頁轉成 pdf 檔案
要将任意 html 頁面轉換成 pdf,運作下面的指令。它會在目前目錄下将頁面轉換成 10-sudo-configurations.pdf。
# wkhtmltopdf http://www.tecmint.com/sudoers-configurations-for-setting-sudo-in-linux/ 10-sudo-configurations.pdf
示例輸出:
loading pages (1/6)
counting pages (2/6)
resolving links (4/6)
loading headers and footers (5/6)
printing pages (6/6)
done
浏覽生成的 pdf 檔案
為了驗證建立的檔案,使用下面的指令。
$ file 10-sudo-configurations.pdf
10-sudo-configurations.pdf: pdf document, version 1.4
浏覽生成的 pdf 檔案細節
要浏覽生成的檔案資訊,運作下面的指令。
$ pdfinfo 10-sudo-configurations.pdf
title: 10 useful sudoers configurations for setting 'sudo' in linux
creator: wkhtmltopdf 0.12.4
producer: qt 4.8.7
creationdate: sat jan 28 13:02:58 2017
tagged: no
userproperties: no
suspects: no
form: none
javascript: no
pages: 13
encrypted: no
page size: 595 x 842 pts (a4)
page rot: 0
file size: 697827 bytes
optimized: no
pdf version: 1.4
浏覽建立的檔案
在桌面中使用 evince 檢視最新生成的 pdf 檔案。
$ evince 10-sudo-configurations.pdf
示例截圖:
在我的 linux mint 17 中看起來很棒。
在 pdf 中浏覽網頁
給 pdf 建立頁面的 目錄(table of content )(toc)
要建立一個 pdf 檔案的目錄,使用 toc 選項。
$ wkhtmltopdf toc http://www.tecmint.com/sudoers-configurations-for-setting-sudo-in-linux/ 10-sudo-configurations.pdf
loading toc (3/6)
要檢視已建立檔案的 toc,再次使用 evince。
看一下下面的圖。它上看去比上面的更好。
在 pdf 中建立網頁的目錄
wkhtmltopdf 選項及使用
更多關于 wkhtmltopdf 的使用及選項,使用下面的幫助指令。它會顯示出所有可用的選項。
$ wkhtmltopdf --help
作者:ravi saive
來源:51cto