利用PyPDF2模块快速拆分PDF文档
利用PyPDF2模块快速拆分PDF文档,
自动查找py文件所在的目录里的pdf文件,并将拆分后的文件放到当前目录中。
from PyPDF2 import PdfFileReader, PdfFileWriter import os pdf_dir=[] def get_filepath(): docunames = os.listdir() for docuname in docunames: if os.path.splitext(docuname)[1] == \'.pdf\': pdf_dir.append(docuname) def current_path(): current_path = os.path.abspath(__file__) return os.path.abspath(os.path.dirname(current_path) + os.path.sep + ".") # 将PDF文件每页分割为一个单独pdf的文件,并pdf保存至当前目录中 def pdf_split_1(pdf_input, path_output): fname = os.path.splitext(os.path.basename(pdf_input))[0] # 获取pdf文件名,去掉后缀名 pdf = PdfFileReader(pdf_input) for page in range(pdf.getNumPages()): pdf_writer = PdfFileWriter() pdf_writer.addPage(pdf.getPage(page)) output_filename = path_output + r\'\{}-{}.pdf\'.format(fname, page+1) with open(output_filename, \'wb\') as out: pdf_writer.write(out) # print(\'生成文件:{}\'.format(output_filename)) if __name__ == "__main__": get_filepath() pdffile = os.path.join(current_path(),"".join(pdf_dir)) pdf_split_1(pdffile, current_path())
版权声明:本文为ken-yu原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。