Python uses the img2pdf library to batch convert images to PDF files

Python uses the img2pdf library to batch convert images to PDF files

import os #导入os库
import time #导入时间库生成时间戳
import img2pdf #导入img2pdf库, 安装命令:pip install img2pdf
localtime = time.localtime() #获取本地时间
timesign = time.strftime("%Y%m%d%H%M%S", localtime) #格式化时间为 202209031212 
print(time.strftime("%Y%m%d%H%M%S", localtime)) #打印格式化时间
imgpath = 'imgs'  #设置图片文件夹
try:
    with open('PDF' + timesign + '.pdf', 'wb+') as f:   #创建以二进制读写模式 ‘PDF‘’加时间戳的PDF文件
        imgs =[] #创建图片路径保存列表
        for fname in os.listdir(imgpath): #遍历图片文件夹里面的文件
            if not fname.endswith('.jpg'): #遍历文件格式为jpg的图片文件
                continue
            path = os.path.join(imgpath, fname) #读取图片文件路径
            if os.path.isdir(path):
                continue
            imgs.append(path)  #添加图片路径到imgs列表
        f.write(img2pdf.convert(imgs)) #转换imgs列表里面所有图片为一个PDF文件
        print("文件保存至outout.pdf") #打印PDF转换成功
except OSError as err:
    print("OS error: {0}".format(err))  #打印转换出错

Guess you like

Origin blog.csdn.net/weixin_40071463/article/details/126682789