python:PyPDF2 将多个图片转换为pdf,再合并成一个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

......

pip install Pillow

pip install pypdf2

pypdf2-3.0.1-py3-none-any.whl (232 kB)

将多个图片转换为pdf,再合并成一个PDF文件

编写 merge_pdf2.py 如下

python 复制代码
# -*- coding: utf-8 -*-
""" PyPDF2 将多个图片转换为pdf,再合并成一个PDF文件 """
import os
import re
from PIL import Image
from PyPDF2 import PdfMerger

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

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

def trans_jpg2pdf(jpg_list: list) -> list:
    """jpg图片转换成 pdf
      Args:
        jpg_list (list): 图片文件列表

      Returns:
        list: 图片转换后的 pdf文件列表
    """
    pdf_list = []
    for jpg in jpg_list:
        jpg_path = os.path.join(images_dir, jpg)
        pdf_file = revise(jpg) # 修正后的pdf文件名
        pdf_path = os.path.join(tmpdir, pdf_file)
        if os.path.exists(pdf_path):
            os.remove(pdf_path)
        pdf_list.append(pdf_path)
        im = Image.open(jpg_path)
        im.save(pdf_path, 'PDF', resolution=100.0)
    return pdf_list

def merge_pdf(pdf_list: list, result_pdf: str = "result.pdf"):
    """ 合并 pdf文件
      Args:
        pdf_list (list): pdf文件列表
        result_pdf (str): 合并后的 pdf文件名称
    """
    sorted_list = sorted(pdf_list)
    f_merger = PdfMerger()
    for pdf in sorted_list:
        print(pdf)
        f_merger.append(pdf)
    if os.path.exists(result_pdf):
        os.remove(result_pdf)
    f_merger.write(result_pdf)


if __name__ == '__main__':
    jpg_list = [f for f in os.listdir(images_dir) if f.endswith(".jpg") or f.endswith(".png")]
    pdf_list = trans_jpg2pdf(jpg_list)
    merge_pdf(pdf_list, "result.pdf")

运行 python merge_pdf2.py

生成 result.pdf ,打开 result.pdf 看不见"文本水印"了。

相关推荐
AI数据皮皮侠23 分钟前
中国各省森林覆盖率等数据(2000-2023年)
大数据·人工智能·python·深度学习·机器学习
西柚小萌新2 小时前
【深入浅出PyTorch】--3.1.PyTorch组成模块1
人工智能·pytorch·python
2401_841495643 小时前
【数据结构】红黑树的基本操作
java·数据结构·c++·python·算法·红黑树·二叉搜索树
西猫雷婶3 小时前
random.shuffle()函数随机打乱数据
开发语言·pytorch·python·学习·算法·线性回归·numpy
♛小小小让让4 小时前
RabbitMQ (二)参数
笔记·python·rabbitmq
fly-phantomWing4 小时前
在命令提示符页面中用pip命令行安装Python第三方库的详细步骤
开发语言·python·pip
万粉变现经纪人4 小时前
如何解决 pip install 安装报错 ImportError: cannot import name ‘xxx’ from ‘yyy’ 问题
python·selenium·测试工具·flask·scikit-learn·fastapi·pip
深栈4 小时前
机器学习:线性回归
人工智能·pytorch·python·机器学习·线性回归·sklearn
simon_skywalker5 小时前
第三章 字典与集合
python
gc_22996 小时前
学习Python中Selenium模块的基本用法(18:使用ActionChains操作鼠标)
python·selenium