Python Multiple pictures merged into a reference example of pdf

  • 2021-11-13 08:00:48
  • OfStack

Directory procedure
Photographing
Python operation library used
Python Traverses the folder to get the picture, rotates the picture display direction and compresses the pixels
Whole code
Whole code
Package the script as exe
Installing PyInstaller
Packaging script
Summarize

Process

The most important thing to get a requirement is to split the large task into small modules and break them one by one.

Photographing

In this step, all the pages are photographed first. It should be noted that they should be photographed according to the page number of the book, because the following sorting is sorted according to the file name, and the file name of the photo is basically generated according to the time. If the photo is messed up, the page number in the generated pdf will also be messed up.

Python operation library used

The best thing about Python is that there are a large number of third-party libraries that can help us quickly realize the method we want. After searching for two libraries, PyFPDF and img2pdf, we chose img2pdf to fulfill our requirements pip install img2pdf

Python Traversing Folders for 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)

It should be noted that if the file name of the picture is pure number and the number of digits is not 1, the sorting will be 10 after 1 instead of 2, and one sorting is needed. If it is a file taken by mobile phone, there is no such problem. files. sort (key = lambda x: int (x [:-4]))

Rotate the display direction of the picture and compress the pixels

Sometimes the pictures taken by mobile phones are horizontal, so it is necessary to change them to vertical ones
When using rotate to rotate the direction, you should pay attention to adding the parameter expand=True, otherwise there will be black edges.

The pixels of the photos of mobile phones are too high, and some need to be compressed to ensure that the final pdf is of moderate size.


    img = Image.open(path)    
    if img.size[0] > img.size[1]:
        im_rotate = img.rotate(90, expand=True)
        size = (int(im_rotate.size[0] / 3), int(im_rotate.size[1] / 3))
        im_rotate = im_rotate.resize(size)
        im_rotate.save(savepath, quality=95)
    else:
        size = (int(img.size[0] / 3), int(img.size[1] / 3))
        img = img.resize(size)
        img.save(savepath, quality=95)

Whole code

There are many things to consider when writing a script. For convenience, you need to change various parameters to allow users to enter. For example, the path where the picture folder is located, 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(" The path where the picture folder is located does not exist! ")
saveflag = False
while not saveflag:
    savedirname = input(" Please enter the path of the destination picture folder ( For example d:/wlzcool2) : ")
    saveflag = os.path.exists(savedirname)
    if not saveflag:
        print(" The path where the picture folder is located does not exist! ")
        automakedir = input(" Do you want to automatically create corresponding folders? ( Yes Y/ No N):")
        if automakedir.strip().upper() == "Y":
            os.makedirs(savedirname)
            saveflag = True
files = os.listdir(dirname)
reductionFactor = int(input(" Please enter the aspect compression ratio ( For example 3):"))
if reductionFactor <= 0:
    reductionFactor = 3
isConvertBlack = input(" 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[0] > img.size[1]:
        im_rotate = img.rotate(90, expand=True)
        size = (int(im_rotate.size[0] / reductionFactor), int(im_rotate.size[1] / 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[0] / reductionFactor), int(img.size[1] / reductionFactor))
        img = img.resize(size)
        if isConvertBlack:
            img = img.convert("L")
        img.save(savePath, quality=95)
filename = input(" Please enter an output file name ( For example: 1 Chapter ) : ")
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))

Whole code

There are many things to consider when writing a script. For convenience, you need to change various parameters to allow users to enter. For example, the path where the picture folder is located, 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(" The path where the picture folder is located does not exist! ")
saveflag = False
while not saveflag:
    savedirname = input(" Please enter the path of the destination picture folder ( For example d:/wlzcool2) : ")
    saveflag = os.path.exists(savedirname)
    if not saveflag:
        print(" The path where the picture folder is located does not exist! ")
        automakedir = input(" Do you want to automatically create corresponding folders? ( Yes Y/ No N):")
        if automakedir.strip().upper() == "Y":
            os.makedirs(savedirname)
            saveflag = True
files = os.listdir(dirname)
reductionFactor = int(input(" Please enter the aspect compression ratio ( For example 3):"))
if reductionFactor <= 0:
    reductionFactor = 3
isConvertBlack = input(" 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[0] > img.size[1]:
        im_rotate = img.rotate(90, expand=True)
        size = (int(im_rotate.size[0] / reductionFactor), int(im_rotate.size[1] / 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[0] / reductionFactor), int(img.size[1] / reductionFactor))
        img = img.resize(size)
        if isConvertBlack:
            img = img.convert("L")
        img.save(savePath, quality=95)
filename = input(" Please enter an output file name ( For example: 1 Chapter ) : ")
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))

Package the script as exe

Not all computers have an Python environment, so we need to package the script into exe for easy use on any one computer. Packaging scripts using PyInstaller

Installing PyInstaller

pip install pyinstaller

Packaging script

Execute the following command in cmd in the path where the script is located


pyinstaller -F yourprogram.py

Summarize

Life is too short, I use Python, with the help of the powerful third-party library, we only need a little time to develop a very interesting small function.

The above is the Python images merged into a reference example of pdf details, more about Python images merged into pdf information please pay attention to other related articles on this site!


Related articles: