Python batch converts pictures to pdf

Code to convert and merge images in Word documents to PDF. The code first reads the pictures in the Word document from the specified path, and then saves the picture files to the specified folder path_convert. Then, the program traverses the folders where the pictures are saved, converts all picture files into PDF files with the same name, and saves them in the folder where the original picture files are located. Finally, the program combines all PDF files in the same folder into one file named output.pdf.

It should be noted that the PyPDF2 library needs to be installed in the code, because the library provides a PdfMerger class that can be used to merge PDF files. If the library is not installed, you can open a command prompt or terminal and use the following command to install it:

Full code:

# -*- coding: utf-8 -*-
"""
Spyder Editor

This is a temporary script file.
"""

from PIL import Image
import os
from os.path import join
from pathlib import Path
from PyPDF2 import PdfMerger


path = "C:/Users/ypzhao/Desktop/word/"
path_convert = "C:/Users/ypzhao/Desktop/pict/"

for i in os.listdir(path):
    file_name,file_suffix = i.split(".")
    if file_suffix != "jpg":
        im = Image.open(path+f"{
      
      i}")
        im.save(path_convert+f"{
      
      file_name}"+".jpg")       
    else:
        pass   

def convert_to_pdf(file_path):
    # 打开图片文件
    img = Image.open(file_path)
    # 将图片转换为 PDF,并保存到同名文件
    pdf_path = os.path.splitext(file_path)[0] + ".pdf"
    img.save(pdf_path, "PDF", resolution=300.0)

def main():
    # 指定图片所在目录
    image_dir = Path("C:/Users/ypzhao/Desktop/pict/")
    # 遍历目录下的所有文件
    for file_path in image_dir.glob("*"):
        # 如果是图片文件,则转换为 PDF
        if file_path.suffix.lower() in (".jpg", ".jpeg", ".png", ".bmp"):
            convert_to_pdf(file_path)
    # 将所有 PDF 合并成一个文件
    merger = PdfMerger()
    for file_path in image_dir.glob("*.pdf"):
        merger.append(str(file_path))
    merger.write("output.pdf")

if __name__ == "__main__":
    main()

operation result:
insert image description here

Guess you like

Origin blog.csdn.net/m0_58857684/article/details/130849482