Skip to content

Instantly share code, notes, and snippets.

@jb0hn
Last active August 29, 2024 13:37
Show Gist options
  • Save jb0hn/760447d7737555793efe48fb4192802c to your computer and use it in GitHub Desktop.
Save jb0hn/760447d7737555793efe48fb4192802c to your computer and use it in GitHub Desktop.
Rotate PDF file with PyPDF2
#!/usr/bin/env python3
import PyPDF2
pdfIn = open('original.pdf', 'rb') # exchange the 'original.pdf' with a name of your file
pdfReader = PyPDF2.PdfFileReader(pdfIn)
pdfWriter = PyPDF2.PdfFileWriter()
for pageNum in range(pdfReader.numPages):
page = pdfReader.getPage(pageNum)
page.rotateClockwise(90)
pdfWriter.addPage(page)
pdfOut = open('rotated.pdf', 'wb')
pdfWriter.write(pdfOut)
pdfOut.close()
pdfIn.close()
@awolad
Copy link

awolad commented Jan 11, 2022

@jb0hn Great! But how can write the file in the AWS s3 bucket?

@asafdaman
Copy link

asafdaman commented Aug 29, 2024

@jb0hn Really helpful!!
Some of the code written above are deprecated functions since PyPDF2 version 3.0.0.
Here is the same code but adapted:

@asafdaman
Copy link

fname = 'original.pdf' # exchange the 'original.pdf' with a name of your file
new_fname = fname.replace('.pdf', '_rotated.pdf')
pdfIn = open(fname, 'rb')
pdfReader = PyPDF2.PdfReader(pdfIn)
pdfWriter = PyPDF2.PdfWriter()

for page in pdfReader.pages:
    page.rotate(90)
    pdfWriter.add_page(page)

pdfOut = open(new_fname, 'wb')
pdfWriter.write(pdfOut)
pdfOut.close()
pdfIn.close()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment