python:reportlab 将多个图片合并成一个PDF文件

承上一篇:java:pdfbox 3.0 去除扫描版PDF中文本水印

导出扫描版PDF文件中每页的图片文件

java -jar pdfbox-app-3.0.3.jar export:images -prefix=test -i your_book.pdf

导出

Writing image: test-1.jpg

Writing image: test-2.jpg

Writing image: test-3.png

......

在日常工作中,我们经常需要将多张图片合并成一个PDF文件,以便于分享或打印。Python作为一种强大的编程语言,提供了丰富的库和工具,使得这一任务变得非常简单。在本文中,我们将介绍如何使用Python合并多张图片并生成一个PDF文件的方法。我们需要安装两个库:Pillow 和ReportLab。Pillow 用于处理图片,ReportLab 用于生成PDF文件。

pip install Pillow

pip install reportlab

reportlab-4.2.2-py3-none-any.whl (1.9 MB)

编写 merge_pdf1.py 如下

python 复制代码
# -*- coding: utf-8 -*-
""" reportLab 将多个图片合并成一个PDF文件 """
import os
from PIL import Image
from reportlab.pdfgen import canvas

images_dir = "." # imgs
tmpdir = r"\tmp" # Win 10

def revise(s):
    """ 修正图片文件名中的数字,假设0<页数<=999 """
    prefix = s[0:5]
    d = s.split('-')[1].split('.')[0]
    ext = s.split('.')[1]
    # 数字前补零
    if len(d) ==1:
        d = '00'+d
    elif len(d) ==2:
        d = '0' +d
    else:
        pass
    filename = prefix + d +'.'+ext
    os.rename(s, filename)
    return filename

def merge_images_to_pdf(image_list, output_pdf):
    """ 使用画布 """
    c = canvas.Canvas(output_pdf)
    for image in image_list:
        print(image)
        img = Image.open(image)
        c.setPageSize((img.width, img.height))
        c.drawInlineImage(image, 0, 0)
        c.showPage()
    c.save()

# main()
# 图片路径列表
img_list = [f for f in os.listdir(images_dir) if f.endswith(".jpg") or f.endswith(".png")]
imgs_list = []
for img in img_list:
    imgs_list.append(revise(img))
# 修正img文件名后排序
imgs_list = sorted(imgs_list)
# 输出PDF文件路径
output_path = os.path.join(tmpdir, 'result.pdf')
merge_images_to_pdf(imgs_list, output_path)

运行 python merge_pdf1.py

生成 \tmp\result.pdf

在这段代码中,我们首先导入了必要的库。然后定义了一个名为 merge_images_to_pdf 的函数,该函数将接受一个图片列表和输出PDF文件的路径作为参数。在函数中,我们使用 Pillow库打开每张图片,并将其逐一添加到PDF中。最后,我们保存生成的PDF文件。

相关推荐
前端精髓20 小时前
结构化输出with_structured_output(抽卡)
python·langchain
尹人入圣21 小时前
目前热门的IP驱动产业新场景新工具
网络·python·网络协议·tcp/ip
Nuanyt1 天前
Agent 学习笔记(下篇三):上线工程、进阶选择与操作界面(Stage 7 / 7.5 / 8 + 延伸路线)
笔记·python·学习·memory·aiagent·harness
吴卫斌1 天前
定投ETF实战指南(四):行业/主题ETF——定投的“进攻端“
开发语言·python·股票·量化
2601_967987371 天前
Python——入门级(定义功能def函数)
python·函数·可变参数·默认参数·关键字参数
专注仿真1 天前
梯度提升类(XFBoost)算法详解与代码实例
开发语言·人工智能·python·算法·大模型训练·控制算法
外收内放1 天前
Python基础语法练习题(75)
开发语言·python·学习
黑十1 天前
PyTorch 报 “no CUDA GPUs are available“ 怎么办?3 步排查
服务器·网络·人工智能·pytorch·python
threelab1 天前
开源图片去水印代码
python
taller_20001 天前
【012】数据类型入门: Excel 数据到 Python 值的转换
python·excel·pie·py