Today, a friend asked about a tool for archiving a bunch of TIFF files by putting them all into a single PDF file. This seemed like a good entry point for creating a simple, yet useful, tool with python.
As an added challenge, he didn’t have administrator access to his windows PC, so we came up with a solution to create a python development environment in windows without using any administrative privileges. Then we used the environment to develop a simple python application to bundle tiff files into a single PDF. And just to add a little icing to the cake, we used some python build tools to create a standalone exe file.
Step 1. Setting Up the Development Environment
- Download zip file of all the necessary files https://goo.gl/l9KCrE
- This includes the python installation file, pycharm IDE, sample images, etc.
- Extract zip file (let’s say this was extracted to C:\Users\drwho\Downloads\pybundle
- Create a virtual drive for that directory (let’s say T:) and install python:
- open command line window, type the following:
subst T: C:\Users\drwho\Downloads\pybundle
T:
install_python.bat
Python is now installed with pip and the package img2pdf. You can run this command to combine the sample images with the img2pdf command line tool that comes with the package:
Scripts\img2pdf.exe -o ../output.pdf ../images/dir_1/dir_2/dir_3/CCITT_2.TIF ../images/dir_a/dir_b/dir_c/CCITT_1.TIF ../images/dir_x/dir_y/dir_z/CCITT_3.TIF
Step 2. Using img2pdf library to create tool
Turns out that with the img2pdf library, it is a very few lines of code that are required to create the command line tool. Here is the resulting code that creates a simple GUI with Tk and allows you to specify a root directory to search for files:
import img2pdf, sys, os, time
if len(sys.argv) > 1:
image_directory = sys.argv[1]
print "I'm looking for TIFs in ", image_directory
else:
print "Please tell me the directory to look in"
sys.exit()
image_files = []
for root, dirs, files in os.walk(image_directory):
for file in files:
if file.endswith(".tif") or file.endswith(".TIF"):
print"Discovered this TIF: ", os.path.join(root, file)
image_files.append(os.path.join(root, file))
if image_files:
output_file = time.strftime("%Y%m%d-%H%M%S") + ".pdf"
print "Putting all TIFs into ", output_file
pdf_bytes = img2pdf.convert(image_files)
file = open(output_file,"wb")
file.write(pdf_bytes)
else:
print "Couldn't find any TIFs"
For reference, here is what the sample input images directory structure looks like:
Step 3. Create an exe file using pyinstaller
This is as simple as running (once pyinstaller is installed):
pyinstaller --onefile --windowed tif2pdf.py #assuming the above python file is named "tif2pdf.py"
Summary
I found this to be a simple use case that serves a real-world need, but is also relatively easy to implement. I hope this can be useful to others, especially for anyone who is just starting to learn python.