寒窗轩,寒川的个人网络博客,记录互联网事,学习网络编程、分享工作经验、人生感悟,包括但不限于程序代码、数据库、Office办公、随笔等内容。

python读取文件夹下图片并生成pdf文件

如何用python读取文件夹下的图片并生成pdf文件?这或许是一个比较常见的需求,市面上很多图片转pdf的软件,各有千秋。怎么用python实现这一功能?废话不多说,直接上代码。

from reportlab.lib.pagesizes import A4
from reportlab.pdfgen import canvas
from PIL import Image
import os

def get_image_paths_from_folder(folder_path):
    # 定义支持的图片文件扩展名
    image_extensions = {".png", ".jpg", ".jpeg", ".bmp", ".gif", ".tiff"}
    
    # 初始化一个空列表来存储图片路径
    image_paths = []
    
    # 遍历文件夹中的所有文件
    for filename in os.listdir(folder_path):
        # 获取文件的完整路径
        file_path = os.path.join(folder_path, filename)
        
        # 检查文件是否是图片文件(通过扩展名判断)
        if os.path.isfile(file_path) and os.path.splitext(file_path)[1].lower() in image_extensions:
            image_paths.append(file_path)
    return image_paths

def images_to_pdf(image_paths, output_pdf):
    # 创建一个新的PDF文件
    c = canvas.Canvas(output_pdf, pagesize=A4)
    width, height = A4  # A4纸的宽度和高度

    for image_path in image_paths:
        img = Image.open(image_path)
        img_width, img_height = img.size

        # 根据图片尺寸调整在PDF中的位置
        if img_width > img_height:
            # 如果是横图,旋转90度
            img = img.rotate(90, expand=True)
            img_width, img_height = img.size

        # 计算图片在PDF中的缩放比例
        ratio = min(width / img_width, height / img_height)
        img_width *= ratio
        img_height *= ratio

        # 计算图片在PDF中的位置
        x = (width - img_width) / 2
        y = (height - img_height) / 2

        # 将图片插入到PDF中
        c.drawImage(image_path, x, y, width=img_width, height=img_height)
        c.showPage()  # 新的一页

    c.save()  # 保存PDF文件

# 示例使用
image_paths = get_image_paths_from_folder("images")  # 图片文件路径列表
output_pdf = "output.pdf"  # 输出的PDF文件名

images_to_pdf(image_paths, output_pdf)


程序 2024-12-20 14:45:23 47 2 3206 pythonpdf图片
文章写得不错?我是土豪我要在线打赏!
在线打赏

昵称:

验证码:验证码

评论:

文章分类
系统
程序
数据
Office
随笔
热门文章
VB.net开发的word转pdf的小工具
使用python把word转成pdf
文章推荐
免责声明
关于博主
开篇第一章
随机推荐
EMlog再次升级了
网站模板对SEO(搜索引擎优化)的影响
帮朋友诚聘php程序员
MySQL数据库的concat()函数为什么返回空
2020开局不顺
windows xp win7双系统引导wubi安装ubuntu linux
调整PHP和MySQL的时区,实现同步显示中国时间
准备写点专业的东东
Google今天收录博客了
Windows如何隐藏CMD命令运行窗口
友情连接
春燕网络
谢润的博客
企安文库