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文件。

相关推荐
FreakStudio5 小时前
全网最适合入门的面向对象编程教程:56 Python字符串与序列化-正则表达式和re模块应用
python·单片机·嵌入式·面向对象·电子diy
丶21365 小时前
【CUDA】【PyTorch】安装 PyTorch 与 CUDA 11.7 的详细步骤
人工智能·pytorch·python
_.Switch6 小时前
Python Web 应用中的 API 网关集成与优化
开发语言·前端·后端·python·架构·log4j
一个闪现必杀技6 小时前
Python入门--函数
开发语言·python·青少年编程·pycharm
小鹿( ﹡ˆoˆ﹡ )7 小时前
探索IP协议的神秘面纱:Python中的网络通信
python·tcp/ip·php
卷心菜小温7 小时前
【BUG】P-tuningv2微调ChatGLM2-6B时所踩的坑
python·深度学习·语言模型·nlp·bug
陈苏同学7 小时前
4. 将pycharm本地项目同步到(Linux)服务器上——深度学习·科研实践·从0到1
linux·服务器·ide·人工智能·python·深度学习·pycharm
唐家小妹7 小时前
介绍一款开源的 Modern GUI PySide6 / PyQt6的使用
python·pyqt
墨染辉7 小时前
pdf处理2
pdf