文件按页进行拆分"/>
使用 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 文件按页进行拆分
发布评论