Skip to content

Rotate pages

ozaru.rotate turns pages of a PDF clockwise and saves the result to another file:

import ozaru

# Turn the second page a quarter turn clockwise, into a new file.
ozaru.rotate("report.pdf", "rotated.pdf", 90, pages=[2])

for page in ozaru.page_info("rotated.pdf"):
    print(f"Page {page.number}: turned {page.rotation} degrees, {page.width:.0f} x {page.height:.0f}")

Output:

Page 1: turned 0 degrees, 595 x 842
Page 2: turned 90 degrees, 842 x 595
Page 3: turned 0 degrees, 595 x 842

The arguments are the PDF to read, the file to write and the degrees to turn, a multiple of 90. Use a negative number to turn pages counterclockwise: -90 is the same as 270.

Without pages, every page is turned. With it, only the pages listed are, counted from 1, as page_info numbers them. A page number the PDF doesn't have raises an IndexError, and the output file isn't written.

Turning adds to the rotation a page already has: turning by 90 a page shown at 90 degrees leaves it at 180. Only how viewers show the page changes; its content, text and images stay as they are.

The output can be the same file as the input: ozaru reads the whole PDF before writing.

What the new file keeps

The new file has the whole document: its pages, bookmarks, links, forms and metadata. ozaru writes it again from the objects the document uses, so objects left over from earlier edits are not copied, and the file can come out smaller.

There are two exceptions:

  • A protected PDF is saved without its password, so pass the password argument to rotate it. Anyone can then open the new file.
  • A damaged page that can't be read is saved as an empty page of its size, and a PageWarning tells you its number, as in Handle errors.

Keep the original bytes

By default ozaru writes the whole file again. With incremental=True, it keeps every byte of the original and adds only the pages it changed at the end, as PDF editors do when they save:

ozaru.rotate("signed.pdf", "signed.pdf", 90, incremental=True)

Use it for PDFs with a digital signature: a signature covers the bytes of the file, so rewriting it breaks the signature, while adding to it doesn't. The earlier version of the document stays in the file too.

A protected PDF and a damaged one can't be updated this way: ozaru raises a ValueError and writes nothing. Save them without incremental=True.

Next: extract and split pages.