Created
May 12, 2015 01:14
-
-
Save jbolda/3926cab1465a249d1830 to your computer and use it in GitHub Desktop.
Create docx with table of all pictures in folders
This file contains hidden or 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
from docx import Document | |
from docx.shared import Inches | |
from PIL import Image | |
import glob | |
import datetime | |
import os | |
import sys | |
size = 688, 516 | |
print "(preprocess) Making thumbnails" | |
for infile in glob.glob("./*/*.jpg"): | |
file, ext = os.path.splitext(infile) | |
im = Image.open(infile) | |
im.thumbnail(size, Image.ANTIALIAS) | |
im.save(file + ".thumbnail.jpg", "JPEG", quality=95) | |
document = Document('CLIENT Pics.docx') | |
# Set section margins | |
section = document.sections[0] | |
section.left_margin = Inches(0.95) | |
section.right_margin = Inches(0.5) | |
section.top_margin = Inches(1.12) | |
section.bottom_margin = Inches(1.0) | |
section.header_distance = Inches(0.19) | |
section.footer_distance = Inches(0.5) | |
# Grab all pictures in folder and drop in list | |
print "(1 of 4) Grabbing picture names" | |
recordset = glob.glob('./*/*.thumbnail.jpg') | |
# Add table, specify width, can we specify height? | |
table = document.add_table(rows=len(recordset), cols=2, style='None') | |
table.allow_autofit = False | |
table.cell(0, 0).width = Inches(4.0) | |
table.cell(0, 1).width = Inches(3.0) | |
# Iterate through picture list and add pictures to each of the table cells | |
print "(2 of 4) Pasting pictures in table" | |
for idx, item in enumerate(recordset): | |
paragraph = table.cell(idx, 0).paragraphs[0] | |
run = paragraph.add_run() | |
run.add_picture(item, width=Inches(3.85)) | |
table.cell(idx, 1).text = item | |
# Iterate through picture list and delete picture thumbnails | |
print "(3 of 4) Pasting pictures in table" | |
for item in recordset: | |
try: | |
os.remove(item) | |
except: | |
print "Unexpected error:", sys.exec_info()[0] | |
wait = input('Press enter to continue.') | |
# Save! | |
print "(4 of 4) All done! Saving the file and cleaning up" | |
timestamp = datetime.datetime.now().strftime("%Y-%m-%d %I.%M%p") | |
document.save(timestamp + ' CLIENT Pics.docx') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment