python使用PIL和fpdf库整理图片合并为PDF(版本2.0)

本文介绍了如何使用Python的PIL库处理图像,fpdf库生成PDF,以及os库操作文件系统,实现将一级目录下的多级子文件夹中的图片按名称顺序整理并添加到A4横向模式的PDF中,优化了文件处理速度和命名规则。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

提示:点击关注作者,以获取其他的最新消息推送


前言

最近在处理文档时,需要将发票文件批量打印,因此将之前的第一篇代码进行适当修改,升级为2.0版本。
新增功能:
1.原先的FPDF默认为A4竖向模式,现在添加进A4横向模式。
2.自动调整图片尺寸以适应A4页面。
3.去除temp以优化处理速度。
4.支持在一级目录下处理二级的图片文件夹。例如:work文件夹中的a,b,c…文件夹等。
5.自动输出的pdf文件自动命名为源文件夹的名字,例如:将work文件夹自动命名为work-1.pdf。


提示:以下是本篇文章正文内容,下面案例可供参考

一、PIL、fpdf、os是什么?

PIL 英文全称Python Imaging Library,是 Python 的图像处理库。
fpdf 是 Python PDF的库,可以用于创建PDF文件。
os函数主要处理文件系统中目录及相关文件的操作,

二、步骤

1.引入库

代码如下:

from PIL import Image
from fpdf import FPDF
import os

2.读取数据

代码如下:

# 读取待整理图片的文件路径
    Path = r'.\pdf\workspace2'
    list_Path = os.listdir(Path)

os.llist(path),将path下的文件变为列表。
这里的路径我使用了相对路径,你也可以设置为绝对路径,比如:D:\document_projects\pdf\workspace2


3.假设一级目录下包含多个二级文件夹(使用遍历方法)

代码如下:

    for subdir in list_Path:
        img_paths = os.path.join(Path, subdir)
        img_list = os.listdir(img_paths)
        output_path = os.path.join(Path, subdir + "-1.pdf")

4.按文件名顺序整理

代码如下:

    # 使用文件名的长度作为排序的关键
    sorted_img_list = sorted(img_list, key=lambda x: len(x))
    img_path_lists = []  #创建一个新的列表用于保存所有的图片路径
    for img in sorted_img_list:
        img_path = os.path.join(img_paths, img)
        img_path_lists.append(img_path)

sorted(list, key=lambda x: len(x)), 将list 中的文件按照长度排序。
list.apped(a) ,在list中添加a


5.创建PDF并按整理好的顺序添加图片(自定义函数)

导入横向图片进A4页面需要考虑的问题

代码如下:

def merge_images_to_pdf(image_paths, output_path):
    pdf = FPDF(unit='mm', format='A4', orientation='L')
    # 添加计数
    image_count = 0

    for image_path in image_paths:
        with Image.open(image_path) as image:
            image = image.convert('RGB')
            pdf.add_page()

            # 获取图片的原始尺寸
            width, height = image.size

            # 计算缩放比例以适合A4页面(同时保持纵横比)
            max_width = 210  # A4宽度
            max_height = 297  # A4高度
            if width > height:
                scale = max_height / width
            else:
                scale = max_width / height

            # 调整图片大小
            new_width = int(width * scale)
            new_height = int(height * scale)

            # 添加图片到PDF
            pdf.image(image_path, 0, 0, new_width, new_height)

            image_count += 1
            print(f"当前进度:第{image_count}张图片已添加到PDF中。")

    pdf.output(output_path, "F")
    print("图片转换为PDF成功!")

6.程序调用

代码如下:

        merge_images_to_pdf(img_path_lists, output_path)

7.附整体代码

代码如下:

from PIL import Image
from fpdf import FPDF
import os


def merge_images_to_pdf(image_paths, output_path):
    pdf = FPDF(unit='mm', format='A4', orientation='L')
    # 添加计数
    image_count = 0

    for image_path in image_paths:
        with Image.open(image_path) as image:
            image = image.convert('RGB')
            pdf.add_page()

            # 获取图片的原始尺寸
            width, height = image.size

            # 计算缩放比例以适合A4页面(同时保持纵横比)
            max_width = 210  # A4宽度
            max_height = 297  # A4高度
            if width > height:
                scale = max_height / width
            else:
                scale = max_width / height

            # 调整图片大小
            new_width = int(width * scale)
            new_height = int(height * scale)

            # 添加图片到PDF
            pdf.image(image_path, 0, 0, new_width, new_height)

            image_count += 1
            print(f"当前进度:第{image_count}张图片已添加到PDF中。")

    pdf.output(output_path, "F")
    print("图片转换为PDF成功!")


if __name__ == "__main__":
    # 读取待整理图片的文件路径
    Path = r'.\pdf\workspace2'
    list_Path = os.listdir(Path)
    for subdir in list_Path:
        img_paths = os.path.join(Path, subdir)
        img_list = os.listdir(img_paths)
        output_path = os.path.join(Path, subdir + "-1.pdf")
        # 使用文件名的长度作为排序的关键
        sorted_img_list = sorted(img_list, key=lambda x: len(x))
        img_path_lists = []
        for img in sorted_img_list:
            img_path = os.path.join(img_paths, img)
            img_path_lists.append(img_path)
        merge_images_to_pdf(img_path_lists, output_path)

8.运行结果

在这里插入图片描述
在这里插入图片描述

总结

以上就是今天要讲的内容,本文使用到Python中的 PIL、fpdf、os等函数。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值