Python 3 PyPDF2 Library Script to Rotate PDF Clockwise or AntiClockWise at any Angle Full Project For Beginners

Python 3 PyPDF2 Library Script to Rotate PDF Clockwise or AntiClockWise at any Angle Full Project For Beginners

 

Welcome folks today in this blog post we will be rotating pdf file at any direction using python script. All the full source code of the application will be given below.

 

 

 

Get Started

 

 

 

In order to get started we need to install the following library using the pip command as shown below

 

pip install pypdf2

 

After installing this library make an app.py file and copy paste the following code

 

app.py

 

 

from PyPDF2 import PdfFileReader, PdfFileWriter
from os import listdir

input_dir = "uploads/"
output_dir = "output/"

for x in listdir(input_dir):
    if not x.endswith('.pdf'):
        continue
    pdf_in = open(input_dir + x, 'rb')
    pdf_reader = PdfFileReader(pdf_in)
    pdf_writer = PdfFileWriter()
    for pagenum in range(pdf_reader.numPages):
        page = pdf_reader.getPage(pagenum)
        page.rotateClockwise(270)
        pdf_writer.addPage(page)
    pdf_out = open(output_dir + x, 'wb')
    pdf_writer.write(pdf_out)
    pdf_out.close()
    pdf_in.close()

 

See also  Python 3 Kivy Flappy Bird Clone Game GUI Desktop App Full Project For Beginners

 

In this above python script we are importing the pypdf2 library and then we are using the following methods to rotate the pdf file

 

page.rotateCounterClockwise(270) : Here we are rotating the pdf file in anticlockwise direction at an angle of 270

 

page.rotateClockwise(270): Here we are rotating the pdf file in clockwise direction at an angle of 270

 

Now after this make two directories inside your root folder which is uploads/ and output/ as shown below

 

 

 

 

See also  Python 3 Script to Convert PDF Document to Images Using pdf2image Library Full Example

 

Here inside the uploads/ directory we have stored the input pdf file that is not rotated and after the script execution the output file will be stored inside the output/ folder

 

So now if you execute this python script app.py by typing the below command

 

python app.py

 

 

 

 

Leave a Reply