import os from PyPDF2 import PdfFileReader, PdfFileWriter dir_name = '保存文件目录' if not os.path.exists(dir_name): os.mkdir(dir_name)
# 用pypdf2分割PDF pdf_reader = PdfFileReader('./111.pdf') for page in range(pdf_reader.getNumPages()): # 读取所有页数 从0开始 pdf_writer = PdfFileWriter() pdf_writer.addPage(pdf_reader.getPage(page)) with open(dir_name + '/{}.pdf'.format(page+1), 'wb') as f: pdf_writer.write(f)
# 用pypdf2 将分割后的pdf进行合并 pdf_writer = PdfFileWriter() # 要合并的PDF数量 for page in range(1, 10): pdf_reader = PdfFileReader(dir_name + '/{}.pdf'.format(page+1)) # 每个PDF的页数 for page in range(pdf_reader.getNumPages()): pdf_writer.addPage(pdf_reader.getPage(page)) with open('merged0.pdf', 'wb') as w: pdf_writer.write(w)