はじめに
PDF を出力するためのライブラリとしては、個人的には wkhtmltopdf が馴染み深いです。しかし、今回たまたま WeasyPrint というライブラリを見つけたので試してみました。
インストール
$ pip install weasyprint
使用例
次の HTML を PDF に変換します。せっかくなので、PDF 文書っぽく二列表示に。
なお、文章は Wikipedia » 魔法少女まどか☆マギカ より引用しました。
そして pdf.css という PDF 専用の CSS も用意します。
pdf.css
@page {
  margin: 8.0rem 2.0rem;
  font-family: YuMincho, "Hiragino Mincho ProN", serif;
  @top-center {
    content: "魔法少女まどか☆マギカ";
    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 magica.html magica.pdf -s pdf.css
でました ![]()
出力された PDF がこちらです。
気軽に使えるし、ドキュメントも充実しているしで、今後も使っていきたいです ![]()
おまけ: Docker 対応
Dockerfile
FROM python:3.6.2
RUN apt-get update \
 && apt-get install -y \
      python-lxml \
      fontconfig \
      libcairo2 \
      libpango1.0-0 \
      libgdk-pixbuf2.0-0 \
      libffi-dev \
      shared-mime-info \
      unzip \
 && apt-get autoremove \
 && apt-get clean
WORKDIR /opt
ENV WEASYPRINT_VERSION 0.40
RUN pip install weasyprint==$WEASYPRINT_VERSION
ADD https://noto-website.storage.googleapis.com/pkgs/NotoSerifCJKjp-hinted.zip .
RUN unzip -d noto NotoSerifCJKjp-hinted.zip \
 && mkdir -p /usr/share/fonts/opentype \
 && mv -fv noto /usr/share/fonts/opentype/noto \
 && rm -rfv NotoSerifCJKjp-hinted.zip \
 && fc-cache -fv
docker-compose.yml
version: '3.3'
services:
  weasyprint:
    build: .
    volumes:
      - .:/opt/data-volume
    working_dir: /opt/data-volume
    entrypoint:
      - weasyprint
    command:
      - -h
$ docker-compose run weasyprint magica.html magica.pdf -s pdf.css

