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
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 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
# 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() |
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