Skip to content

Instantly share code, notes, and snippets.

@pulsejet
Created October 10, 2018 11:51
Show Gist options
  • Save pulsejet/7de5939d3808359c160e37a745bad954 to your computer and use it in GitHub Desktop.
Save pulsejet/7de5939d3808359c160e37a745bad954 to your computer and use it in GitHub Desktop.
Convert all JPEG files in a directory to PDF
"""Converts all JPEG files in INPUT DIR to full size PDF.
requirements.txt
========================================
fpdf==1.7.2
========================================
Requires python 3.5+
"""
import os
from fpdf import FPDF
# ============== Configuration ============= #
INPUT_DIR = './images/'
ORIENTATION = 'P'
FORMAT = 'A4'
OUTPUT_DIR = './pdf/'
# ========================================== #
# Get all files in path
images = [f for f in os.listdir(INPUT_DIR) if os.path.isfile(os.path.join(INPUT_DIR, f))]
# Create output directory
if not os.path.exists(OUTPUT_DIR):
os.makedirs(OUTPUT_DIR)
# Iterate over all files
for image in images:
# Make a new PDF
pdf = FPDF(orientation=ORIENTATION, format=FORMAT)
# Add the image to the PDF
pdf.add_page()
pdf.image(INPUT_DIR + image, 0, 0, 210, 297)
# Change extension of output
pdf.output(OUTPUT_DIR + image.lower().replace('.jpg', '.pdf'), 'F')
# Show a friendly message
print('Converted', image)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment