Python小工具(3)-按照时间顺序将多个png整合成一个pdf

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)

修改路径,安装对应的库,运行即可。

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值