需要安裝PyPDF2庫,
pip3 install PyPDF2
代碼如下:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from PyPDF2 import PdfFileReader, PdfFileWriter
import os
def split_pdf(infile, out_path):
"""
:param infile: 待拆分的pdf文件
:param out_path: 拆分成單頁的pdf文件的存儲路徑
:return: 無
"""
if not os.path.exists(out_path):
os.makedirs(out_path)
with open(infile, 'rb') as infile:
reader = PdfFileReader(infile)
number_of_pages = reader.getNumPages() #計算此PDF文件中的頁數
for i in range(number_of_pages):
writer = PdfFileWriter()
writer.addPage(reader.getPage(i))
out_file_name = out_path + str(i+1)+'.pdf'
with open(out_file_name, 'wb') as outfile:
writer.write(outfile)
if __name__ == '__main__':
in_File = './Schedule.pdf'
out_Path = './PDF試驗/單頁的/' # 生成輸出文件夾
split_pdf(in_File, out_Path)