まじめにゆいがどくそん

仕事関連の真面目な記事が満載です、多分。

wkhtmltopdf インストール (Ubuntu 10.4 LTS)

※以下、Ubuntu 10.4 LTSで検証

wkhtmltopdfを使えばCSSでバリバリにクールなデザインを施したHTMLを手軽にPDFにできます。

wkhtmltopdfとは?

簡単に言うと、WebkitQtによるHTML→PDFコンバータです。
Safarichromeで使用されているレンダリングエンジンWebkitレンダリングした結果をPDFに変換するため、ブラウザで見たままのイメージでPDFにすることができます。
画面のレイアウトやテーブル行の背景色などをJavaScriptで動的に変更するサイトも変換可能です。

以下、wkhtmltopdfプロジェクトサイトより引用

Description

Simple shell utility to convert html to pdf using the webkit rendering engine, and qt.

Introduction

Searching the web, I have found several command line tools that allow you to convert a HTML-document to a PDF-document, however they all seem to use their own, and rather incomplete rendering engine, resulting in poor quality. Recently QT 4.4 was released with a WebKit widget (WebKit is the engine of Apples Safari, which is a fork of the KDE KHtml), and making a good tool became very easy.


インストールは簡単です。

sudo apt-get install wkhtmltopdf

使い方も簡単。
wkhtmltopdf

wkhtmltopdf http://www.google.co.jp/ google.pdf
wkhtmltopdf /home/hoge/sample.html sample.pdf


単一のサイトやHTMLファイルをそのままPDFにするならこれで十分ですが、目次の生成やオリジナルHTMLファイルによるヘッダおよびフッタの付加、複数HTMLのPDF化などといった、ちょっと凝ったことをしたいなら一手間かける必要があります。


※下記インストール手順はダウンロードしたwkhtmltopdfソース内に含まれている README_WKHTMLTOPDF に記載されています。

インストール手順

既存のwkhtmltopdfを削除

sudo apt-get --purge remove wkhtmltopdf


必須ライブラリをインストール

sudo apt-get build-dep libqt4-gui libqt4-network libqt4-webkit
sudo apt-get install openssl build-essential xorg git-core git-doc libssl-dev


Qtをコンパイル&インストール
※相当時間がかかります。環境によっては半日以上かかるかも。。。
wkhtmktopdf用Qt取得

git clone git://gitorious.org/+wkhtml2pdf/qt/wkhtmltopdf-qt.git wkhtmltopdf-qt

wkhtmktopdf用Qtコンパイル&インストール

cd wkhtmltopdf-qt
./configure -nomake tools,examples,demos,docs,translations -opensource -prefix ../wkqt
make -j3
make install
cd ..


wkhtmltopdfをコンパイル&インストール

git clone git://github.com/antialize/wkhtmltopdf.git wkhtmltopdf
cd wkhtmltopdf
../wkqt/bin/qmake
make -j3
make install

wkhtmltoimage

ちなみに、wkhtmltoimageという姉妹ツールがあります。
読んで字のごとく、wkhtmltopdfと同様の使用方法で、Webページのサムネイル画像を簡単に作成できるツールです。
wkhtmltopdfのプロジェクトサイトよりダウンロードできます。