2
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

PythonでPDFをラスタライズする

Last updated at Posted at 2020-01-19

背景

特定の環境で、ベクター形式のPDFの描画がうまく行かないことがあった。
この問題を回避するため、ベクターではなくJPEGなどにラスタライズされたPDFとして変換して保存したい。

方法

Python3を用いると容易に実現できた。

事前準備

コード

main.py
import pdf2image as p
from PIL import Image
import sys

# ラスタライズ時の解像度
# 値が大きいほど綺麗だが時間がかかる(ある値で綺麗さはサチる)
DPI = 300

# 最終出力PDFの画像縦幅
HEIGHT = 1200

pdfpath = sys.argv[1]
images = p.convert_from_path(pdfpath, dpi=DPI)

def resize(image):
    r = HEIGHT / image.height
    width = int(image.width * r)
    return image.resize((width, HEIGHT), Image.LANCZOS)

images = list(map(resize, images))
images = list(map(lambda image: image.convert('RGB'), images))

images[0].save('output.pdf',save_all=True, append_images=images[1:])

まずは解像度高めにラスタライズし、その後ほしい解像度の画像へ縮小すると画質が良好になる。

使い方

変換したいPDFファイル (hoge.pdf) が実行フォルダにあるとする。

$ python main.py hoge.pdf

上記コマンドを実行すると、実行したディレクトリに output.pdf が生成される。

2
6
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
2
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?