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

相关推荐
山烛12 分钟前
KNN 算法中的各种距离:从原理到应用
人工智能·python·算法·机器学习·knn·k近邻算法·距离公式
guozhetao25 分钟前
【ST表、倍增】P7167 [eJOI 2020] Fountain (Day1)
java·c++·python·算法·leetcode·深度优先·图论
墨染点香31 分钟前
第七章 Pytorch构建模型详解【构建CIFAR10模型结构】
人工智能·pytorch·python
阿什么名字不会重复呢1 小时前
在线工具+网页平台来学习和操作Python与Excel相关技能
python·数据分析
Vertira1 小时前
python 阿里云 安装 dashscope的简介、安装
开发语言·python
gc_22992 小时前
学习Python中Selenium模块的基本用法(1:简介)
python·selenium
先做个垃圾出来………3 小时前
2116. 判断一个括号字符串是否有效
python
兮℡檬,3 小时前
房价预测|Pytorch
人工智能·pytorch·python
im_AMBER7 小时前
学习日志19 python
python·学习
mortimer10 小时前
安装NVIDIA Parakeet时,我遇到的两个Pip“小插曲”
python·github