Skip to content

Instantly share code, notes, and snippets.

@tako2
Created June 14, 2021 15:33
Show Gist options
  • Save tako2/6fdfe42b423387de2aa0ad5633537ab1 to your computer and use it in GitHub Desktop.
Save tako2/6fdfe42b423387de2aa0ad5633537ab1 to your computer and use it in GitHub Desktop.
画像ファイルを PDF に出力
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from PIL 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
import sys
import glob
from natsort import natsorted
# -----------------------------------------------------------------------------
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.print_help()
exit()
in_files = []
for arg in args:
if '*' in arg:
in_files.extend(natsorted(glob.glob(arg)))
else:
in_files.append(arg)
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", out_file, file=sys.stderr)
page_no = 1
for img_file in in_files:
print(img_file, "to page", page_no, file=sys.stderr)
drawImage(c, img_file)
c.showPage()
page_no += 1
c.save()
print("finished", file=sys.stderr)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment