Python 3 Script to Rotate PDF Files Using PyPDF2 Library Full Tutorial For Beginners

 

Welcome folks today in this blog post we will be rotating 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 PDFrotate(origFileName, newFileName, rotation): 

    # creating a pdf File object of original pdf 
    pdfFileObj = open(origFileName, 'rb') 
    
    # creating a pdf Reader object 
    pdfReader = PyPDF2.PdfFileReader(pdfFileObj) 

    # creating a pdf writer object for new pdf 
    pdfWriter = PyPDF2.PdfFileWriter() 
    
    # rotating each page 
    for page in range(pdfReader.numPages): 

        # creating rotated page object 
        pageObj = pdfReader.getPage(page) 
        pageObj.rotateClockwise(rotation) 

        # adding rotated page object to pdf writer 
        pdfWriter.addPage(pageObj) 

    # new pdf file object 
    newFile = open(newFileName, 'wb') 
    
    # writing rotated pages to new file 
    pdfWriter.write(newFile) 

    # closing the original pdf file object 
    pdfFileObj.close() 
    
    # closing the new pdf file object 
    newFile.close() 
    

def main(): 

    # original pdf file name 
    origFileName = 'fancy.pdf'
    
    # new pdf file name 
    newFileName = 'rotated_example.pdf'
    
    # rotation angle 
    rotation = 270
    
    # calling the PDFrotate function 
    PDFrotate(origFileName, newFileName, rotation) 
    
if __name__ == "__main__": 
    # calling the main function 
    main()

 

READ  Python 3 Email Keylogger GUI Desktop App Script Using Pygame and Smtplib Library Which Sends Keystrokes Logs as Email 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