Tako can fry!

とほほ・・・

複数画像を PDF ファイルに

もしかして python で PDF ファイルを操作できるライブラリがあるんじゃないかと探してみたらあったので試してみた次第。
ライブラリには PIL と reportlab が必要で、MacPorts を使ってインストール。
python2.7 を使っているので、インストールはこんな感じ。

$ sudo port install py27-pil
$ sudo port install py27-reportlab

1 ページにつき 1 枚の画像を貼り付けるというコードを書いてみた。
これだけで PDF を出力できてしまうから楽やねえ。
人に見られると困る画像を扱うケースを考慮して、パスワードも設定できるようにしてますよ。

#!/usr/bin/env python
# coding: UTF-8

import Image

from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import A4
from reportlab.lib import pdfencrypt
from reportlab.lib.units import mm
from reportlab.lib.units import cm

from optparse import OptionParser

# -----------------------------------------------------------------------------
def drawImage(c, img_file):
    img = Image.open(img_file)
    img_w, img_h = img.size

    page_w, page_h = A4

    if (float(img_w) / img_h) < (float(page_w) / page_h):
        dest_h = page_h
        dest_w = img_w * (page_h / img_h)
        x = (page_w - dest_w) / 2
        y = 0
    else:
        dest_w = page_w
        dest_h = img_h * (page_w / img_w)
        y = (page_h - dest_h) / 2
        x = 0

    c.drawInlineImage(img_file, x, y, width=dest_w, height=dest_h)

# -----------------------------------------------------------------------------
if __name__ == '__main__':

    parser = OptionParser('usage: %prog (options) [image files]')
    parser.add_option("-o", "--output", type="string",
                      dest="output", default="a.pdf",
                      metavar="FILE",
                      help="specify output FILE (default: a.pdf)")
    parser.add_option("-p", "--password", type="string",
                      dest="password", metavar="PASSWORD",
                      help="specify PASSWORD")

    (options, args) = parser.parse_args()

    if len(args) < 1:
        parser.error("need to specify image file(s)")

    out_file = options.output

    if options.password is not None:
        enc = pdfencrypt.StandardEncryption(options.password, canPrint=0, canCopy=0)
        c = canvas.Canvas(out_file, pagesize=A4, encrypt=enc)
    else:
        c = canvas.Canvas(out_file, pagesize=A4)

    print "write images to %s" % out_file

    page_no = 1
    for img_file in args:
        print "..page %d" % page_no
        drawImage(c, img_file)
        c.showPage()
        page_no += 1

    c.save()

    print "finish"

自分の最近の落書きを出力してみた結果。