【Python】WebページやHTMLをPDF出力する


大量のPDFをプログラムでバッチ出力したい。
けど、帳票ツールを買うお金はない…。

そうだ、HTMLをPythonスクリプトで組んでPDF変換しよう!
ということでやり方を調べたメモ。

wkhtmltopdfのインストール

まずは、wkhtmltopdfというツールをインストールします。

ダウンロードページ

インストールしたら インストールフォルダ\wkhtmltopdf\bin にパスを通すと、コマンドラインでWebページをPDF化することができます。

>wkhtmltopdf https://www.google.com/ google.pdf
Loading pages (1/6)
Counting pages (2/6)
Resolving links (4/6)
Loading headers and footers (5/6)
Printing pages (6/6)
Done

pdfkitを使ってPythonで出力する

pdfkitというPythonライブラリを使います。
これは内部でwkhtmltopdfを使用しています。

pip install pdfkit
import pdfkit

# 指定できる出力オプション https://wkhtmltopdf.org/usage/wkhtmltopdf.txt
options = {
    'page-size': 'A4',
    'margin-top': '0.1in',
    'margin-right': '0.1in',
    'margin-bottom': '0.1in',
    'margin-left': '0.1in',
    'encoding': "UTF-8",
    'no-outline': None,
    'disable-smart-shrinking': '',
}

# WebページをPDF出力
pdfkit.from_url('https://google.com', 'google.pdf', options=options)

"""
パスを通さなかった場合はプログラム内でパスを設定する必要がある。
config_path = r'C:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe'
config = pdfkit.configuration(wkhtmltopdf=config_path)
pdfkit.from_url('https://google.com', 'google.pdf', options=options, configuration=config)
"""

# HTML/CSSファイルをPDF出力
pdfkit.from_file('index.html', 'index.pdf', css='style.css', options=options)

# テキストをPDF出力
pdfkit.from_string('<html><body><h1>It works!</h1></body></html>', 'apache.pdf', options=options)