Python 3 pdfrw Library Tutorial to Rotate Pages of PDF Document Full Project For Beginners



Welcome folks today in this blog post we will be rotating pdf pages in python using pdfrw library. All the full source code of the application is shown below.




Get Started




In order to get started you need to install the below library using the below pip command as shown below



pip install pdfrw



After installing this library you need to make an file and copy paste the following code



#!/usr/bin/env python

usage: my.pdf rotation [page[range] ...]
         eg. 270 1-3 5 7-9
        Rotation must be multiple of 90 degrees, clockwise.
Creates with selected pages rotated.  Rotates all by default.

import sys
import os

from pdfrw import PdfReader, PdfWriter

inpfn = sys.argv[1]
rotate = sys.argv[2]
ranges = sys.argv[3:]

rotate = int(rotate)
assert rotate % 90 == 0

ranges = [[int(y) for y in x.split('-')] for x in ranges]
outfn = 'rotate.%s' % os.path.basename(inpfn)
trailer = PdfReader(inpfn)
pages = trailer.pages

if not ranges:
    ranges = [[1, len(pages)]]

for onerange in ranges:
    onerange = (onerange + onerange[-1:])[:2]
    for pagenum in range(onerange[0]-1, onerange[1]):
        pages[pagenum].Rotate = (int(pages[pagenum].inheritable.Rotate or
                                     0) + rotate) % 360

outdata = PdfWriter(outfn)
outdata.trailer = trailer

Leave a Reply