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

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

[Mac] コマンドラインでウェブページを PDF に変換する:wkhtmltopdf – with a Christian Wife
https://wacw.cf/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 というファイル名で以下のようなスタイルを設定すると、フォントをを游ゴシック体にしたり、フッターにページ番号を記入できる。

body {
  margin: 8.0rem 2.0rem;
  font-family: 'YuGothic', sans-serif !important;
}

@page {
  margin: 8.0rem 2.0rem;

  @top-center {
  content: "test";
  vertical-align: bottom;
  font-size: 1.2rem;
  border-bottom: 0.1rem solid;
  margin-bottom: 1.2rem;
  }

  @bottom-right {
  content: counter(page) " / " counter(pages);
  }
}

このスタイルで 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