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

相关推荐
Niuguangshuo13 分钟前
Python 设计模式:访问者模式
python·设计模式·访问者模式
Jamesvalley15 分钟前
【Django】新增字段后兼容旧接口 This field is required
后端·python·django
Luck_ff08101 小时前
【Python爬虫详解】第四篇:使用解析库提取网页数据——BeautifuSoup
开发语言·爬虫·python
学渣676561 小时前
什么时候使用Python 虚拟环境(venv)而不用conda
开发语言·python·conda
悲喜自渡7211 小时前
线性代数(一些别的应该关注的点)
python·线性代数·机器学习
陌殇殇2 小时前
Java使用IText7动态生成带审批文本框的PDF文档
java·pdf
Huanzhi_Lin2 小时前
python源码打包为可执行的exe文件
python
声声codeGrandMaster2 小时前
django之账号管理功能
数据库·后端·python·django
娃娃略2 小时前
【AI模型学习】双流网络——更强大的网络设计
网络·人工智能·pytorch·python·神经网络·学习
LCY1333 小时前
python 与Redis操作整理
开发语言·redis·python