twitter youtube tumblr flickr rss mail

category: computer

[Mac] コマンドラインでウェブページを PDF に変換する:WeasyPrint


本記事のタイトルとURL をコピーする

wkhtmltopdf を使って、コマンドラインからウェブページを PDF に変換する方法について書いた。

[Mac] コマンドラインでウェブページを PDF に変換する:wkhtmltopdf – with a Christian Wife
https://blog.withachristianwife.com/2020/04/15/convert-webpage-to-pdf-via-commandline/

もう一つ試したのが WeasyPrint だ。

Kozea/WeasyPrint: WeasyPrint converts web documents (HTML with CSS, SVG, …) to PDF.
https://github.com/Kozea/WeasyPrint/

インストールは以下。

環境:macOS Catalina Version 10.15.3

$ brew install python3 cairo pango gdk-pixbuf libffi
$ pip3 install WeasyPrint

参考:
Installing — WeasyPrint 51 documentation
https://weasyprint.readthedocs.io/en/stable/install.html

ウェブページを PDF に変換するには以下のコマンド。デフォルトで A4 サイズとなる。

$ weasyprint https://google.com google.pdf

しかし、日本語のページだと文字化けしてしまった。そこでスタイルを指定したら文字化けが発生しなかった。

$ weasyprint https://google.com google.pdf -s <(echo 'body { font-family: sans-serif !important }')

WeasyPrint で PDF を作成して分かるのが、wkhtmltopdf と比べて美しくないこと・・・。

一応細かいスタイルを設定できるが、そのためにはスタイルシートを別に作成する。例えば、pdf.css というファイル名で以下のようなスタイルを設定すると、フォントをを游ゴシック体にしたり、フッターにページ番号を記入できる。

このスタイルで PDF を作成するには以下のコマンドを実行。

$ weasyprint https://google.com google.pdf -s pdf.css

ただ、いい具合にスタイルを調整するのは大変そう。やはりデフォルトで綺麗な PDF ができる wkhtmltopdf が楽だ。

参考:
Tutorial — WeasyPrint 51 documentation
https://weasyprint.readthedocs.io/en/stable/tutorial.html

WeasyPrint で PDF を出力する - Qiita
https://qiita.com/QUANON/items/727433f6c39a51fd4052


書籍