[PYTHON/PYPDF] PDF 파일 분할하기
■ PDF 파일을 분할하는 방법을 보여준다. ▶ main.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
import os from PyPDF2 import PdfReader from PyPDF2 import PdfWriter def splitPDFFile(sourceFilePath, targetDirectoryPath, pageCountPerFile): pdfReader = PdfReader(sourceFilePath) totalPageCount = len(pdfReader.pages) if not os.path.exists(targetDirectoryPath): os.makedirs(targetDirectoryPath) fileNameWithoutExtension = os.path.splitext(os.path.basename(sourceFilePath))[0] for i in range(0, totalPageCount, pageCountPerFile): pdfWriter = PdfWriter() for page in range(i, min(i + pageCountPerFile, totalPageCount)): pdfWriter.add_page(pdfReader.pages[page]) targetFileName = f"{fileNameWithoutExtension}_part_{i//pageCountPerFile + 1}.pdf" targetFilePath = os.path.join(targetDirectoryPath, targetFileName) with open(targetFilePath, "wb") as bufferedWriter: pdfWriter.write(bufferedWriter) print(f"Created : {targetFileName}") print("PDF splitting completed.") sourceFilePath = "d:\\Practical C# Charts and Graphics.pdf" targetDirectoryPath = "d:\\Practical C# Charts and Graphics" pageCountPerFile = 100 splitPDFFile(sourceFilePath, targetDirectoryPath, pageCountPerFile) |
▶ requirements.txt
1 2 3 |
PyPDF2==3.0.1 |
※ pip install pypdf2 명령을 실행했다.