Skip to content

Instantly share code, notes, and snippets.

@Belval
Last active July 24, 2019 14:35
Show Gist options
  • Save Belval/e35b9f65676de1cf06308e96b03be353 to your computer and use it in GitHub Desktop.
Save Belval/e35b9f65676de1cf06308e96b03be353 to your computer and use it in GitHub Desktop.
Takes a directory of images, create pages with 6 images per page.
import os
import re
import sys
from subprocess import Popen
from PIL import Image
from pdf2image import convert_from_path
def pdfs_to_images(in_dir, out_dir):
for i, f in enumerate(os.listdir(in_dir)):
convert_from_path(os.path.join(in_dir, f), fmt='png', output_folder=out_dir, output_file=str(i))
def images_to_tiles(in_dir, out_dir):
stacks = []
files = os.listdir(in_dir)
files.sort(key=lambda s: int(s.split('_')[0]) * 1000 + int(s.split('-')[-1][:-4]))
for i in range(0, len(files) // 6 + 1):
stacks.append(files[i * 6:(i+1) * 6])
max_width = 1700 // 2
max_height = 2200 // 3
for pn, s in enumerate(stacks):
page = Image.new("RGB", (1700, 2200), (255, 255, 255))
for i, f in enumerate(s):
img = Image.open(os.path.join(out_dir, f))
img.thumbnail((1700 // 2, 2200 // 3))
x = (i % 2) * max_width
y = (i % 3) * max_height
w, h = img.size
page.paste(img, (x, y, x + w, y + h))
page.save(os.path.join(out_dir, f"{pn}.png"))
def tiles_to_pdf(in_dir, out_dir):
p = Popen(f"convert $(ls -1 -v {in_dir}) {out_dir}/out.pdf")
p.communicate()
def main(args):
in_dir = args[2]
out_dir = args[3]
if args[1] == "1":
pdfs_to_images(in_dir, out_dir)
elif args[1] == "2":
images_to_tiles(in_dir, out_dir)
elif args[1] == "3":
tiles_to_pdf(in_dir, out_dir)
if __name__=='__main__':
main(sys.argv)
@Belval
Copy link
Author

Belval commented Jul 24, 2019

To convert to PDF: convert $(ls -1 -v *.png) out.pdf

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment