LoginSignup
11
11

More than 5 years have passed since last update.

WeasyPrint で PDF を出力する

Last updated at Posted at 2017-09-11

はじめに

PDF を出力するためのライブラリとしては、個人的には wkhtmltopdf が馴染み深いです。しかし、今回たまたま WeasyPrint というライブラリを見つけたので試してみました。

インストール

$ pip install weasyprint

使用例

次の HTML を PDF に変換します。せっかくなので、PDF 文書っぽく二列表示に。

quanon/magica.html

なお、文章は Wikipedia » 魔法少女まどか☆マギカ より引用しました。

01.png

そして 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

でました :tada:

出力された PDF がこちらです。

スクリーンショット 2017-09-11 22.46.36.png

気軽に使えるし、ドキュメントも充実しているしで、今後も使っていきたいです :sparkling_heart:

おまけ: 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

参考

WeasyPrint

CSS

11
11
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
11