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 看不见"文本水印"了。

相关推荐
luthane22 分钟前
python 实现algorithm topo卡恩拓扑算法
数据结构·python·算法
坚持学习的你1 小时前
Jax(Random、Numpy)常用函数
人工智能·pytorch·python·jax
ZPC82101 小时前
Pytorch详解-Pytorch核心模块
人工智能·pytorch·python·深度学习·机器学习
985小水博一枚呀1 小时前
【深度学习基础模型】极限学习机(Extreme Learning Machines, ELM)详细理解并附实现代码。
人工智能·python·深度学习·极限学习机
985小水博一枚呀1 小时前
【深度学习基础模型】液态状态机(Liquid State Machines, LSM)详细理解并附实现代码。
人工智能·python·rnn·深度学习
码农超哥同学2 小时前
Python知识点:如何使用KubeEdge与Python进行容器化边缘计算
开发语言·python·面试·编程·边缘计算
无敌の星仔2 小时前
一个月学会Java 第7天 字符串与键盘输入
java·开发语言·python
心易行者2 小时前
ChatGPT 与 CoT 思维链:如何重塑 AI 的逻辑大脑?
开发语言·python
小白熊_XBX2 小时前
机器学习可视化教程——混淆矩阵与回归图
人工智能·python·机器学习·矩阵·回归·sklearn
_.Switch3 小时前
自动机器学习(AutoML):实战项目中的应用与实现
人工智能·python·机器学习·自然语言处理·架构·scikit-learn