刚开始合并没有顺序,合并成了一个指定文件了,但排序是乱的。
import os
from PIL import Imagedef folder_to_pdf(folder_path, output_path):image_paths = []for file_name in os.listdir(folder_path):if file_name.endswith(('jpg', 'jpeg', 'png')):image_paths.append(os.path.join(folder_path, file_name))if image_paths:images = [Image.open(image).convert('RGB') for image in sorted(image_paths)]images[0].save(output_path, save_all=True, append_images=images[1:])print(f"已将文件夹 {folder_path} 中的图片合并为 PDF 文件 {output_path}")else:print("文件夹中没有找到图片文件")# 示例
folder_to_pdf('images_folder', 'output_folder.pdf')
第二版优化后的
实际效果还是达到了,需要的可以玩玩。
from PIL import Imagedef images_to_pdf(image_paths, output_path):images = [Image.open(image).convert('RGB') for image in image_paths]images[0].save(output_path, save_all=True, append_images=images[1:])print(f"已将多张图片合并为 PDF 文件 {output_path}")def generate_filenames(start, end):return [f"{i}.jpg" for i in range(start, end + 1)]# 这里修改数值按照从1开始累加的方式排序
start = 1
end = 1000
image_paths = generate_filenames(start, end)
images_to_pdf(image_paths, 'output2024.pdf')