应用场景
主文件夹下有多个子文件夹分别存放有相应的png文件,png文件按名称升序。
代码
import os
from reportlab.lib.pagesizes import letter
from reportlab.platypus import SimpleDocTemplate, Image
from reportlab.lib.units import inch
from PIL import Image as PILImage # 用于获取图片尺寸
# 设置主文件夹路径
main_folder = r'C:\Users\MakiWinster\Downloads\jy'
# 遍历主文件夹
for folder_name in os.listdir(main_folder):
folder_path = os.path.join(main_folder, folder_name)
if os.path.isdir(folder_path):
# 创建PDF文件
pdf_path = os.path.join(main_folder, f"{folder_name}.pdf")
doc = SimpleDocTemplate(pdf_path, pagesize=letter)
elements = []
# 遍历子文件夹下的所有PNG文件
png_files = [f for f in os.listdir(folder_path) if f.endswith('.PNG')]
if png_files:
for filename in png_files:
image_path = os.path.join(folder_path, filename)
# 获取图片的原始宽高
with PILImage.open(image_path) as img:
width, height = img.size
aspect_ratio = width / height
# 调整图片尺寸
max_width = 6 * inch
if width > max_width:
width = max_width
height = width / aspect_ratio
else:
width = width
height = height
# 将PNG图片以原始比例添加到PDF中
img = Image(image_path, width, height)
elements.append(img)
# 生成PDF文件
doc.build(elements)
print(f"PDF '{folder_name}.pdf' 已生成.")
else:
print(f"文件夹 '{folder_name}' 没有找到任何PNG文件.")
运行结果
运行时可看见每一个pdf逐渐出现