Counting the number of PDF pages Do you need to count the total number of pages in your pdf files?
Rotate PDF files with PyPdf2 and Tkinter!
Rotating PDF files with PyPDF2 and Tkinter
Sometimes we need simple tools to get the job done. At work, we have people that use pdf files daily, on which they need to perform certain manual operations. One of these operations is rotating pages. Thinking of programming a pdf rotator can look quite massive at first, but is it really?
To build our tool, we need to rotate the pdf in three ways, clockwise, counterclockwise and 180 degrees. For simplicity, we want to rotate all pdf files in our current working directory. The user shall also be able to use the finished script, without installing Python or any dependencies on Windows. Let us walk through the steps in creating our tool.
Step 1 - PyPDF2 for rotating pages
Rotating a pdf with PyPDF2 can be done with the PageObject class's method RotateClockwise. The method takes one Int parameter,
anglewhich defines the rotation degrees. Note that the angle have to be specified in incremetns of 90°. There is no possibility of rotating a PDF page for example 55°.
Ok, we know how to rotate our page, now we need to load our PDF file into memory. After that, we need to initialize our PdfFileReader and PdfFileWriter objects. We can then loop through our pages by using the readers numPages variable. We get the page, rotate it, write it to our new PDF and then save it to disc.
with open("test.pdf", "rb") as pdf_file:
pdf_reader = PyPDF2.PdfFileReader(pdf_file)
pdf_writer = PyPDF2.PdfFileWriter()
for page_num in range(pdf_reader.numPages):
pdf_page = pdf_reader.getPage(page_num)
with open("test_rotated.pdf", "wb") as pdf_file_rotated:
Step 2 - Giving the user an interface
GUI is better than CLI for the average user. To easily create our interface, we use Tkinter. We need three Radiobuttons for specifying the rotations, Left, Right and 180 degrees. We also need some kind of descripte text to guide the user, as well as a Button for being able to start the rotation. See the code comments for further descriptions.
Step 3 - Getting the files
We want to rotate all pdf files in the folder where our script is contained.
Step 4 - Putting it all together
Here is the complete code for rotating our pdf files. Enjoy!