import os
import img2pdf
def filterFileName(imagesPath: str, formatName: str) -> list:
"""
获取指定文件夹下所有的文件名称, 并筛选出指定格式的图片.
Args:
imagesPath: 图片文件夹路径
formatName: 需要筛选的图片格式名
Returns: 返回指定格式的图片名称组成的 List
"""
nameArr = []
for name in os.listdir(imagesPath):
if (name.split(".")[-1] == formatName):
nameArr.append(fr"{imagesPath}\{name}")
return nameArr
def main(imagesPath: str, formatName="jpg", pageSize=25) -> None:
"""
Args:
imagesPath: 图片文件夹路径
formatName: 需要筛选的图片格式名
pageSize: 组成一个 PDF 的图片数量
"""
allImgList = filterFileName(imagesPath, formatName)
cnt = 1
while (len(allImgList) > 0):
imgList = allImgList[:pageSize]
with open(fr"D:\SamplePDF\第{cnt}.pdf", "wb") as f:
print(f"已转录第 {cnt} 本.")
cnt += 1
f.write(img2pdf.convert(imgList))
allImgList = allImgList[pageSize:]
if __name__ == '__main__':
# 参数含义依次为: 图片文件夹路径, 需要筛选的格式, 组成一个 PDF 的图片数量
main(r"D:\SampleImage", "jpg", 25)