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

相关推荐
搏博6 分钟前
将图形可视化工具的 Python 脚本打包为 Windows 应用程序
开发语言·windows·python·matplotlib·数据可视化
硅基茶水间20 分钟前
「轻量级AI编程桌面软件」代码上下文一键搞定|已开源
python
Hockor1 小时前
写给前端的 Python 教程三(字符串驻留和小整数池)
前端·后端·python
网安小张1 小时前
解锁FastAPI与MongoDB聚合管道的性能奥秘
数据库·python·django
GeekAGI1 小时前
Python 定时器框架
python
KENYCHEN奉孝1 小时前
Pandas和Django的示例Demo
python·django·pandas
拾零吖1 小时前
《Pytorch深度学习实践》ch8-多分类
人工智能·pytorch·python
亿牛云爬虫专家1 小时前
NLP驱动网页数据分类与抽取实战
python·分类·爬虫代理·电商·代理ip·网页数据·www.goofish.com
weixin_466485112 小时前
PyCharm中运行.py脚本程序
ide·python·pycharm
Jay_272 小时前
python项目如何创建docker环境
开发语言·python·docker