承上一篇: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 如下
# -*- coding: utf-8 -*-
""" reportLab 将多个图片合并成一个PDF文件 """
import os
from PIL import Image
from reportlab.pdfgen import canvasimages_dir = "." # imgs
tmpdir = r"\tmp" # Win 10def revise(s):""" 修正图片文件名中的数字,假设0<页数<=999 """prefix = s[0:5]d = s.split('-')[1].split('.')[0]ext = s.split('.')[1]# 数字前补零if len(d) ==1:d = '00'+delif len(d) ==2:d = '0' +delse:passfilename = prefix + d +'.'+extos.rename(s, filename)return filenamedef 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文件。