Python小工具(3)-按照时间顺序将多个png整合成一个pdf
import os
from PIL import Image
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import letter
def get_sorted_images(folder_path):
# 获取所有图像文件及其最后修改时间
images = [(filename, os.path.getmtime(os.path.join(folder_path, filename)))
for filename in os.listdir(folder_path)
if filename.endswith(('.jpg', '.png', '.jpeg'))]
# 按照最后修改时间对文件进行排序
images.sort(key=lambda x: x[1])
return [os.path.join(folder_path, img[0]) for img in images]
def create_pdf(images, output_pdf):
c = canvas.Canvas(output_pdf, pagesize=letter)
width, height = letter
for img_path in images:
try:
img = Image.open(img_path)
img_width, img_height = img.size
aspect = img_height / float(img_width)
# 调整图片大小以适应PDF页面大小
img_width = width
img_height = (width * aspect)
if img_height > height:
img_height = height
img_width = (height / aspect)
# 居中图片
x = (width - img_width) / 2
y = (height - img_height) / 2
c.drawImage(img_path, x, y, img_width, img_height)
c.showPage()
except IOError:
print("无法处理图片: ", img_path)
c.save()
if __name__ == "__main__":
folder_path = r'E:\c++' # 替换为您的文件夹路径
output_pdf = r'E:\c++\c.pdf' # 替换为输出PDF文件的路径
images = get_sorted_images(folder_path)
create_pdf(images, output_pdf)
修改路径,安装对应的库,运行即可。