Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I rotate a page in pyPDF2?

Tags:

python

pypdf2

I'm editing a PDF file with pyPDF2. I managed to generate the PDF I want but I've yet to rotate some pages.

I went to the documentation and found two methods: rotateClockwise and rotateCounterClockwise, and while they say the parameter is an int, I can't make it work. Python says:

TypeError: unsupported operand type(s) for +: 'IndirectObject' and 'int'

To produce this error:

from PyPDF2 import PdfFileReader, PdfFileWriter


reader = PdfFileReader("example.pdf")

with open("out.pdf", "wb") as fh:
    writer = PdfFileWriter(fh)
    page = reader.getPage(0)
    page.rotateCounterClockwise(90)
    writer.addPage(page)

I can't find someone explaining the procedure. There is, however, a question in stackoverflow but the answer's just vague.

like image 513
Ignacio Tiraboschi Avatar asked Mar 06 '17 00:03

Ignacio Tiraboschi


2 Answers

This was a known bug with the rotateClockwise function. This was fixed.

For older versions of PyPDF2: Just edit the '_rotate' method in your pdf.py with this fix

def _rotate(self, angle):
    rotateObj = self.get("/Rotate", 0)
    currentAngle = rotateObj if isinstance(rotateObj, int) else rotateObj.getObject()
    self[NameObject("/Rotate")] = NumberObject(currentAngle + angle)
like image 144
Norsk Avatar answered Oct 16 '22 21:10

Norsk


Try replacing your three lines with this:

output.addPage(input1.getPage(i).rotateCounterClockwise(90))

I think the rotate has to be done to a getPage call and not on the "extracted" page.

like image 1
James C. Taylor Avatar answered Oct 16 '22 21:10

James C. Taylor