使用 Python 将 PDF 文件按页进行拆分

编程入门 行业动态 更新时间:2024-10-26 22:23:02

使用 Python 将 PDF <a href=https://www.elefans.com/category/jswz/34/1771438.html style=文件按页进行拆分"/>

使用 Python 将 PDF 文件按页进行拆分

""" 用途:将一个 PDF 文件按页拆分为多个 PDF 文件注意事项:若报错 ModuleNotFoundError: No module named 'PyPDF2'则需要先安装该模块。使用命令 “pip install PyPDF2” 安装即可
"""import PyPDF2  # 需要先安装:pip/pip3 install PyPDF2
import osroot = r'C:\Users\liujieru\Documents\pdf'  # 源文件所在的绝对路径
file_path = os.path.join(root, '组合.pdf')pdf_file = open(file_path, 'rb')  # 获取原 PDF 文件
pdf_reader = PyPDF2.PdfFileReader(pdf_file)  # 创建 PDF 对象
source_name = pdf_file.name  # 获取源文件名称,包含绝对路径pdf_writer = PyPDF2.PdfFileWriter()  # 创建一个空白 PDF 对象for page_num in range(pdf_reader.numPages):  # 将每页内容分别写入一个新文件page_obj = pdf_reader.getPage(page_num)pdf_writer.addPage(page_obj)  # 向空白 PDF 对象中添加要复制的 PDF页面new_name = source_name[:-4] + str(page_num) + ".pdf"pdf_new_file = open(new_name, 'wb')  # 创建一个新文件pdf_writer.write(pdf_new_file)  # 将添加了内容的空白 PDF 对象,写入到新建文件中pdf_new_file.close()pdf_writer.__init__()  # 将 PDF 对象初始化pdf_file.close()

更多推荐

使用 Python 将 PDF 文件按页进行拆分

本文发布于:2023-06-28 13:45:44,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/928379.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文件   Python   PDF

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!