Recently I need to organize my notes into a pdf Preservation , So we studied how to use Python The code merges all the photos taken into one pdf.
2. The process
To get a requirement, the most important thing is to split large tasks into small modules , Break one by one .
2.1 Taking pictures
The first step is to take all the pages of the book , It should be noted that the page number of the book should be taken , Because the following sort is sorted by file name , The file name of the photo is basically generated according to the time , If it's a mess , Generated at that time pdf The page numbers inside will also be out of order .
2.2 Python Operation Library
Python The best part is that there are lots of third-party libraries that can help us quickly implement the methods we want , We found two libraries ,
PyFPDF and img2pdf, We choose img2pdf To fulfill our needs
pip install img2pdf
2.3 Python Go through the folder to get pictures
dirname = "f:/wlzcool" imgs =  for fname in os.listdir(dirname): if not fname.endswith(".jpg"): continue path = os.path.join(dirname, fname) if os.path.isdir(path): continue imgs.append(path)
Note that if the file name of the image is a pure number and the number of digits is different , The order would be 1 And then 10 instead of 2, You need an extra sort of sorting of numbers , If the file is taken by mobile phone, there is no such problem .
files.sort(key=lambda x: int(x[:-4]))
2.4 Rotate the image display direction and compress pixels
Sometimes the pictures taken by the mobile phone are horizontal , It needs to be changed to vertical
use rotate When you rotate, you need to add expand=True This parameter , Otherwise, there will be black edges .
The photo pixels of the phone are too high , Some need to be compressed to ensure that the final generated pdf The size is moderate .
img = Image.open(path) if img.size > img.size: im_rotate = img.rotate(90, expand=True) size = (int(im_rotate.size / 3), int(im_rotate.size / 3)) im_rotate = im_rotate.resize(size) im_rotate.save(savepath, quality=95) else: size = (int(img.size / 3), int(img.size / 3)) img = img.resize(size) img.save(savepath, quality=95)
2.5 The overall code
There are many things to consider when writing a script , For ease of use , The parameters need to be changed to allow user input . For example, the path of the image folder , Compression ratio and so on
from PIL import Image import os import img2pdf flag = False while not flag: dirname = input(" Please enter the path of the picture folder ( for example d:/wlzcool)：") flag = os.path.exists(dirname) if not flag: print(" Image folder path does not exist ！") saveflag = False while not saveflag: savedirname = input(" Please enter the path of the destination image folder ( for example d:/wlzcool2)：") saveflag = os.path.exists(savedirname) if not saveflag: print(" Image folder path does not exist ！") automakedir = input(" Whether to create the corresponding folder automatically ？( yes Y/ no N):") if automakedir.strip().upper() == "Y": os.makedirs(savedirname) saveflag = True files = os.listdir(dirname) reductionFactor = int(input(" Please input the length width compression ratio ( for example 3):")) if reductionFactor <= 0: reductionFactor = 3 isConvertBlack = input(" Whether to output black and white version ？( yes Y/ no N):").strip().upper() == "Y" for fname in files: if not fname.endswith(".jpg"): continue path = os.path.join(dirname, fname) savePath = os.path.join(savedirname, fname) if os.path.isdir(path): continue img = Image.open(path) if img.size > img.size: im_rotate = img.rotate(90, expand=True) size = (int(im_rotate.size / reductionFactor), int(im_rotate.size / reductionFactor)) im_rotate = im_rotate.resize(size) if isConvertBlack: im_rotate = im_rotate.convert("L") im_rotate.save(savePath, quality=95) else: size = (int(img.size / reductionFactor), int(img.size / reductionFactor)) img = img.resize(size) if isConvertBlack: img = img.convert("L") img.save(savePath, quality=95) filename = input(" Please input the output file name ( for example ： Chapter one )：") with open(filename + ".pdf", "wb") as f: imgs =  files = os.listdir(savedirname) for fname in files: if not fname.endswith(".jpg"): continue path = os.path.join(savedirname, fname) if os.path.isdir(path): continue imgs.append(path) f.write(img2pdf.convert(imgs))
2.6 Package the script into exe
All computers don't have Python Environmental Science , We need to package the script as exe Easy to use on any computer .
Use PyInstaller To package scripts
2.6.1 install PyInstaller
pip install pyinstaller
2.6.2 Packaging script
In the path where the script is located cmd Execute the following command in
pyinstaller -F yourprogram.py
Life is too short , I use Python, Powerful third-party libraries can save us a lot of time to develop an interesting Python Picture merge pdf Small application of ,Python It's just cool ！