Python - Split PDF Files
Python - Split PDF Files
CODE
#Import Modules required for the PDF Splitting operation
from PyPDF2 import PdfFileReader, PdfFileWriter
#Provide the Input and Output Folder and Files
inputFolder = "C:\\Test\\Simple Kettle\\Programs\\work\\input"
outputFolder = "C:\\Test\\Simple Kettle\\Programs\\work\\output"
inputFile = inputFolder + "\\input.pdf"
#Function definition: This will take care of splitting the input file.
def splitPDFFile():
#Open the input pdf file in the binary format.
with open(inputFile, 'rb') as f:
#Read the pdf file.
r = PdfFileReader(f)
#Loop through the different pages of the pdf file. In the below for loop, the i starts from 0 and go up to the maximum pages.
for i in range(0, r.getNumPages()):
print("Splitting Page_" + str(i+1))
#Start a PDF Writer object.
w = PdfFileWriter()
#Add the current page to the PDF Writer object.
w.addPage(r.getPage(i))
#Open and Write the writer object contents to a new pdf output file.
#If 4 pages are there in the input file, it will be splitted into 4 different pdf files.
#The iteration variable "i" controls the naming of the pdf output files.
with open(outputFolder + "\\output_" + str(i+1) + ".pdf", "wb") as result:
w.write(result)
#Invoke the function
splitPDFFile()
Comments
Post a Comment