LoginSignup
19
18

More than 5 years have passed since last update.

ImageMagickでPDFを画像に変換する

Last updated at Posted at 2015-07-03

ImageMagickでPDFを扱うための設定

ImageMagickでPDFを扱う場合、GSをインストールしないといけないとのこと。

OSXでbrew使ってる時は、brew install gsで大丈夫。

サンプリング解像度の設定が必須

densityオプションでdpiを設定をしないと、すごく画像が粗くなる。
元PDF設定や、出力したい画像のサイズに合わせて設定する。

参考にしたサイト
http://icepotato.cocolog-nifty.com/blog/2013/06/imagemagickpdfw.html

PythonのPillowではPDFの読み込みができない

PythonのPillowだとPDFは、書き込みのみで読み込みは対応してないみたい。

フォルダ丸ごとPDFをPNGに変換するコード

サンプリング解像度が300dpi、余白のトリミング付きで、同じフォルダにPNG画像を書き出してます。

ImageMagickをインストールしてれば動くはず。

# coding: utf-8

import os
import os.path
import fnmatch
import subprocess


def execute(root_path):
    for dirpath, _, filenames in os.walk(root_path):
        for filename in filenames:
            if fnmatch.fnmatch(filename, u"*.pdf"):
                org_path = os.path.join(dirpath, filename)
                png_path = org_path.replace(".pdf", ".png")

                print "convert {0} to {1}".format(org_path, png_path)

                if subprocess.call(["convert", "-density", "300", "-trim", org_path, png_path]) != 0:
                    print "failed: {0}".format(org_path)

if __name__ == '__main__':
    root_path = raw_input("target folder path> ")
    execute(root_path)
19
18
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
19
18