import os
from PIL import Image
from PyPDF2 import PdfFileMerger
# 防止字符串乱码
os.environ['NLS_LANG'] = 'SIMPLIFIED CHINESE_CHINA.UTF8'
class AllImagesToPdf:
def __init__(self):
self.imgs_path = "imgs" # 将所有的图片放到此文件夹中
self.pdfs_path = "pdfs" # 将所有转换后的pdf放到此文件夹
def imgs_to_pdfs(self):
imgs_path = self.imgs_path
imgs_list = os.listdir(imgs_path)
for img_name in imgs_list:
if "jpg" in img_name or "png" in img_name:
read_img_path = os.path.join(self.imgs_path,img_name)
obj_img = Image.open(read_img_path) # 打开指定路径下的图片
save_img_path = os.path.join(self.pdfs_path,img_name.split(".")[0]+".pdf") # 拼接pdf的路径和名称
obj_img.save(save_img_path) # 保存为pdf
def pdfs_to_pdf(self):
pdfs_path = self.pdfs_path
pdfs_list = os.listdir(pdfs_path)
pdfs_path_list = []
for pdf_name in pdfs_list:
if pdf_name.endswith(".pdf"):
pdfs_path_list.append(os.path.join(self.pdfs_path,pdf_name))
# print(pdfs_path_list)
pdf_merger = PdfFileMerger() # 创建PdfFileMerger对象,用来合并pdf文件
for file_path in pdfs_path_list:
pdf_merger.append(file_path)
pdf_merger.write("mergerd.pdf") # 使用write方法将所有pdf文件写入到一个文件
def run(self):
self.imgs_to_pdfs() # 把大量的图片一个个转为pdf
print("批量图片转批量pdf完毕")
self.pdfs_to_pdf() # 把大量的pdf合并到一个pdf
print("批量pdf转pdf完毕")
if __name__ == '__main__':
itp = AllImagesToPdf()
itp.run()
————————————————
原文链接:https://blog.csdn.net/weixin_44346972/article/details/127263455
标签:img,批量,python,self,pdfs,imgs,pdf,path From: https://www.cnblogs.com/panlifeng/p/17739690.html