Search code examples
pythonpdfpypdf

Batch rotate PDF files with PyPDF2


I've been working on a code to batch rotate PDF files inside a folder, but I can't find a way to iterate and change the destination folder of the rotated file.

My intention is to save the new file with the same name in another folder.

from os import listdir

from PyPDF2 import PdfReader, PdfWriter

# Collect files
root = "C:\z_PruebPy\pdf"
archs = []
for x in listdir(root):
    archs.append(root + x)

# Batch rotate
for arch in archs:
    pdf_in = open(arch, "rb")
    reader = PdfReader(pdf_in)
    writer = PdfWriter()

    for page in reader.pages:
        page.rotate_clockwise(270)
        writer.add_page(page)

    with open(arch, "wb") as pdf_out:  # ????????
        writer.write(pdf_out)
    pdf_in.close()

Solution

  • You have to give PdfFileWriter a file pointer to the new location. Also you don't need to create a list and iterate on the list, just iterate on os.listdir results. Finally you had unused variables, like loc. I cleaned your code a bit.

    So this should work, assuming you create the output folder :

    from os import listdir
    from PyPDF2 import PdfReader, PdfWriter
    
    input_dir  = "C:\\z_PruebPy\\pdf\\"
    output_dir = "C:\\z_PruebPy\\output_pdf\\"
    
    for fname in listdir(input_dir):
        if not fname.endswith(".pdf"):  # ignore non-pdf files
            continue
        reader = PdfReader(input_dir + fname)
        writer = PdfWriter()
        for page in reader.pages:
            # page.rotate_clockwise(270) # (before pypdf3.0 - deprecated - thanks to Maciejg for the update)
            page.rotate(270)
            writer.add_page(page)
        with open(output_dir + fname, "wb") as pdf_out:
            writer.write(pdf_out)