Python 3 Script to Split PDF File Pages into Multiple PDF Files Using PyPDF2 Library Full Tutorial For Beginners

Python 3 Script to Split PDF File Pages into Multiple PDF Files Using PyPDF2 Library Full Tutorial For Beginners

 

Welcome folks today in this blog post we will be splitting multiple pdf pages into multiple pdf files in python 3 using pypdf2 library. All the source code of the project will be given below.

 

 

Requirements

 

 

python 3 should be installed on your system

 

pypdf2 library should be installed on your system

 

 

Installation

 

 

In order to install pypdf2 library we can use the pip command to install

 

pip install pypdf2

 

After installing it you can make a app.py file inside the root directory and copy paste the following code

 

 

app.py

 

 

 

# importing the required modules 
import PyPDF2 

def PDFsplit(pdf, splits): 
    # creating input pdf file object 
    pdfFileObj = open(pdf, 'rb') 
    
    # creating pdf reader object 
    pdfReader = PyPDF2.PdfFileReader(pdfFileObj) 
    
    # starting index of first slice 
    start = 0
    
    # starting index of last slice 
    end = splits[0] 
    
    
    for i in range(len(splits)+1): 
        # creating pdf writer object for (i+1)th split 
        pdfWriter = PyPDF2.PdfFileWriter() 
        
        # output pdf file name 
        outputpdf = pdf.split('.pdf')[0] + str(i) + '.pdf'
        
        # adding pages to pdf writer object 
        for page in range(start,end): 
            pdfWriter.addPage(pdfReader.getPage(page)) 
        
        # writing split pdf pages to pdf file 
        with open(outputpdf, "wb") as f: 
            pdfWriter.write(f) 

        # interchanging page split start position for next split 
        start = end 
        try: 
            # setting split end position for next split 
            end = splits[i+1] 
        except IndexError: 
            # setting split end position for last split 
            end = pdfReader.numPages 
        
    # closing the input pdf file object 
    pdfFileObj.close() 
            
def main(): 
    # pdf file to split 
    pdf = 'output2.pdf'
    
    # split page positions 
    splits = [2,4] 
    
    # calling PDFsplit function to split pdf 
    PDFsplit(pdf, splits) 

if __name__ == "__main__": 
    # calling the main function 
    main()

 

READ  Python Tkinter GUI Script to Make a Basic Calculator in Sweet UI Full Project For Beginners

 

 

Now if you execute this python script app.py by running this command like below

 

python app.py

 

 

You can see the result like this

 

 

 

 

 

 

Leave a Reply