Created
April 9, 2017 07:45
-
-
Save pansapiens/19c633726a7cfc023413fe38226fa94e to your computer and use it in GitHub Desktop.
Convert a directory of images or scanned pages to a PDF
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# Creates a PDF from a set of images in a directory (one image per page, alphanumeric ordering). | |
# | |
# Usage: | |
# python images2pdf.py output_file.pdf | |
# | |
# Requires: | |
# pip install fpdf | |
from fpdf import FPDF | |
from PIL import Image | |
import glob | |
import os | |
from os import path | |
import sys | |
def create_pdf(pdf_filename, image_filenames, working_directory=None): | |
if working_directory is None: | |
working_directory = os.getcwd() | |
cover = Image.open(path.join(working_directory, str(image_filenames[0]))) | |
width, height = cover.size | |
pdf = FPDF(unit="pt", format=[width, height]) | |
for page in image_filenames: | |
pdf.add_page() | |
pdf.image(path.join(working_directory, str(page)), 0, 0) | |
pdf.output(path.join(working_directory, pdf_filename), "F") | |
if __name__ == '__main__': | |
image_extensions = ['png', 'jpg', 'jpeg'] | |
images = [] | |
for ext in image_extensions: | |
images.extend(glob.glob('*.%s' % ext)) | |
images = sorted(images) | |
create_pdf(sys.argv[1], images) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment